feat: 维护台 maintain(巡检/补号/日志)+ 配置与 .gitignore
- Flask 控制台:Cliproxy 巡检、批量补号、流水线、运行日志 - codex_stats_oauth_dir 支持统计 Cliproxy auth 目录 - 忽略 accounts/oauth、.venv、本地 DB/日志与 new.py Made-with: Cursor
This commit is contained in:
1 parent
ebef9acd7c
commit
a089da31cd
22 files changed
+3127
-39
No files matched your search
@@ -0,0 +1,33 @@
|
||||
# CPA 定时 runner(scripts/cpa_runner.py)— 复制为 .env.cpa-runner 或写入仓库根 .env
|
||||
# 若已用 `python -m maintain` 并开启「流水线 → 定时」,请勿再跑本脚本。
|
||||
# 状态文件默认与维护台一致:maintain/data/pipeline_state.json(可用 STATE_FILE 覆盖)
|
||||
|
||||
# 必填:注册脚本(默认本仓库 run.py)
|
||||
# RUN_SCRIPT=/home/ubt/protocol_chatgpt/run.py
|
||||
|
||||
# OAuth JSON 源目录(run.py 写入处)
|
||||
# OAUTH_DIR=/home/ubt/protocol_chatgpt/accounts/oauth
|
||||
|
||||
# 同步目标(Docker/CPA 消费端读此目录)
|
||||
# TARGET_DIR=/www/wwwroot/docker/cpa/auths
|
||||
|
||||
# Python 解释器
|
||||
# PYTHON_BIN=python3
|
||||
|
||||
# 定时间隔(分钟)
|
||||
# RUN_EVERY_MINUTES=10
|
||||
|
||||
# run.py 子进程超时(秒),默认 480
|
||||
# RUN_SUBPROCESS_TIMEOUT_SEC=480
|
||||
|
||||
# 未迁出任何 json 时:发钉钉后是否退出进程(1=与旧版一致,适合 systemd 重启;0=scheduler 继续跑)
|
||||
# CPA_EXIT_ON_EMPTY=1
|
||||
|
||||
# 状态 / 日志 / 锁文件(默认 maintain/data/ 下)
|
||||
# STATE_FILE=
|
||||
# LOG_FILE=
|
||||
# LOCK_FILE=
|
||||
|
||||
# 钉钉机器人(可选,不填则跳过通知)
|
||||
# DINGTALK_WEBHOOK=
|
||||
# DINGTALK_SECRET=
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
# 虚拟环境
|
||||
.venv/
|
||||
venv/
|
||||
|
||||
# Python
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*.so
|
||||
.Python
|
||||
|
||||
# 密钥与环境(示例文件可提交)
|
||||
.env
|
||||
.env.*
|
||||
!.env.cpa-runner.example
|
||||
|
||||
# 账号 OAuth / 失败记录(含 token,切勿提交)
|
||||
accounts/oauth/*
|
||||
!accounts/oauth/.gitkeep
|
||||
accounts/failed/*
|
||||
!accounts/failed/.gitkeep
|
||||
|
||||
# 迁出目录
|
||||
export/
|
||||
|
||||
# 维护台本地数据(库与日志)
|
||||
maintain/data/*.db
|
||||
maintain/data/*.log
|
||||
maintain/data/pipeline_state.json
|
||||
maintain/data/*.lock
|
||||
!maintain/data/.gitkeep
|
||||
|
||||
# 本地草稿
|
||||
new.py
|
||||
@@ -37,3 +37,94 @@ protocol_bot/
|
||||
├── oauth_login.py # 协议级 OAuth 登录模块
|
||||
└── README.md
|
||||
```
|
||||
|
||||
## 一条命令跑整条流水线(推荐)
|
||||
|
||||
维护台把 **CPA 统计 / 补号 / 子进程 run.py / 迁出 JSON / 钉钉** 收在一个进程里:
|
||||
|
||||
```bash
|
||||
pip install -r requirements.txt
|
||||
export CODEX_MAINTAIN_PASSWORD='你的密码' # 默认 admin
|
||||
export CODEX_MAINTAIN_SECRET='随机长串' # 生产务必设置
|
||||
python -m maintain
|
||||
# 本机浏览器: http://127.0.0.1:8765
|
||||
```
|
||||
|
||||
### 用服务器公网 IP 访问不到 8765
|
||||
|
||||
默认 **`CODEX_MAINTAIN_HOST=127.0.0.1`**,进程只接受本机连接,**用别的机器浏览器打 `http://IP:8765` 会连不上**。
|
||||
|
||||
1. 启动前监听所有网卡:
|
||||
|
||||
```bash
|
||||
export CODEX_MAINTAIN_HOST=0.0.0.0
|
||||
export CODEX_MAINTAIN_PORT=8765 # 可选
|
||||
python -m maintain
|
||||
# 或 .venv/bin/python -m maintain
|
||||
```
|
||||
|
||||
2. **放行端口**:云厂商安全组 / 本机 `ufw allow 8765/tcp` 或 `iptables` 等。
|
||||
|
||||
3. 仍不通时用 `ss -tlnp | grep 8765`(或 `netstat`)确认进程是否在 `0.0.0.0:8765` 监听。
|
||||
|
||||
4. 公网暴露务必强密码 + `CODEX_MAINTAIN_SECRET`;更好是前面加 **Nginx + HTTPS** 或 **SSH 隧道** / 仅内网访问。
|
||||
|
||||
### 服务器上 `pip install` 报 SSL / 连不上 PyPI
|
||||
|
||||
若出现 `SSLEOFError`、`EOF occurred in violation of protocol`、`Could not find a version that satisfies the requirement flask`,多半是到 **pypi.org** 的 HTTPS 被墙、劫持或本机证书过旧,**不是** Flask 真的不存在。
|
||||
|
||||
1. **换国内镜像再装**(推荐先试清华):
|
||||
|
||||
```bash
|
||||
.venv/bin/pip install -U pip setuptools wheel
|
||||
.venv/bin/pip install -r requirements.txt \
|
||||
-i https://pypi.tuna.tsinghua.edu.cn/simple \
|
||||
--trusted-host pypi.tuna.tsinghua.edu.cn
|
||||
```
|
||||
|
||||
其它镜像可把域名换成:`https://mirrors.aliyun.com/pypi/simple/`(`--trusted-host mirrors.aliyun.com`)。
|
||||
|
||||
2. **更新系统 CA**(Debian/Ubuntu):`sudo apt-get update && sudo apt-get install -y ca-certificates`
|
||||
|
||||
3. 若机房**必须走 HTTP 代理**,先 `export https_proxy=...` 再执行 pip。
|
||||
|
||||
4. **Python 版本**:维护台依赖 Flask 3,需 **Python ≥ 3.8**;能升到 3.10+ 更省心(`python3.10 -m venv .venv`)。
|
||||
|
||||
| 页签 | 能力 |
|
||||
|------|------|
|
||||
| **任务中心** | 巡检:管理 API 探测 + 删失效本地 JSON;仍有缺口则**自动进程内批量注册**(每批 ≤ `max_auto_register_per_tick`,与手动补号**同一把 REGISTER_LOCK**) |
|
||||
| **流水线** | **仅**定时/手动的 `run.py`→迁出;**不再**由巡检触发。仍按当前统计的有效缺口决定是否执行 |
|
||||
| **代理池 / 配置** | Cliproxy **管理 Base** + **Key**;若成功账号 JSON **已迁入 CPA auth 目录**,务必填 **`codex_stats_oauth_dir`** 为该目录绝对路径(与 Manager 列表一致),否则统计/巡检仍只扫项目内 `accounts/oauth`,会一直像 0 个号 |
|
||||
|
||||
- **巡检**一把锁(INSPECT_LOCK);**子进程流水线**一把锁(PIPELINE_LOCK);**所有批量注册**(手动 + 巡检跟进)共 **REGISTER_LOCK**。
|
||||
- 巡检与批量注册、流水线若并行可能争写 `accounts/oauth`,建议错峰。
|
||||
- 状态文件:`maintain/data/pipeline_state.json`;业务库:`maintain/data/maintain.db`。
|
||||
- **日志**:维护台进程内任务写 `maintain/data/maintain_runtime.log`;流水线(`run.py` 输出等)写 `maintain/data/pipeline.log`(可在 SQLite `pipeline_log_file` 改路径)。Web 页签 **「运行日志」** 可拉取文件尾;亦可 SSH 执行 `tail -f`。
|
||||
- 设置项 **`codex_stats_oauth_dir`**:维护台统计、巡检探测、按失败删 JSON 的目录。留空 = `accounts/oauth`;与 Cliproxy **同机**且文件最终在 **`~/.cli-proxy-api/`** 等目录时,填该绝对路径。自定义目录下 JSON 若无 `type` 字段也会计入(Cliproxy 落盘常见);默认目录仍要求 `type=codex`。
|
||||
- 新注册写入的 oauth JSON 会带 `cpa_id` / `cpa_code`;无 `cpa_id` 的旧文件计入唯一账号池(id=1)。默认只预置一条「账号池」;若仍使用**旧版库里的两条 CPA**,可自行在 SQLite 里删掉多余行或合并目标。
|
||||
|
||||
### 验证补号链路(不真实请求 OpenAI)
|
||||
|
||||
在虚拟环境里执行(会 mock `run._do_one`,只测 `run_batch` 并行、成功计数、`register context` 清理):
|
||||
|
||||
```bash
|
||||
python3 -m venv .venv && .venv/bin/pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple --trusted-host pypi.tuna.tsinghua.edu.cn
|
||||
.venv/bin/python -m maintain.verify_batch_register
|
||||
```
|
||||
|
||||
应输出 `verify_batch_register: OK ...`。**真实注册**仍依赖代理、邮箱服务等:在维护台用「开始批量注册」先试 `count=1`,或巡检后看是否出现 `inspect_register` 任务并观察成功/失败数。
|
||||
|
||||
## 可选:独立 cpa_runner 进程
|
||||
|
||||
若不跑维护台、只想要旧版「定时子进程 + 迁文件」,仍可用 `scripts/cpa_runner.py` + `.env.cpa-runner`(见 `.env.cpa-runner.example`)。**维护台已开启「定时流水线」时不要同时跑本脚本。**
|
||||
|
||||
### systemd(仅维护台)
|
||||
|
||||
```ini
|
||||
[Service]
|
||||
WorkingDirectory=/home/ubt/protocol_chatgpt
|
||||
EnvironmentFile=/home/ubt/protocol_chatgpt/.env
|
||||
Environment=CODEX_MAINTAIN_HOST=0.0.0.0
|
||||
ExecStart=/home/ubt/protocol_chatgpt/.venv/bin/python -m maintain
|
||||
Restart=on-failure
|
||||
```
|
||||
Whitespace-only changes.
Whitespace-only changes.
+213
-33
@@ -1,55 +1,232 @@
|
||||
"""临时邮箱服务 - mail.chatgpt.org.uk API"""
|
||||
"""临时邮箱 — [GPTMail](https://mail.chatgpt.org.uk) 网页模拟
|
||||
|
||||
对外接口:
|
||||
- create_temp_email() -> Optional[str]
|
||||
- fetch_emails(email_address) -> list[dict]
|
||||
- wait_for_code(email_address, timeout=120) -> Optional[str]
|
||||
|
||||
通过网页同款鉴权(/api/inbox-token + X-Inbox-Token)访问收件接口,
|
||||
避免 API key 配额限制。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import time
|
||||
from typing import Optional, Tuple
|
||||
from typing import Optional
|
||||
|
||||
import requests
|
||||
import urllib3
|
||||
|
||||
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
|
||||
GPTMAIL_BASE = "https://mail.chatgpt.org.uk"
|
||||
|
||||
BASE_URL = "https://mail.chatgpt.org.uk/api"
|
||||
HEADERS = {
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
|
||||
"Origin": "https://mail.chatgpt.org.uk",
|
||||
"Referer": "https://mail.chatgpt.org.uk/",
|
||||
# 当前进程内:本脚本创建的邮箱 -> 会话信息
|
||||
_MAIL_STATE: dict[str, dict] = {}
|
||||
|
||||
UA = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136 Safari/537.36"
|
||||
|
||||
def _gptmail_headers() -> dict:
|
||||
return {
|
||||
"User-Agent": UA,
|
||||
"Accept": "application/json",
|
||||
}
|
||||
|
||||
|
||||
def _normalize_gptmail_message(raw: dict) -> dict:
|
||||
"""统一成 extract_code / wait_for_code 可用的字段"""
|
||||
sender = (raw.get("from_address") or raw.get("from") or "").strip()
|
||||
mid = raw.get("id")
|
||||
text = raw.get("content") or raw.get("text") or ""
|
||||
html = raw.get("html_content") or raw.get("html") or ""
|
||||
return {
|
||||
"id": mid,
|
||||
"from": sender,
|
||||
"sender": sender,
|
||||
"subject": raw.get("subject", "") or "",
|
||||
"text_content": text,
|
||||
"html_content": html,
|
||||
"content": text,
|
||||
"body": text,
|
||||
"date": raw.get("created_at") or raw.get("timestamp"),
|
||||
}
|
||||
|
||||
|
||||
def _new_session() -> requests.Session:
|
||||
s = requests.Session()
|
||||
s.headers.update(_gptmail_headers())
|
||||
return s
|
||||
|
||||
|
||||
def _bootstrap_session(session: requests.Session) -> bool:
|
||||
"""先访问首页拿 gm_sid,后续 inbox-token 才会通过"""
|
||||
try:
|
||||
r = session.get(
|
||||
f"{GPTMAIL_BASE}/",
|
||||
headers={
|
||||
"Referer": f"{GPTMAIL_BASE}/",
|
||||
"Origin": GPTMAIL_BASE,
|
||||
**_gptmail_headers(),
|
||||
},
|
||||
timeout=20,
|
||||
)
|
||||
return r.status_code == 200
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _refresh_inbox_token(session: requests.Session, email: str = "") -> Optional[dict]:
|
||||
r = session.post(
|
||||
f"{GPTMAIL_BASE}/api/inbox-token",
|
||||
json={"email": (email or "").strip().lower()},
|
||||
headers={
|
||||
"Content-Type": "application/json",
|
||||
"Referer": f"{GPTMAIL_BASE}/",
|
||||
"Origin": GPTMAIL_BASE,
|
||||
**_gptmail_headers(),
|
||||
},
|
||||
timeout=20,
|
||||
)
|
||||
if r.status_code != 200:
|
||||
return None
|
||||
try:
|
||||
body = r.json()
|
||||
except Exception:
|
||||
return None
|
||||
if not body.get("success"):
|
||||
return None
|
||||
auth = body.get("auth") or {}
|
||||
if not isinstance(auth, dict):
|
||||
return None
|
||||
token = (auth.get("token") or "").strip()
|
||||
if not token:
|
||||
return None
|
||||
return {
|
||||
"token": token,
|
||||
"email": (auth.get("email") or "").strip().lower(),
|
||||
"expires_at": int(auth.get("expires_at") or 0),
|
||||
}
|
||||
|
||||
|
||||
def _auth_fetch(
|
||||
session: requests.Session,
|
||||
method: str,
|
||||
path: str,
|
||||
*,
|
||||
auth_email: str,
|
||||
params: dict | None = None,
|
||||
json_data: dict | None = None,
|
||||
) -> requests.Response:
|
||||
auth = _refresh_inbox_token(session, auth_email)
|
||||
headers = {}
|
||||
if auth and auth.get("token"):
|
||||
headers["X-Inbox-Token"] = auth["token"]
|
||||
return session.request(
|
||||
method,
|
||||
f"{GPTMAIL_BASE}{path}",
|
||||
params=params,
|
||||
json=json_data,
|
||||
headers=headers,
|
||||
timeout=20,
|
||||
)
|
||||
|
||||
|
||||
def _gptmail_fetch_detail(session: requests.Session, email_address: str, email_id: str) -> Optional[dict]:
|
||||
r = _auth_fetch(session, "GET", f"/api/email/{email_id}", auth_email=email_address)
|
||||
if r.status_code != 200:
|
||||
return None
|
||||
try:
|
||||
body = r.json()
|
||||
except Exception:
|
||||
return None
|
||||
if not body.get("success"):
|
||||
return None
|
||||
data = body.get("data") or {}
|
||||
return data if isinstance(data, dict) else None
|
||||
|
||||
|
||||
def _gptmail_create_email() -> Optional[str]:
|
||||
session = _new_session()
|
||||
if not _bootstrap_session(session):
|
||||
print("[email] GPTMail 会话初始化失败")
|
||||
return None
|
||||
r = _auth_fetch(session, "GET", "/api/generate-email", auth_email="")
|
||||
try:
|
||||
body = r.json()
|
||||
except Exception:
|
||||
print(f"[email] GPTMail 响应非 JSON: HTTP {r.status_code}")
|
||||
return None
|
||||
|
||||
if not body.get("success"):
|
||||
err = body.get("error") or body.get("message") or r.text[:200]
|
||||
print(f"[email] GPTMail 创建失败: {err}")
|
||||
return None
|
||||
|
||||
data = body.get("data") or {}
|
||||
email = (data.get("email") or "").strip()
|
||||
if not email or "@" not in email:
|
||||
print("[email] GPTMail 返回缺少 email")
|
||||
return None
|
||||
|
||||
_MAIL_STATE[email] = {
|
||||
"provider": "gptmail",
|
||||
"session": session,
|
||||
}
|
||||
return email
|
||||
|
||||
|
||||
def create_temp_email() -> Optional[str]:
|
||||
"""创建临时邮箱,返回邮箱地址"""
|
||||
try:
|
||||
r = requests.get(
|
||||
f"{BASE_URL}/generate-email",
|
||||
headers={**HEADERS, "Content-Type": "application/json"},
|
||||
timeout=10,
|
||||
verify=False,
|
||||
)
|
||||
if r.status_code == 200:
|
||||
data = r.json()
|
||||
if data.get("success") and data.get("data", {}).get("email"):
|
||||
return data["data"]["email"]
|
||||
return _gptmail_create_email()
|
||||
except Exception as e:
|
||||
print(f"[email] 创建失败: {e}")
|
||||
return None
|
||||
|
||||
|
||||
def fetch_emails(email_address: str) -> list[dict]:
|
||||
"""获取邮件列表"""
|
||||
"""获取邮件列表(统一输出字典列表)"""
|
||||
state = _MAIL_STATE.get(email_address)
|
||||
if not state or state.get("provider") != "gptmail":
|
||||
return []
|
||||
|
||||
session = state.get("session")
|
||||
if not isinstance(session, requests.Session):
|
||||
session = _new_session()
|
||||
_bootstrap_session(session)
|
||||
state["session"] = session
|
||||
|
||||
try:
|
||||
ts = int(time.time() * 1000)
|
||||
r = requests.get(
|
||||
f"{BASE_URL}/emails?email={email_address}&_t={ts}",
|
||||
headers={**HEADERS, "Cache-Control": "no-cache"},
|
||||
timeout=30,
|
||||
verify=False,
|
||||
r = _auth_fetch(
|
||||
session,
|
||||
"GET",
|
||||
"/api/emails",
|
||||
auth_email=email_address,
|
||||
params={"email": email_address},
|
||||
)
|
||||
if r.status_code == 200:
|
||||
data = r.json()
|
||||
if data.get("success") and data.get("data", {}).get("emails"):
|
||||
return data["data"]["emails"]
|
||||
if r.status_code != 200:
|
||||
return []
|
||||
|
||||
body = r.json()
|
||||
if not body.get("success"):
|
||||
return []
|
||||
|
||||
data = body.get("data") or {}
|
||||
members = data.get("emails") or []
|
||||
if not isinstance(members, list):
|
||||
return []
|
||||
|
||||
out: list[dict] = []
|
||||
for msg in members:
|
||||
if not isinstance(msg, dict):
|
||||
continue
|
||||
mid = msg.get("id")
|
||||
detail = msg
|
||||
if mid and not (msg.get("content") or msg.get("html_content")):
|
||||
d = _gptmail_fetch_detail(session, email_address, mid)
|
||||
if d:
|
||||
detail = {**msg, **d}
|
||||
|
||||
out.append(_normalize_gptmail_message(detail))
|
||||
|
||||
return out
|
||||
except Exception as e:
|
||||
print(f"[email] 获取邮件错误: {e}")
|
||||
return []
|
||||
@@ -74,8 +251,8 @@ def extract_code(email_data: dict) -> Optional[str]:
|
||||
if m:
|
||||
return m.group(1)
|
||||
# 独立6位数字
|
||||
clean = re.sub(r'<[^>]+>', ' ', content)
|
||||
m = re.search(r'\b(\d{6})\b', clean)
|
||||
clean = re.sub(r"<[^>]+>", " ", content)
|
||||
m = re.search(r"\b(\d{6})\b", clean)
|
||||
if m and m.group(1) != "177010":
|
||||
return m.group(1)
|
||||
return None
|
||||
@@ -93,7 +270,10 @@ def wait_for_code(email_address: str, timeout: int = 120) -> Optional[str]:
|
||||
seen.add(mid)
|
||||
sender = str(mail.get("from", "") or mail.get("sender", "")).lower()
|
||||
subject = str(mail.get("subject", "")).lower()
|
||||
if any(k in sender or k in subject for k in ("openai", "chatgpt", "verification")):
|
||||
if any(
|
||||
k in sender or k in subject
|
||||
for k in ("openai", "chatgpt", "verification", "noreply")
|
||||
):
|
||||
code = extract_code(mail)
|
||||
if code:
|
||||
return code
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
"""Codex 自动维护 Web 控制台"""
|
||||
@@ -0,0 +1,4 @@
|
||||
from maintain.app import main
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+864
@@ -0,0 +1,864 @@
|
||||
#!/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/<int:pid>")
|
||||
@require_login
|
||||
def api_proxies_del(pid: int):
|
||||
db.delete_proxy(pid)
|
||||
return jsonify({"ok": True})
|
||||
|
||||
|
||||
@app.put("/api/cpas/<int:cid>")
|
||||
@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()
|
||||
@@ -0,0 +1,60 @@
|
||||
"""调用现有 run 模块执行批量注册(写入 cpa_id / cpa_code)"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
import threading
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
from typing import Callable, Optional
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
if ROOT not in sys.path:
|
||||
sys.path.insert(0, ROOT)
|
||||
|
||||
from register import RegisterConfig
|
||||
|
||||
import run as run_module
|
||||
|
||||
|
||||
def run_batch(
|
||||
*,
|
||||
count: int,
|
||||
threads: int,
|
||||
proxy: str,
|
||||
skip_oauth: bool,
|
||||
cpa_id: int,
|
||||
cpa_code: str,
|
||||
on_progress: Optional[Callable[[int, int], None]] = None,
|
||||
) -> tuple[int, int]:
|
||||
"""
|
||||
执行 count 次注册,返回 (success, failed)。
|
||||
on_progress(done, total) 每完成 1 个账号回调一次(并行时顺序不定)。
|
||||
"""
|
||||
run_module._counter["success"] = 0
|
||||
run_module._counter["failed"] = 0
|
||||
run_module.set_register_context(cpa_id=cpa_id, cpa_code=cpa_code)
|
||||
try:
|
||||
config = RegisterConfig(proxy=proxy or "")
|
||||
th = max(1, min(int(threads), int(count)))
|
||||
prog_lock = threading.Lock()
|
||||
completed = {"n": 0}
|
||||
|
||||
def one(i: int) -> None:
|
||||
run_module._do_one(i, config, proxy or "", skip_oauth)
|
||||
if on_progress:
|
||||
with prog_lock:
|
||||
completed["n"] += 1
|
||||
on_progress(completed["n"], count)
|
||||
|
||||
if th <= 1:
|
||||
for i in range(1, count + 1):
|
||||
one(i)
|
||||
else:
|
||||
with ThreadPoolExecutor(max_workers=th) as ex:
|
||||
futs = {ex.submit(one, i): i for i in range(1, count + 1)}
|
||||
for fut in as_completed(futs):
|
||||
fut.result()
|
||||
|
||||
return run_module._counter["success"], run_module._counter["failed"]
|
||||
finally:
|
||||
run_module.clear_register_context()
|
||||
@@ -0,0 +1,109 @@
|
||||
"""Cliproxy 管理 API:与 Web 管理台相同的 auth 文件连通性探测。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from urllib.parse import quote, urljoin
|
||||
|
||||
import requests
|
||||
|
||||
_MANAGEMENT_PREFIX = "/v0/management"
|
||||
|
||||
|
||||
def normalize_management_base(raw: str) -> str:
|
||||
base = (raw or "").strip()
|
||||
if not base:
|
||||
return ""
|
||||
base = re.sub(r"/?v0/management/?$", "", base, flags=re.IGNORECASE)
|
||||
base = base.rstrip("/")
|
||||
if not re.match(r"^https?://", base, re.IGNORECASE):
|
||||
base = "http://" + base
|
||||
return base
|
||||
|
||||
|
||||
def management_api_root(base: str) -> str:
|
||||
b = normalize_management_base(base)
|
||||
if not b:
|
||||
return ""
|
||||
return b.rstrip("/") + _MANAGEMENT_PREFIX
|
||||
|
||||
|
||||
def probe_auth_file_models(
|
||||
management_base: str,
|
||||
management_key: str,
|
||||
auth_file_name: str,
|
||||
*,
|
||||
timeout_sec: float = 30.0,
|
||||
) -> tuple[bool, str]:
|
||||
"""
|
||||
请求 GET .../v0/management/auth-files/models?name=<name>
|
||||
与 Cli-Proxy-API-Management-Center 中 getModelsForAuthFile 一致。
|
||||
"""
|
||||
root = management_api_root(management_base)
|
||||
if not root or not management_key.strip():
|
||||
return False, "未配置管理地址或密钥"
|
||||
name = (auth_file_name or "").strip()
|
||||
if not name:
|
||||
return False, "文件名为空"
|
||||
url = urljoin(root + "/", "auth-files/models")
|
||||
url = f"{url}?name={quote(name, safe='')}"
|
||||
try:
|
||||
r = requests.get(
|
||||
url,
|
||||
headers={"Authorization": f"Bearer {management_key.strip()}"},
|
||||
timeout=timeout_sec,
|
||||
)
|
||||
except requests.RequestException as e:
|
||||
return False, str(e)[:200]
|
||||
if r.status_code == 200:
|
||||
return True, ""
|
||||
tail = (r.text or "")[:300].replace("\n", " ")
|
||||
return False, f"HTTP {r.status_code} {tail}".strip()
|
||||
|
||||
|
||||
def verify_management_auth(
|
||||
management_base: str,
|
||||
management_key: str,
|
||||
*,
|
||||
timeout_sec: float = 15.0,
|
||||
) -> tuple[bool, str]:
|
||||
"""先拉 auth-files,密钥错误或不可达时勿对单文件做删除类操作。"""
|
||||
root = management_api_root(management_base)
|
||||
if not root or not management_key.strip():
|
||||
return False, "未配置管理地址或密钥"
|
||||
url = urljoin(root + "/", "auth-files")
|
||||
try:
|
||||
r = requests.get(
|
||||
url,
|
||||
headers={"Authorization": f"Bearer {management_key.strip()}"},
|
||||
timeout=timeout_sec,
|
||||
)
|
||||
except requests.RequestException as e:
|
||||
return False, str(e)[:200]
|
||||
if r.status_code == 200:
|
||||
return True, ""
|
||||
return False, f"HTTP {r.status_code}"
|
||||
|
||||
|
||||
def probe_auth_file_models_for_oauth_stem(
|
||||
management_base: str,
|
||||
management_key: str,
|
||||
oauth_json_stem: str,
|
||||
*,
|
||||
timeout_sec: float = 30.0,
|
||||
) -> tuple[bool, str]:
|
||||
"""先按 oauth 文件名(无 .json)探测,再试带 .json,与常见 Cliproxy 命名一致。"""
|
||||
stem = (oauth_json_stem or "").strip()
|
||||
if not stem:
|
||||
return False, "文件名为空"
|
||||
names = [stem]
|
||||
if not stem.lower().endswith(".json"):
|
||||
names.append(f"{stem}.json")
|
||||
last_err = ""
|
||||
for name in names:
|
||||
ok, err = probe_auth_file_models(
|
||||
management_base, management_key, name, timeout_sec=timeout_sec
|
||||
)
|
||||
if ok:
|
||||
return True, ""
|
||||
last_err = err
|
||||
return False, last_err
|
||||
@@ -0,0 +1,453 @@
|
||||
"""
|
||||
流水线:子进程执行 run.py → 将 accounts/oauth/*.json 迁到目标目录 → 可选钉钉通知。
|
||||
|
||||
- 独立进程:`python scripts/cpa_runner.py`(读环境变量 / .env)
|
||||
- 嵌入维护台:由 `maintain.app` 调用 `execute_pipeline_cycle`,配置来自 SQLite
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import time
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable, Optional
|
||||
from urllib.parse import quote_plus
|
||||
|
||||
import requests
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parent.parent
|
||||
|
||||
logger = logging.getLogger("cpa-runner")
|
||||
|
||||
|
||||
def load_env(path: Path) -> None:
|
||||
if not path.exists():
|
||||
return
|
||||
for line in path.read_text(encoding="utf-8").splitlines():
|
||||
line = line.strip()
|
||||
if not line or line.startswith("#") or "=" not in line:
|
||||
continue
|
||||
key, value = line.split("=", 1)
|
||||
os.environ.setdefault(key.strip(), value.strip())
|
||||
|
||||
|
||||
load_env(REPO_ROOT / ".env")
|
||||
load_env(REPO_ROOT / ".env.cpa-runner")
|
||||
|
||||
|
||||
def env_int(name: str, default: int) -> int:
|
||||
value = os.getenv(name, str(default)).strip()
|
||||
try:
|
||||
return int(value)
|
||||
except ValueError:
|
||||
return default
|
||||
|
||||
|
||||
def env_bool(name: str, default: bool) -> bool:
|
||||
v = os.getenv(name, "").strip().lower()
|
||||
if not v:
|
||||
return default
|
||||
return v in ("1", "true", "yes", "on")
|
||||
|
||||
|
||||
@dataclass
|
||||
class RunnerConfig:
|
||||
run_script: Path
|
||||
oauth_dir: Path
|
||||
target_dir: Path
|
||||
python_bin: str = "python3"
|
||||
dingtalk_webhook: str = ""
|
||||
dingtalk_secret: str = ""
|
||||
exit_on_zero_moved: bool = True
|
||||
subprocess_timeout_sec: int = 60 * 8
|
||||
state_file: Path = REPO_ROOT / "maintain" / "data" / "pipeline_state.json"
|
||||
log_file: Path = REPO_ROOT / "maintain" / "data" / "cpa_runner.log"
|
||||
lock_file: Path = REPO_ROOT / "maintain" / "data" / "cpa_runner.lock"
|
||||
|
||||
|
||||
def runner_config_from_env() -> RunnerConfig:
|
||||
return RunnerConfig(
|
||||
run_script=Path(
|
||||
os.getenv("RUN_SCRIPT", str(REPO_ROOT / "run.py"))
|
||||
).resolve(),
|
||||
oauth_dir=Path(
|
||||
os.getenv("OAUTH_DIR", str(REPO_ROOT / "accounts" / "oauth"))
|
||||
).resolve(),
|
||||
target_dir=Path(
|
||||
os.getenv(
|
||||
"TARGET_DIR",
|
||||
str(REPO_ROOT / "export" / "cpa_auths"),
|
||||
)
|
||||
).resolve(),
|
||||
python_bin=os.getenv("PYTHON_BIN", "python3"),
|
||||
dingtalk_webhook=os.getenv("DINGTALK_WEBHOOK", "").strip(),
|
||||
dingtalk_secret=os.getenv("DINGTALK_SECRET", "").strip(),
|
||||
exit_on_zero_moved=env_bool("CPA_EXIT_ON_EMPTY", True),
|
||||
subprocess_timeout_sec=env_int("RUN_SUBPROCESS_TIMEOUT_SEC", 60 * 8),
|
||||
state_file=Path(
|
||||
os.getenv(
|
||||
"STATE_FILE",
|
||||
str(REPO_ROOT / "maintain" / "data" / "pipeline_state.json"),
|
||||
)
|
||||
).resolve(),
|
||||
log_file=Path(
|
||||
os.getenv(
|
||||
"LOG_FILE",
|
||||
str(REPO_ROOT / "maintain" / "data" / "cpa_runner.log"),
|
||||
)
|
||||
).resolve(),
|
||||
lock_file=Path(
|
||||
os.getenv(
|
||||
"LOCK_FILE",
|
||||
str(REPO_ROOT / "maintain" / "data" / "cpa_runner.lock"),
|
||||
)
|
||||
).resolve(),
|
||||
)
|
||||
|
||||
|
||||
CONFIG = runner_config_from_env()
|
||||
|
||||
DEFAULT_STATE: dict[str, Any] = {
|
||||
"last_run_at": None,
|
||||
"last_notify_at": None,
|
||||
"last_run_moved": 0,
|
||||
"last_run_return_code": None,
|
||||
"last_stdout_tail": "",
|
||||
"last_stderr_tail": "",
|
||||
"last_error": "",
|
||||
}
|
||||
|
||||
LOCK_HANDLE: Any = None
|
||||
|
||||
|
||||
def _setup_cli_logging(cfg: RunnerConfig) -> None:
|
||||
cfg.log_file.parent.mkdir(parents=True, exist_ok=True)
|
||||
if logger.handlers:
|
||||
return
|
||||
logger.setLevel(logging.INFO)
|
||||
fmt = logging.Formatter("%(asctime)s [%(levelname)s] %(message)s")
|
||||
fh = logging.FileHandler(cfg.log_file, encoding="utf-8")
|
||||
fh.setFormatter(fmt)
|
||||
sh = logging.StreamHandler()
|
||||
sh.setFormatter(fmt)
|
||||
logger.addHandler(fh)
|
||||
logger.addHandler(sh)
|
||||
|
||||
|
||||
def ensure_pipeline_file_handler(cfg: RunnerConfig) -> None:
|
||||
"""
|
||||
嵌入维护台时 cpa-runner 可能已有 StreamHandler 而无 FileHandler;
|
||||
保证流水线日志写入 cfg.log_file(run.py 输出等)。
|
||||
"""
|
||||
cfg.log_file.parent.mkdir(parents=True, exist_ok=True)
|
||||
logger.setLevel(logging.INFO)
|
||||
fmt = logging.Formatter("%(asctime)s [%(levelname)s] %(message)s")
|
||||
want = str(cfg.log_file.resolve())
|
||||
for h in logger.handlers:
|
||||
if isinstance(h, logging.FileHandler):
|
||||
try:
|
||||
if os.path.abspath(h.baseFilename) == want:
|
||||
return
|
||||
except (OSError, ValueError, AttributeError):
|
||||
continue
|
||||
fh = logging.FileHandler(cfg.log_file, encoding="utf-8")
|
||||
fh.setFormatter(fmt)
|
||||
logger.addHandler(fh)
|
||||
|
||||
|
||||
def load_state(path: Path) -> dict[str, Any]:
|
||||
if path.exists():
|
||||
try:
|
||||
return {**DEFAULT_STATE, **json.loads(path.read_text(encoding="utf-8"))}
|
||||
except Exception as e:
|
||||
logger.warning("load state failed: %s", e)
|
||||
return {**DEFAULT_STATE}
|
||||
|
||||
|
||||
def save_state(path: Path, state: dict[str, Any]) -> None:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(json.dumps(state, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
|
||||
|
||||
def acquire_single_instance_lock(cfg: RunnerConfig) -> None:
|
||||
global LOCK_HANDLE
|
||||
try:
|
||||
import fcntl
|
||||
except ImportError:
|
||||
logger.warning("fcntl unavailable, skip single-instance lock (non-Unix)")
|
||||
return
|
||||
cfg.lock_file.parent.mkdir(parents=True, exist_ok=True)
|
||||
lock_handle = cfg.lock_file.open("w")
|
||||
try:
|
||||
fcntl.flock(lock_handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
except BlockingIOError:
|
||||
logger.error(
|
||||
"another cpa-runner instance is already running, lock=%s", cfg.lock_file
|
||||
)
|
||||
raise SystemExit(1)
|
||||
lock_handle.write(str(os.getpid()))
|
||||
lock_handle.flush()
|
||||
LOCK_HANDLE = lock_handle
|
||||
|
||||
|
||||
def build_dingtalk_url(webhook: str, secret: str) -> str:
|
||||
if not secret:
|
||||
return webhook
|
||||
timestamp = str(round(time.time() * 1000))
|
||||
sign_data = f"{timestamp}\n{secret}".encode("utf-8")
|
||||
sign = quote_plus(
|
||||
base64.b64encode(
|
||||
hmac.new(secret.encode("utf-8"), sign_data, digestmod=hashlib.sha256).digest()
|
||||
)
|
||||
)
|
||||
sep = "&" if "?" in webhook else "?"
|
||||
return f"{webhook}{sep}timestamp={timestamp}&sign={sign}"
|
||||
|
||||
|
||||
def send_dingtalk(cfg: RunnerConfig, payload: dict) -> bool:
|
||||
if not cfg.dingtalk_webhook:
|
||||
logger.info("skip notify: dingtalk webhook empty")
|
||||
return False
|
||||
url = build_dingtalk_url(cfg.dingtalk_webhook, cfg.dingtalk_secret)
|
||||
try:
|
||||
resp = requests.post(url, json=payload, timeout=15)
|
||||
resp.raise_for_status()
|
||||
data = resp.json()
|
||||
if data.get("errcode") != 0:
|
||||
logger.error("dingtalk notify failed: %s", data)
|
||||
return False
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.exception("send dingtalk notify error: %s", e)
|
||||
return False
|
||||
|
||||
|
||||
def send_dingtalk_markdown(cfg: RunnerConfig, title: str, markdown_text: str) -> bool:
|
||||
return send_dingtalk(
|
||||
cfg,
|
||||
{
|
||||
"msgtype": "markdown",
|
||||
"markdown": {"title": title, "text": markdown_text},
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def format_ts(ts: Optional[int]) -> str:
|
||||
if not ts:
|
||||
return "-"
|
||||
return datetime.fromtimestamp(ts).strftime("%Y-%m-%d %H:%M:%S")
|
||||
|
||||
|
||||
def _tail(s: str, n: int = 4000) -> str:
|
||||
s = (s or "").strip()
|
||||
if len(s) <= n:
|
||||
return s
|
||||
return "…" + s[-n:]
|
||||
|
||||
|
||||
def build_status_markdown(
|
||||
*,
|
||||
moved: int,
|
||||
return_code: int,
|
||||
title: str,
|
||||
status_label: str,
|
||||
status_emoji: str,
|
||||
state: dict[str, Any],
|
||||
cfg: RunnerConfig,
|
||||
note: Optional[str] = None,
|
||||
) -> str:
|
||||
lines = [
|
||||
f"# {status_emoji} {title}",
|
||||
"",
|
||||
f"> 状态:**{status_label}**",
|
||||
"",
|
||||
f"- 本次迁出 JSON:**{moved}** 个",
|
||||
f"- run.py 返回码:**{return_code}**",
|
||||
f"- 执行时间:`{format_ts(state.get('last_run_at'))}`",
|
||||
f"- 目标目录:`{cfg.target_dir}`",
|
||||
]
|
||||
if note:
|
||||
lines.extend(["", f"> {note}"])
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def move_json_files(cfg: RunnerConfig) -> int:
|
||||
moved = 0
|
||||
if not cfg.oauth_dir.exists():
|
||||
logger.warning("oauth dir not found: %s", cfg.oauth_dir)
|
||||
return 0
|
||||
cfg.target_dir.mkdir(parents=True, exist_ok=True)
|
||||
for src in sorted(cfg.oauth_dir.glob("*.json")):
|
||||
target = cfg.target_dir / src.name
|
||||
if target.exists():
|
||||
stem = src.stem
|
||||
suffix = src.suffix
|
||||
target = cfg.target_dir / f"{stem}_{int(time.time())}{suffix}"
|
||||
shutil.move(str(src), str(target))
|
||||
moved += 1
|
||||
logger.info("moved json: %s -> %s", src, target)
|
||||
return moved
|
||||
|
||||
|
||||
def execute_pipeline_cycle(
|
||||
cfg: RunnerConfig,
|
||||
state: dict[str, Any],
|
||||
*,
|
||||
allow_sys_exit_on_empty: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
执行一次:run.py → 迁出 oauth json → 钉钉。
|
||||
返回更新后的 state(调用方负责 save_state)。
|
||||
allow_sys_exit_on_empty:仅独立脚本进程应为 True。
|
||||
"""
|
||||
out = {**DEFAULT_STATE, **state}
|
||||
ensure_pipeline_file_handler(cfg)
|
||||
logger.info("pipeline cycle start run_script=%s", cfg.run_script)
|
||||
cmd = [cfg.python_bin, str(cfg.run_script)]
|
||||
try:
|
||||
completed = subprocess.run(
|
||||
cmd,
|
||||
cwd=str(cfg.run_script.parent),
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=cfg.subprocess_timeout_sec,
|
||||
)
|
||||
rc = completed.returncode
|
||||
logger.info("run.py return code: %s", rc)
|
||||
if completed.stdout:
|
||||
logger.info("run.py stdout:\n%s", completed.stdout.strip())
|
||||
if completed.stderr:
|
||||
logger.warning("run.py stderr:\n%s", completed.stderr.strip())
|
||||
out["last_stdout_tail"] = _tail(completed.stdout or "")
|
||||
out["last_stderr_tail"] = _tail(completed.stderr or "")
|
||||
out["last_error"] = ""
|
||||
|
||||
moved = move_json_files(cfg)
|
||||
out["last_run_moved"] = moved
|
||||
out["last_run_return_code"] = rc
|
||||
out["last_run_at"] = int(time.time())
|
||||
|
||||
if moved == 0:
|
||||
md = build_status_markdown(
|
||||
moved=moved,
|
||||
return_code=rc,
|
||||
title="流水线告警",
|
||||
status_label="未迁出任何 JSON",
|
||||
status_emoji="🚨",
|
||||
state=out,
|
||||
cfg=cfg,
|
||||
note=f"OAuth 目录:`{cfg.oauth_dir}`",
|
||||
)
|
||||
send_dingtalk_markdown(cfg, "流水线告警", md)
|
||||
logger.warning("pipeline: moved=0, alert sent")
|
||||
if cfg.exit_on_zero_moved and allow_sys_exit_on_empty:
|
||||
raise SystemExit(0)
|
||||
else:
|
||||
md = build_status_markdown(
|
||||
moved=moved,
|
||||
return_code=rc,
|
||||
title="流水线战报",
|
||||
status_label="执行完成",
|
||||
status_emoji="✅",
|
||||
state=out,
|
||||
cfg=cfg,
|
||||
)
|
||||
send_dingtalk_markdown(cfg, "流水线战报", md)
|
||||
out["last_notify_at"] = int(time.time())
|
||||
logger.info("pipeline done moved=%s", moved)
|
||||
|
||||
except subprocess.TimeoutExpired:
|
||||
logger.exception("run.py timeout")
|
||||
out["last_run_return_code"] = -1
|
||||
out["last_run_at"] = int(time.time())
|
||||
out["last_error"] = "subprocess timeout"
|
||||
except Exception as e:
|
||||
logger.exception("execute_pipeline_cycle failed")
|
||||
out["last_run_return_code"] = -2
|
||||
out["last_run_at"] = int(time.time())
|
||||
out["last_error"] = str(e)[:500]
|
||||
|
||||
return out
|
||||
|
||||
|
||||
def run_once_cli() -> None:
|
||||
"""独立进程入口使用:读 CONFIG,写 state 文件。"""
|
||||
global CONFIG
|
||||
CONFIG = runner_config_from_env()
|
||||
_setup_cli_logging(CONFIG)
|
||||
CONFIG.target_dir.mkdir(parents=True, exist_ok=True)
|
||||
st = load_state(CONFIG.state_file)
|
||||
st = execute_pipeline_cycle(CONFIG, st, allow_sys_exit_on_empty=True)
|
||||
save_state(CONFIG.state_file, st)
|
||||
|
||||
|
||||
def main_blocking() -> None:
|
||||
from apscheduler.schedulers.blocking import BlockingScheduler
|
||||
from apscheduler.triggers.interval import IntervalTrigger
|
||||
|
||||
global CONFIG
|
||||
CONFIG = runner_config_from_env()
|
||||
_setup_cli_logging(CONFIG)
|
||||
acquire_single_instance_lock(CONFIG)
|
||||
logger.info("cpa-runner (standalone) starting")
|
||||
logger.info("run_script=%s", CONFIG.run_script)
|
||||
logger.info("interval_min=%s", env_int("RUN_EVERY_MINUTES", 10))
|
||||
|
||||
scheduler = BlockingScheduler(timezone="Asia/Shanghai")
|
||||
scheduler.add_job(
|
||||
run_once_cli,
|
||||
IntervalTrigger(minutes=env_int("RUN_EVERY_MINUTES", 10)),
|
||||
id="run_job",
|
||||
max_instances=1,
|
||||
coalesce=True,
|
||||
)
|
||||
|
||||
run_once_cli()
|
||||
scheduler.start()
|
||||
|
||||
|
||||
def runner_config_from_db(get_setting: Callable[[str, str], str]) -> RunnerConfig:
|
||||
"""从维护台 SQLite settings 构造配置。"""
|
||||
g = get_setting
|
||||
return RunnerConfig(
|
||||
run_script=Path(
|
||||
g("pipeline_run_script", str(REPO_ROOT / "run.py"))
|
||||
).resolve(),
|
||||
oauth_dir=Path(
|
||||
g("pipeline_oauth_dir", str(REPO_ROOT / "accounts" / "oauth"))
|
||||
).resolve(),
|
||||
target_dir=Path(
|
||||
g("cpa_target_dir", str(REPO_ROOT / "export" / "cpa_auths"))
|
||||
).resolve(),
|
||||
python_bin=g("pipeline_python_bin", "python3"),
|
||||
dingtalk_webhook=g("dingtalk_webhook", "").strip(),
|
||||
dingtalk_secret=g("dingtalk_secret", "").strip(),
|
||||
exit_on_zero_moved=g("cpa_exit_on_empty", "0") == "1",
|
||||
subprocess_timeout_sec=int(g("run_subprocess_timeout_sec", "480") or 480),
|
||||
state_file=Path(
|
||||
g(
|
||||
"pipeline_state_file",
|
||||
str(REPO_ROOT / "maintain" / "data" / "pipeline_state.json"),
|
||||
)
|
||||
).resolve(),
|
||||
log_file=Path(
|
||||
g(
|
||||
"pipeline_log_file",
|
||||
str(REPO_ROOT / "maintain" / "data" / "pipeline.log"),
|
||||
)
|
||||
).resolve(),
|
||||
lock_file=Path(
|
||||
g(
|
||||
"pipeline_lock_file",
|
||||
str(REPO_ROOT / "maintain" / "data" / "cpa_runner.lock"),
|
||||
)
|
||||
).resolve(),
|
||||
)
|
||||
Whitespace-only changes.
+480
@@ -0,0 +1,480 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import sqlite3
|
||||
import threading
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any, Optional
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
DB_PATH = ROOT / "maintain" / "data" / "maintain.db"
|
||||
ACCOUNTS_OAUTH = ROOT / "accounts" / "oauth"
|
||||
|
||||
_lock = threading.Lock()
|
||||
|
||||
|
||||
def resolve_oauth_stats_dir() -> Path:
|
||||
"""
|
||||
统计 / 巡检用的 codex JSON 目录。
|
||||
留空 = 项目内 accounts/oauth;若注册成功后文件迁入 Cliproxy auth 目录,填该目录绝对路径。
|
||||
"""
|
||||
raw = get_setting("codex_stats_oauth_dir", "").strip()
|
||||
if not raw:
|
||||
return ACCOUNTS_OAUTH.resolve()
|
||||
return Path(raw).expanduser().resolve()
|
||||
|
||||
|
||||
def safe_unlink_oauth_json(path_str: str) -> bool:
|
||||
"""仅允许删除「统计目录」下的 .json 文件,防路径穿越。"""
|
||||
try:
|
||||
p = Path(path_str).resolve()
|
||||
root = resolve_oauth_stats_dir()
|
||||
p.relative_to(root)
|
||||
except (ValueError, OSError):
|
||||
return False
|
||||
if p.suffix.lower() != ".json":
|
||||
return False
|
||||
if not p.is_file():
|
||||
return False
|
||||
try:
|
||||
p.unlink()
|
||||
return True
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
|
||||
def _conn() -> sqlite3.Connection:
|
||||
DB_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||||
c = sqlite3.connect(str(DB_PATH), check_same_thread=False)
|
||||
c.row_factory = sqlite3.Row
|
||||
return c
|
||||
|
||||
|
||||
def init_db() -> None:
|
||||
with _lock:
|
||||
c = _conn()
|
||||
try:
|
||||
c.executescript(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS cpa (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
name TEXT NOT NULL,
|
||||
code TEXT NOT NULL UNIQUE,
|
||||
target_count INTEGER NOT NULL DEFAULT 0,
|
||||
api_base_url TEXT DEFAULT ''
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS settings (
|
||||
key TEXT PRIMARY KEY,
|
||||
value TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS proxies (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
url TEXT NOT NULL,
|
||||
label TEXT DEFAULT '',
|
||||
enabled INTEGER NOT NULL DEFAULT 1
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS tasks (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
task_type TEXT NOT NULL,
|
||||
status TEXT NOT NULL,
|
||||
message TEXT DEFAULT '',
|
||||
cpa_id INTEGER,
|
||||
total INTEGER DEFAULT 0,
|
||||
done INTEGER DEFAULT 0,
|
||||
created_at TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL
|
||||
);
|
||||
"""
|
||||
)
|
||||
cur = c.execute("SELECT COUNT(*) FROM cpa")
|
||||
if cur.fetchone()[0] == 0:
|
||||
c.execute(
|
||||
"INSERT INTO cpa (name, code, target_count, api_base_url) VALUES (?,?,?,?)",
|
||||
("账号池", "default", 8000, ""),
|
||||
)
|
||||
defaults = {
|
||||
"auto_inspect_enabled": "0",
|
||||
"inspect_interval_min": "60",
|
||||
"use_proxy_pool_auto": "1",
|
||||
"max_auto_register_per_tick": "30",
|
||||
"default_threads": "1",
|
||||
"skip_oauth": "0",
|
||||
"manual_default_proxy": "",
|
||||
# 子进程流水线(run.py → 迁出 JSON),与维护台共用 pipeline_state.json
|
||||
"pipeline_auto_enabled": "0",
|
||||
"pipeline_interval_min": "10",
|
||||
"pipeline_run_script": str(ROOT / "run.py"),
|
||||
"pipeline_oauth_dir": str(ROOT / "accounts" / "oauth"),
|
||||
"cpa_target_dir": str(ROOT / "export" / "cpa_auths"),
|
||||
"pipeline_python_bin": "python3",
|
||||
"run_subprocess_timeout_sec": "480",
|
||||
"cpa_exit_on_empty": "0",
|
||||
"dingtalk_webhook": "",
|
||||
"dingtalk_secret": "",
|
||||
# Cliproxy 管理端巡检(与 Web 管理台「探测模型」同源)
|
||||
"cliproxy_management_base": "",
|
||||
"cliproxy_management_key": "",
|
||||
"cliproxy_probe_timeout_sec": "30",
|
||||
# 成功后 JSON 若在 Cliproxy auth 目录,填绝对路径;留空则用项目 accounts/oauth
|
||||
"codex_stats_oauth_dir": "",
|
||||
"inspect_probe_valid_json": "",
|
||||
"pipeline_state_file": str(ROOT / "maintain" / "data" / "pipeline_state.json"),
|
||||
"pipeline_log_file": str(ROOT / "maintain" / "data" / "pipeline.log"),
|
||||
"pipeline_lock_file": str(ROOT / "maintain" / "data" / "cpa_runner.lock"),
|
||||
}
|
||||
for k, v in defaults.items():
|
||||
c.execute(
|
||||
"INSERT OR IGNORE INTO settings (key, value) VALUES (?, ?)", (k, v)
|
||||
)
|
||||
c.commit()
|
||||
finally:
|
||||
c.close()
|
||||
|
||||
|
||||
def get_setting(key: str, default: str = "") -> str:
|
||||
with _lock:
|
||||
c = _conn()
|
||||
try:
|
||||
row = c.execute("SELECT value FROM settings WHERE key=?", (key,)).fetchone()
|
||||
return row["value"] if row else default
|
||||
finally:
|
||||
c.close()
|
||||
|
||||
|
||||
def set_setting(key: str, value: str) -> None:
|
||||
with _lock:
|
||||
c = _conn()
|
||||
try:
|
||||
c.execute(
|
||||
"INSERT INTO settings (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value",
|
||||
(key, value),
|
||||
)
|
||||
c.commit()
|
||||
finally:
|
||||
c.close()
|
||||
|
||||
|
||||
def all_settings() -> dict[str, str]:
|
||||
with _lock:
|
||||
c = _conn()
|
||||
try:
|
||||
rows = c.execute("SELECT key, value FROM settings").fetchall()
|
||||
return {r["key"]: r["value"] for r in rows}
|
||||
finally:
|
||||
c.close()
|
||||
|
||||
|
||||
def list_cpas() -> list[dict[str, Any]]:
|
||||
with _lock:
|
||||
c = _conn()
|
||||
try:
|
||||
rows = c.execute(
|
||||
"SELECT id, name, code, target_count, api_base_url FROM cpa ORDER BY id"
|
||||
).fetchall()
|
||||
return [dict(r) for r in rows]
|
||||
finally:
|
||||
c.close()
|
||||
|
||||
|
||||
def update_cpa(
|
||||
cpa_id: int,
|
||||
*,
|
||||
name: Optional[str] = None,
|
||||
target_count: Optional[int] = None,
|
||||
api_base_url: Optional[str] = None,
|
||||
) -> None:
|
||||
with _lock:
|
||||
c = _conn()
|
||||
try:
|
||||
if name is not None:
|
||||
c.execute("UPDATE cpa SET name=? WHERE id=?", (name, cpa_id))
|
||||
if target_count is not None:
|
||||
c.execute("UPDATE cpa SET target_count=? WHERE id=?", (target_count, cpa_id))
|
||||
if api_base_url is not None:
|
||||
c.execute("UPDATE cpa SET api_base_url=? WHERE id=?", (api_base_url, cpa_id))
|
||||
c.commit()
|
||||
finally:
|
||||
c.close()
|
||||
|
||||
|
||||
def list_proxies() -> list[dict[str, Any]]:
|
||||
with _lock:
|
||||
c = _conn()
|
||||
try:
|
||||
rows = c.execute(
|
||||
"SELECT id, url, label, enabled FROM proxies ORDER BY id"
|
||||
).fetchall()
|
||||
return [dict(r) for r in rows]
|
||||
finally:
|
||||
c.close()
|
||||
|
||||
|
||||
def add_proxy(url: str, label: str = "") -> int:
|
||||
with _lock:
|
||||
c = _conn()
|
||||
try:
|
||||
cur = c.execute(
|
||||
"INSERT INTO proxies (url, label, enabled) VALUES (?,?,1)",
|
||||
(url.strip(), label.strip()),
|
||||
)
|
||||
c.commit()
|
||||
return int(cur.lastrowid)
|
||||
finally:
|
||||
c.close()
|
||||
|
||||
|
||||
def delete_proxy(proxy_id: int) -> None:
|
||||
with _lock:
|
||||
c = _conn()
|
||||
try:
|
||||
c.execute("DELETE FROM proxies WHERE id=?", (proxy_id,))
|
||||
c.commit()
|
||||
finally:
|
||||
c.close()
|
||||
|
||||
|
||||
def pick_random_proxy_url() -> Optional[str]:
|
||||
rows = [p for p in list_proxies() if p.get("enabled")]
|
||||
if not rows:
|
||||
return None
|
||||
import random
|
||||
|
||||
return random.choice(rows)["url"]
|
||||
|
||||
|
||||
def cliproxy_inspect_configured() -> bool:
|
||||
return bool(get_setting("cliproxy_management_base", "").strip()) and bool(
|
||||
get_setting("cliproxy_management_key", "").strip()
|
||||
)
|
||||
|
||||
|
||||
def _oauth_json_is_codex_candidate(data: dict[str, Any], *, strict_codex_type: bool) -> bool:
|
||||
if data.get("disabled"):
|
||||
return False
|
||||
if strict_codex_type:
|
||||
return data.get("type") == "codex"
|
||||
t = data.get("type")
|
||||
if t == "codex":
|
||||
return True
|
||||
if t in (None, ""):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _oauth_cpa_id_from_json(data: dict[str, Any]) -> int:
|
||||
cid = data.get("cpa_id")
|
||||
if cid is None:
|
||||
return 1
|
||||
try:
|
||||
return int(cid)
|
||||
except (TypeError, ValueError):
|
||||
return 1
|
||||
|
||||
|
||||
def parse_inspect_probe_cache() -> Optional[dict[str, Any]]:
|
||||
raw = get_setting("inspect_probe_valid_json", "").strip()
|
||||
if not raw:
|
||||
return None
|
||||
try:
|
||||
o = json.loads(raw)
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
return None
|
||||
if not isinstance(o, dict) or "by_cpa" not in o:
|
||||
return None
|
||||
return o
|
||||
|
||||
|
||||
def list_oauth_codex_entries() -> list[dict[str, Any]]:
|
||||
"""每个统计目录下 *.json 一条;stem 与 Cliproxy auth 文件名对应。"""
|
||||
root = resolve_oauth_stats_dir()
|
||||
strict = root.resolve() == ACCOUNTS_OAUTH.resolve()
|
||||
out: list[dict[str, Any]] = []
|
||||
if not root.is_dir():
|
||||
return out
|
||||
for path in sorted(root.glob("*.json")):
|
||||
try:
|
||||
with open(path, encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
except Exception:
|
||||
continue
|
||||
if not isinstance(data, dict):
|
||||
continue
|
||||
if not _oauth_json_is_codex_candidate(data, strict_codex_type=strict):
|
||||
continue
|
||||
cid = _oauth_cpa_id_from_json(data)
|
||||
out.append({"cpa_id": cid, "stem": path.stem, "path": str(path)})
|
||||
return out
|
||||
|
||||
|
||||
def count_oauth_accounts_by_cpa() -> dict[int, int]:
|
||||
"""按统计目录统计;无 cpa_id 归入 id=1。"""
|
||||
root = resolve_oauth_stats_dir()
|
||||
strict = root.resolve() == ACCOUNTS_OAUTH.resolve()
|
||||
counts: dict[int, int] = {}
|
||||
if not root.is_dir():
|
||||
return counts
|
||||
for path in root.glob("*.json"):
|
||||
try:
|
||||
with open(path, encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
except Exception:
|
||||
continue
|
||||
if not isinstance(data, dict):
|
||||
continue
|
||||
if not _oauth_json_is_codex_candidate(data, strict_codex_type=strict):
|
||||
continue
|
||||
cid = _oauth_cpa_id_from_json(data)
|
||||
counts[cid] = counts.get(cid, 0) + 1
|
||||
return counts
|
||||
|
||||
|
||||
def overview_stats() -> dict[str, Any]:
|
||||
cpas = list_cpas()
|
||||
by_file = count_oauth_accounts_by_cpa()
|
||||
probe = parse_inspect_probe_cache()
|
||||
use_probe = cliproxy_inspect_configured() and probe is not None
|
||||
by_valid: dict[int, int] = {}
|
||||
if use_probe and isinstance(probe.get("by_cpa"), dict):
|
||||
raw_bc = probe["by_cpa"]
|
||||
for c in cpas:
|
||||
cid = c["id"]
|
||||
v = raw_bc.get(str(cid), raw_bc.get(cid))
|
||||
if v is None:
|
||||
v = 0
|
||||
try:
|
||||
by_valid[cid] = int(v)
|
||||
except (TypeError, ValueError):
|
||||
by_valid[cid] = 0
|
||||
rows = []
|
||||
total = 0
|
||||
total_raw = 0
|
||||
total_target = 0
|
||||
for c in cpas:
|
||||
cid = c["id"]
|
||||
n_raw = by_file.get(cid, 0)
|
||||
total_raw += n_raw
|
||||
n = by_valid.get(cid, n_raw) if use_probe else n_raw
|
||||
total += n
|
||||
tgt = int(c["target_count"] or 0)
|
||||
total_target += tgt
|
||||
health = (n / tgt * 100.0) if tgt > 0 else 100.0
|
||||
gap = max(0, tgt - n)
|
||||
status = "健康" if health >= 95 else ("偏低" if health >= 70 else "告警")
|
||||
row: dict[str, Any] = {
|
||||
**c,
|
||||
"candidates": n,
|
||||
"health_pct": round(health, 2),
|
||||
"gap": gap,
|
||||
"status": status,
|
||||
}
|
||||
if use_probe and n_raw != n:
|
||||
row["raw_candidates"] = n_raw
|
||||
rows.append(row)
|
||||
global_health = (total / total_target * 100.0) if total_target > 0 else 100.0
|
||||
out: dict[str, Any] = {
|
||||
"cpas": rows,
|
||||
"total_accounts": total,
|
||||
"total_candidates": total,
|
||||
"total_target": total_target,
|
||||
"global_health_pct": round(global_health, 2),
|
||||
"global_status": "健康" if global_health >= 95 else ("偏低" if global_health >= 70 else "告警"),
|
||||
"inspect_probe_mode": use_probe,
|
||||
"inspect_last_at": (probe or {}).get("probed_at") if use_probe else None,
|
||||
"total_accounts_raw": total_raw,
|
||||
}
|
||||
if cliproxy_inspect_configured() and not use_probe:
|
||||
out["inspect_probe_pending"] = True
|
||||
stats_root = resolve_oauth_stats_dir()
|
||||
out["oauth_stats_dir"] = str(stats_root)
|
||||
out["oauth_stats_dir_is_default"] = stats_root.resolve() == ACCOUNTS_OAUTH.resolve()
|
||||
return out
|
||||
|
||||
|
||||
def create_task(
|
||||
task_type: str,
|
||||
status: str,
|
||||
message: str = "",
|
||||
cpa_id: Optional[int] = None,
|
||||
total: int = 0,
|
||||
) -> int:
|
||||
now = datetime.now(timezone.utc).isoformat()
|
||||
with _lock:
|
||||
c = _conn()
|
||||
try:
|
||||
cur = c.execute(
|
||||
"""INSERT INTO tasks (task_type, status, message, cpa_id, total, done, created_at, updated_at)
|
||||
VALUES (?,?,?,?,?,?,?,?)""",
|
||||
(task_type, status, message, cpa_id, total, 0, now, now),
|
||||
)
|
||||
c.commit()
|
||||
return int(cur.lastrowid)
|
||||
finally:
|
||||
c.close()
|
||||
|
||||
|
||||
def update_task(
|
||||
task_id: int,
|
||||
*,
|
||||
status: Optional[str] = None,
|
||||
message: Optional[str] = None,
|
||||
done: Optional[int] = None,
|
||||
) -> None:
|
||||
now = datetime.now(timezone.utc).isoformat()
|
||||
parts = ["updated_at=?"]
|
||||
vals: list[Any] = [now]
|
||||
if status is not None:
|
||||
parts.append("status=?")
|
||||
vals.append(status)
|
||||
if message is not None:
|
||||
parts.append("message=?")
|
||||
vals.append(message)
|
||||
if done is not None:
|
||||
parts.append("done=?")
|
||||
vals.append(done)
|
||||
vals.append(task_id)
|
||||
with _lock:
|
||||
c = _conn()
|
||||
try:
|
||||
c.execute(f"UPDATE tasks SET {','.join(parts)} WHERE id=?", vals)
|
||||
c.commit()
|
||||
finally:
|
||||
c.close()
|
||||
|
||||
|
||||
def get_active_task() -> Optional[dict[str, Any]]:
|
||||
with _lock:
|
||||
c = _conn()
|
||||
try:
|
||||
row = c.execute(
|
||||
"""SELECT * FROM tasks WHERE status IN ('running','queued')
|
||||
ORDER BY id DESC LIMIT 1"""
|
||||
).fetchone()
|
||||
return dict(row) if row else None
|
||||
finally:
|
||||
c.close()
|
||||
|
||||
|
||||
def get_task(task_id: int) -> Optional[dict[str, Any]]:
|
||||
with _lock:
|
||||
c = _conn()
|
||||
try:
|
||||
row = c.execute("SELECT * FROM tasks WHERE id=?", (task_id,)).fetchone()
|
||||
return dict(row) if row else None
|
||||
finally:
|
||||
c.close()
|
||||
|
||||
|
||||
def list_recent_tasks(limit: int = 20) -> list[dict[str, Any]]:
|
||||
lim = max(1, min(int(limit), 100))
|
||||
with _lock:
|
||||
c = _conn()
|
||||
try:
|
||||
rows = c.execute(
|
||||
"SELECT * FROM tasks ORDER BY id DESC LIMIT ?",
|
||||
(lim,),
|
||||
).fetchall()
|
||||
return [dict(r) for r in rows]
|
||||
finally:
|
||||
c.close()
|
||||
@@ -0,0 +1,37 @@
|
||||
"""维护台进程内任务日志(巡检 / 补号 / 与流水线摘要),写入 data/maintain_runtime.log"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parent.parent
|
||||
DEFAULT_PATH = REPO_ROOT / "maintain" / "data" / "maintain_runtime.log"
|
||||
|
||||
_logger: Optional[logging.Logger] = None
|
||||
|
||||
|
||||
def runtime_log_path() -> Path:
|
||||
return DEFAULT_PATH
|
||||
|
||||
|
||||
def setup_runtime_logging() -> logging.Logger:
|
||||
global _logger
|
||||
if _logger is not None:
|
||||
return _logger
|
||||
DEFAULT_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||||
lg = logging.getLogger("maintain.runtime")
|
||||
lg.setLevel(logging.INFO)
|
||||
lg.propagate = False
|
||||
if not lg.handlers:
|
||||
fh = logging.FileHandler(DEFAULT_PATH, encoding="utf-8")
|
||||
fh.setFormatter(
|
||||
logging.Formatter("%(asctime)s [%(levelname)s] %(message)s")
|
||||
)
|
||||
lg.addHandler(fh)
|
||||
_logger = lg
|
||||
return lg
|
||||
|
||||
|
||||
def rtlog() -> logging.Logger:
|
||||
return setup_runtime_logging()
|
||||
Whitespace-only changes.
@@ -0,0 +1,607 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>Codex 自动维护</title>
|
||||
<style>
|
||||
:root {
|
||||
--bg: #0f1419;
|
||||
--panel: #161b22;
|
||||
--border: #30363d;
|
||||
--text: #e6edf3;
|
||||
--muted: #8b949e;
|
||||
--accent: #1f6feb;
|
||||
--ok: #238636;
|
||||
--warn: #d29922;
|
||||
--bad: #f85149;
|
||||
}
|
||||
* { box-sizing: border-box; }
|
||||
body { margin: 0; font-family: system-ui, -apple-system, sans-serif; background: var(--bg); color: var(--text); min-height: 100vh; }
|
||||
header { display: flex; align-items: center; justify-content: space-between; padding: 12px 24px; border-bottom: 1px solid var(--border); background: var(--panel); }
|
||||
header h1 { margin: 0; font-size: 1.15rem; font-weight: 600; }
|
||||
.tabs { display: flex; gap: 4px; padding: 0 24px; background: var(--panel); border-bottom: 1px solid var(--border); }
|
||||
.tabs button { background: transparent; border: 0; color: var(--muted); padding: 12px 16px; cursor: pointer; border-bottom: 2px solid transparent; font-size: 0.9rem; }
|
||||
.tabs button.active { color: var(--text); border-bottom-color: var(--accent); }
|
||||
main { padding: 20px 24px; max-width: 1200px; margin: 0 auto; }
|
||||
.section { display: none; }
|
||||
.section.visible { display: block; }
|
||||
.banner { background: rgba(31, 111, 235, 0.15); border: 1px solid var(--accent); border-radius: 8px; padding: 12px 16px; margin-bottom: 20px; font-size: 0.9rem; }
|
||||
.banner.idle { display: none; }
|
||||
.cards { display: grid; grid-template-columns: repeat(4, 1fr); gap: 16px; margin-bottom: 24px; }
|
||||
@media (max-width: 900px) { .cards { grid-template-columns: repeat(2, 1fr); } }
|
||||
.card { background: var(--panel); border: 1px solid var(--border); border-radius: 10px; padding: 16px; }
|
||||
.card .label { color: var(--muted); font-size: 0.8rem; margin-bottom: 6px; }
|
||||
.card .value { font-size: 1.5rem; font-weight: 700; }
|
||||
.card .sub { font-size: 0.8rem; color: var(--muted); margin-top: 4px; }
|
||||
table { width: 100%; border-collapse: collapse; background: var(--panel); border: 1px solid var(--border); border-radius: 10px; overflow: hidden; }
|
||||
th, td { text-align: left; padding: 12px 14px; border-bottom: 1px solid var(--border); font-size: 0.875rem; }
|
||||
th { color: var(--muted); font-weight: 500; }
|
||||
tr:last-child td { border-bottom: 0; }
|
||||
.tag { display: inline-block; padding: 2px 8px; border-radius: 999px; font-size: 0.75rem; }
|
||||
.tag.ok { background: rgba(35, 134, 54, 0.2); color: #3fb950; }
|
||||
.tag.warn { background: rgba(210, 153, 34, 0.2); color: #e3b341; }
|
||||
.tag.bad { background: rgba(248, 81, 73, 0.15); color: var(--bad); }
|
||||
.grid2 { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-top: 24px; }
|
||||
@media (max-width: 800px) { .grid2 { grid-template-columns: 1fr; } }
|
||||
.panel { background: var(--panel); border: 1px solid var(--border); border-radius: 10px; padding: 18px; }
|
||||
.panel h3 { margin: 0 0 14px; font-size: 1rem; }
|
||||
label { display: block; font-size: 0.8rem; color: var(--muted); margin-bottom: 4px; }
|
||||
input, select { width: 100%; padding: 8px 10px; border-radius: 6px; border: 1px solid var(--border); background: #0d1117; color: var(--text); margin-bottom: 12px; }
|
||||
.row { display: flex; align-items: center; gap: 8px; margin-bottom: 10px; }
|
||||
.row input { width: auto; margin: 0; }
|
||||
button.primary { background: var(--accent); color: #fff; border: 0; padding: 10px 16px; border-radius: 8px; font-weight: 600; cursor: pointer; }
|
||||
button.primary:hover { filter: brightness(1.1); }
|
||||
button.ghost { background: transparent; border: 1px solid var(--border); color: var(--text); padding: 8px 12px; border-radius: 8px; cursor: pointer; }
|
||||
.proxy-list { max-height: 220px; overflow: auto; margin-bottom: 12px; }
|
||||
.proxy-item { display: flex; justify-content: space-between; align-items: center; padding: 8px 0; border-bottom: 1px solid var(--border); font-size: 0.85rem; }
|
||||
.toast { position: fixed; bottom: 20px; right: 20px; background: var(--panel); border: 1px solid var(--border); padding: 12px 16px; border-radius: 8px; display: none; z-index: 99; }
|
||||
.task-log { width: 100%; border-collapse: collapse; font-size: 0.8rem; }
|
||||
.task-log th { padding: 8px 10px; color: var(--muted); font-weight: 500; text-align: left; border-bottom: 1px solid var(--border); }
|
||||
.task-log td { padding: 8px 10px; border-bottom: 1px solid var(--border); vertical-align: top; }
|
||||
.task-log tr:last-child td { border-bottom: 0; }
|
||||
.task-log .st-err { color: var(--bad); }
|
||||
.task-log .st-run { color: #58a6ff; }
|
||||
.task-log .st-done { color: #3fb950; }
|
||||
.task-msg { max-width: min(48vw, 520px); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.log-pre { margin: 0; max-height: 65vh; overflow: auto; background: #0d1117; border: 1px solid var(--border); border-radius: 8px; padding: 12px; font-size: 0.78rem; line-height: 1.45; white-space: pre-wrap; word-break: break-all; font-family: ui-monospace, monospace; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<header>
|
||||
<h1>Codex 自动维护</h1>
|
||||
<div style="display:flex;gap:8px;flex-wrap:wrap;align-items:center">
|
||||
<button class="ghost" type="button" id="btnRefreshData">刷新数据</button>
|
||||
<button class="ghost" type="button" id="btnSyncForms">同步表单</button>
|
||||
<button class="ghost" type="button" id="btnLogout">退出登录</button>
|
||||
</div>
|
||||
</header>
|
||||
<nav class="tabs">
|
||||
<button type="button" class="active" data-tab="task">任务中心</button>
|
||||
<button type="button" data-tab="pipeline">流水线</button>
|
||||
<button type="button" data-tab="proxy">代理池</button>
|
||||
<button type="button" data-tab="config">配置编辑</button>
|
||||
<button type="button" data-tab="logs">运行日志</button>
|
||||
<button type="button" data-tab="sec">安全设置</button>
|
||||
</nav>
|
||||
<main>
|
||||
<div id="section-task" class="section visible">
|
||||
<div class="banner idle" id="taskBanner"></div>
|
||||
<div class="panel" style="margin-bottom:16px;padding:12px 16px">
|
||||
<span style="color:var(--muted)">子进程流水线</span> — <span id="pipeHint">—</span>
|
||||
</div>
|
||||
<div class="panel" style="margin-bottom:16px">
|
||||
<div style="display:flex;justify-content:space-between;align-items:flex-start;gap:12px;flex-wrap:wrap;margin-bottom:10px">
|
||||
<h3 style="margin:0;font-size:0.95rem">任务进度与历史</h3>
|
||||
<span style="color:var(--muted);font-size:0.75rem;max-width:420px;line-height:1.4">自动轮询只更新此处与统计、账号表、流水线摘要,<strong>不会</strong>改写各页配置表单。填表前可先点「同步表单」拉服务端当前值。</span>
|
||||
</div>
|
||||
<div style="overflow-x:auto">
|
||||
<table class="task-log">
|
||||
<thead><tr><th>#</th><th>类型</th><th>状态</th><th>进度</th><th>说明</th><th>更新</th></tr></thead>
|
||||
<tbody id="recentTasksBody"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
<div class="cards">
|
||||
<div class="card"><div class="label">账号总数</div><div class="value" id="stTotal">—</div></div>
|
||||
<div class="card"><div class="label">有效账号</div><div class="value" id="stCand">—</div><div class="sub" id="stCandSub"></div></div>
|
||||
<div class="card"><div class="label">目标阈值</div><div class="value" id="stTarget">—</div></div>
|
||||
<div class="card"><div class="label">健康度</div><div class="value" id="stHealth">—</div><div class="sub" id="stHealthLbl"></div></div>
|
||||
</div>
|
||||
<p id="oauthStatsDirHint" style="margin:0 0 16px;font-size:0.78rem;color:var(--muted);line-height:1.45;word-break:break-all"></p>
|
||||
<h2 style="font-size:1rem;margin:0 0 12px;color:var(--muted)">账号池</h2>
|
||||
<table>
|
||||
<thead><tr><th>名称</th><th>有效 / 本地文件</th><th>目标</th><th>健康度</th><th>缺口</th><th>状态</th><th>操作</th></tr></thead>
|
||||
<tbody id="cpaBody"></tbody>
|
||||
</table>
|
||||
<div class="grid2">
|
||||
<div class="panel">
|
||||
<h3>自动巡检 → 批量补号</h3>
|
||||
<p style="color:var(--muted);font-size:0.8rem;margin:0 0 12px;line-height:1.5">按间隔 <strong>Cliproxy 管理 API</strong> 全量探测;<strong>失败条目删本地 JSON</strong>(预检密钥;超时/5xx/401 不删)。再按有效数算缺口,<strong>仍不足则自动进程内批量注册</strong>,每批不超过配置里的 <strong>单次自动注册上限</strong>(与手动补号共锁,勿并行)。</p>
|
||||
<div class="row"><input type="checkbox" id="autoEn" /><label for="autoEn" style="margin:0">启用自动巡检</label></div>
|
||||
<label>巡检间隔(分钟)</label>
|
||||
<input type="number" id="intervalMin" min="5" value="60" />
|
||||
<button class="primary" type="button" id="saveInspect">保存巡检设置</button>
|
||||
</div>
|
||||
<div class="panel">
|
||||
<h3>手动巡检</h3>
|
||||
<button class="primary" type="button" id="btnInspectNow" style="width:100%;margin-bottom:14px">立即巡检(探测删失效 → 不足则批量注册)</button>
|
||||
<label>单次批量注册数量</label>
|
||||
<input type="number" id="manualCount" min="1" max="500" value="20" />
|
||||
<div id="manualCpaWrap">
|
||||
<label>账号池</label>
|
||||
<select id="manualCpa"></select>
|
||||
</div>
|
||||
<p id="manualCpaSingle" style="display:none;color:var(--muted);font-size:0.85rem;margin:0 0 12px"></p>
|
||||
<div class="row"><input type="checkbox" id="manualS5" checked /><label for="manualS5" style="margin:0">本次任务启用代理池随机注册</label></div>
|
||||
<button class="primary" type="button" id="btnManual">开始批量注册</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div id="section-pipeline" class="section">
|
||||
<div class="panel" style="margin-bottom:16px">
|
||||
<h3>当前状态</h3>
|
||||
<pre id="pipeStatus" style="margin:0;font-size:0.8rem;color:var(--muted);white-space:pre-wrap;word-break:break-all"></pre>
|
||||
</div>
|
||||
<div class="grid2">
|
||||
<div class="panel">
|
||||
<h3>定时:run.py → 迁出 JSON</h3>
|
||||
<div class="row"><input type="checkbox" id="pipeAuto" /><label for="pipeAuto" style="margin:0">启用定时流水线</label></div>
|
||||
<label>间隔(分钟)</label>
|
||||
<input type="number" id="pipeInterval" min="1" value="10" />
|
||||
<label>Python 可执行文件</label>
|
||||
<input type="text" id="pipePy" placeholder="python3" />
|
||||
<label>子进程超时(秒)</label>
|
||||
<input type="number" id="pipeTimeout" min="60" value="480" />
|
||||
<div class="row"><input type="checkbox" id="pipeExit0" /><label for="pipeExit0" style="margin:0">迁出 0 个时仍发钉钉告警</label></div>
|
||||
<button class="primary" type="button" id="savePipe">保存流水线设置</button>
|
||||
</div>
|
||||
<div class="panel">
|
||||
<h3>路径与钉钉</h3>
|
||||
<label>run.py 绝对路径</label>
|
||||
<input type="text" id="pipeRunScript" />
|
||||
<label>OAuth 目录(源)</label>
|
||||
<input type="text" id="pipeOauth" />
|
||||
<label>迁出目标目录</label>
|
||||
<input type="text" id="pipeTarget" />
|
||||
<label>钉钉 Webhook(可选)</label>
|
||||
<input type="text" id="pipeDing" />
|
||||
<label>钉钉 Secret(可选)</label>
|
||||
<input type="text" id="pipeDingSec" />
|
||||
<button class="primary" type="button" id="btnPipeOnce" style="width:100%">立即执行一次(run.py + 迁出)</button>
|
||||
</div>
|
||||
</div>
|
||||
<p style="color:var(--muted);font-size:0.8rem;margin-top:14px">定时流水线按维护台当前统计的<strong>有效账号缺口</strong>(已配置管理端且跑过巡检后,与探测结果一致;否则按本地文件数)。充足则跳过。勿与 <code>scripts/cpa_runner.py</code> 双开。</p>
|
||||
</div>
|
||||
<div id="section-proxy" class="section">
|
||||
<div class="panel">
|
||||
<h3>代理池(HTTP / HTTPS / SOCKS5 URL 每行一条)</h3>
|
||||
<div class="proxy-list" id="proxyList"></div>
|
||||
<label>新增代理 URL</label>
|
||||
<input type="text" id="newProxyUrl" placeholder="socks5://127.0.0.1:1080 或 http://127.0.0.1:7890" />
|
||||
<label>备注</label>
|
||||
<input type="text" id="newProxyLabel" placeholder="可选" />
|
||||
<button class="primary" type="button" id="btnAddProxy">添加</button>
|
||||
</div>
|
||||
</div>
|
||||
<div id="section-config" class="section">
|
||||
<div class="panel">
|
||||
<h3>Cliproxy 管理端(巡检必填)</h3>
|
||||
<p style="color:var(--muted);font-size:0.8rem;margin:0 0 12px;line-height:1.5">与 <a href="https://help.router-for.me/cn/management/api" target="_blank" rel="noopener">管理 API</a> 一致。若<strong>注册成功后的 JSON 已迁入 Cliproxy 的 auth 目录</strong>,须填写下方「统计目录」为该目录绝对路径,否则维护台仍只扫项目内 <code>accounts/oauth</code>,账号数会显示 0。巡检按该目录下的文件名调用 <code>auth-files/models</code>;删除失效 JSON 也在该目录内。密钥存 SQLite。</p>
|
||||
<label>统计 / 巡检用 Codex JSON 目录(留空 = 项目内 accounts/oauth)</label>
|
||||
<input type="text" id="cfgStatsOauthDir" placeholder="/root/.cli-proxy-api 或你的 CPA auth 绝对路径" />
|
||||
<label>管理 Base(如 http://127.0.0.1:8317,勿带 /v0/management)</label>
|
||||
<input type="text" id="cfgClipBase" placeholder="http://127.0.0.1:8317" />
|
||||
<label>Management Key(Bearer)</label>
|
||||
<input type="password" id="cfgClipKey" autocomplete="new-password" placeholder="留空表示不修改已保存的密钥" />
|
||||
<label>探测超时(秒)</label>
|
||||
<input type="number" id="cfgClipTimeout" min="5" max="120" value="30" />
|
||||
<button class="primary" type="button" id="saveCliproxy">保存 Cliproxy 设置</button>
|
||||
</div>
|
||||
<div class="panel">
|
||||
<h3>运行参数</h3>
|
||||
<label>巡检后自动补号:每批最多注册个数(≤500,受缺口裁剪)</label>
|
||||
<input type="number" id="cfgMaxAutoReg" min="1" max="500" value="30" />
|
||||
<label>默认并行线程数(注册)</label>
|
||||
<input type="number" id="cfgThreads" min="1" max="16" value="1" />
|
||||
<div class="row"><input type="checkbox" id="cfgSkipOauth" /><label for="cfgSkipOauth" style="margin:0">仅注册、跳过 OAuth(unoauth)</label></div>
|
||||
<label>无代理池时的默认代理(可选)</label>
|
||||
<input type="text" id="cfgDefaultProxy" placeholder="留空则直连" />
|
||||
<button class="primary" type="button" id="saveConfig">保存配置</button>
|
||||
</div>
|
||||
</div>
|
||||
<div id="section-logs" class="section">
|
||||
<div class="panel">
|
||||
<h3>运行日志(文件尾部)</h3>
|
||||
<p style="color:var(--muted);font-size:0.8rem;line-height:1.55;margin:0 0 14px">
|
||||
<strong>维护台</strong>:巡检 / 批量补号排队与异常写入 <code>maintain/data/maintain_runtime.log</code>。<br />
|
||||
<strong>流水线</strong>:<code>run.py</code> 的 stdout/stderr 及迁出记录写入 SQLite 里的 <code>pipeline_log_file</code>(默认 <code>maintain/data/pipeline.log</code>)。<br />
|
||||
服务器上也可 <code>tail -f maintain/data/maintain_runtime.log</code> 实时看。
|
||||
</p>
|
||||
<div class="row" style="flex-wrap:wrap;margin-bottom:10px">
|
||||
<label style="margin:0;display:flex;align-items:center;gap:8px;width:auto">
|
||||
来源
|
||||
<select id="logSource" style="width:auto;min-width:220px;margin:0">
|
||||
<option value="runtime">维护台 runtime</option>
|
||||
<option value="pipeline">流水线 pipeline</option>
|
||||
</select>
|
||||
</label>
|
||||
<label style="margin:0;display:flex;align-items:center;gap:8px;width:auto">
|
||||
行数
|
||||
<input type="number" id="logLines" min="50" max="2000" value="400" style="width:90px;margin:0" />
|
||||
</label>
|
||||
<button class="primary" type="button" id="btnLogReload" style="margin:0">加载日志</button>
|
||||
<div class="row" style="margin:0"><input type="checkbox" id="logAuto" /><label for="logAuto" style="margin:0">本页打开时每 15 秒自动加载</label></div>
|
||||
</div>
|
||||
<div id="logPath" style="font-size:0.75rem;color:var(--muted);margin-bottom:8px"></div>
|
||||
<pre class="log-pre" id="logPre">(点「加载日志」)</pre>
|
||||
</div>
|
||||
</div>
|
||||
<div id="section-sec" class="section">
|
||||
<div class="panel">
|
||||
<h3>安全</h3>
|
||||
<p style="color:var(--muted);font-size:0.9rem;line-height:1.6">
|
||||
登录密码由环境变量 <code>CODEX_MAINTAIN_PASSWORD</code> 控制(默认 <code>admin</code>)。<br />
|
||||
生产环境请同时设置 <code>CODEX_MAINTAIN_SECRET</code> 作为会话密钥。
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
<div class="toast" id="toast"></div>
|
||||
<script>
|
||||
const $ = (id) => document.getElementById(id);
|
||||
let lastOverview = null;
|
||||
|
||||
function toast(msg) {
|
||||
const t = $('toast');
|
||||
t.textContent = msg;
|
||||
t.style.display = 'block';
|
||||
clearTimeout(t._h);
|
||||
t._h = setTimeout(() => { t.style.display = 'none'; }, 3200);
|
||||
}
|
||||
function esc(s) {
|
||||
return String(s ?? '').replace(/&/g, '&').replace(/</g, '<').replace(/"/g, '"');
|
||||
}
|
||||
async function api(path, opt) {
|
||||
const r = await fetch(path, { credentials: 'same-origin', ...opt, headers: { 'Content-Type': 'application/json', ...(opt && opt.headers || {}) } });
|
||||
if (r.status === 401) { location.href = '/'; return null; }
|
||||
return r;
|
||||
}
|
||||
|
||||
/** 仅写表单:首次进入、点「同步表单」、或某块保存后按区块更新 */
|
||||
function applySettingsToForms(st, sections) {
|
||||
const all = sections === 'all';
|
||||
if (all || sections.includes('inspect')) {
|
||||
$('autoEn').checked = st.auto_inspect_enabled === '1';
|
||||
$('intervalMin').value = st.inspect_interval_min;
|
||||
}
|
||||
if (all || sections.includes('run')) {
|
||||
$('cfgMaxAutoReg').value = st.max_auto_register_per_tick || '30';
|
||||
$('cfgThreads').value = st.default_threads;
|
||||
$('cfgSkipOauth').checked = st.skip_oauth === '1';
|
||||
$('cfgDefaultProxy').value = st.manual_default_proxy || '';
|
||||
}
|
||||
if (all || sections.includes('pipe')) {
|
||||
$('pipeAuto').checked = st.pipeline_auto_enabled === '1';
|
||||
$('pipeInterval').value = st.pipeline_interval_min || '10';
|
||||
$('pipePy').value = st.pipeline_python_bin || 'python3';
|
||||
$('pipeTimeout').value = st.run_subprocess_timeout_sec || '480';
|
||||
$('pipeExit0').checked = st.cpa_exit_on_empty === '1';
|
||||
$('pipeRunScript').value = st.pipeline_run_script || '';
|
||||
$('pipeOauth').value = st.pipeline_oauth_dir || '';
|
||||
$('pipeTarget').value = st.cpa_target_dir || '';
|
||||
$('pipeDing').value = st.dingtalk_webhook || '';
|
||||
$('pipeDingSec').value = st.dingtalk_secret || '';
|
||||
}
|
||||
if (all || sections.includes('clip')) {
|
||||
$('cfgStatsOauthDir').value = st.codex_stats_oauth_dir || '';
|
||||
$('cfgClipBase').value = st.cliproxy_management_base || '';
|
||||
$('cfgClipTimeout').value = st.cliproxy_probe_timeout_sec || '30';
|
||||
$('cfgClipKey').value = '';
|
||||
$('cfgClipKey').placeholder = st.cliproxy_management_key_set ? '已保存密钥(留空不改)' : '必填';
|
||||
}
|
||||
}
|
||||
|
||||
function renderDataOnly(j) {
|
||||
const s = j.stats;
|
||||
$('stTotal').textContent = s.total_accounts;
|
||||
$('stCand').textContent = s.total_candidates;
|
||||
const sub = $('stCandSub');
|
||||
if (s.inspect_probe_mode) {
|
||||
sub.textContent = '管理端探测 · 本地文件 ' + (s.total_accounts_raw ?? '') + (s.inspect_last_at ? ' · ' + new Date(s.inspect_last_at).toLocaleString() : '');
|
||||
} else if (s.inspect_probe_pending) {
|
||||
sub.textContent = '已配置管理端,尚未完成探测 — 请点「立即巡检」';
|
||||
} else {
|
||||
sub.textContent = '';
|
||||
}
|
||||
$('stTarget').textContent = s.total_target;
|
||||
$('stHealth').textContent = s.global_health_pct + '%';
|
||||
$('stHealthLbl').textContent = s.global_status;
|
||||
const dh = $('oauthStatsDirHint');
|
||||
if (dh && s.oauth_stats_dir) {
|
||||
dh.textContent = s.oauth_stats_dir_is_default
|
||||
? `统计/巡检目录(默认): ${s.oauth_stats_dir}`
|
||||
: `统计/巡检目录(自定义,应与 Cliproxy auth 一致): ${s.oauth_stats_dir}`;
|
||||
} else if (dh) {
|
||||
dh.textContent = '';
|
||||
}
|
||||
|
||||
const tb = $('cpaBody');
|
||||
tb.innerHTML = '';
|
||||
const sel = $('manualCpa');
|
||||
const keep = sel.value;
|
||||
sel.innerHTML = '';
|
||||
for (const c of s.cpas) {
|
||||
const tr = document.createElement('tr');
|
||||
const tag = c.status === '健康' ? 'ok' : (c.status === '偏低' ? 'warn' : 'bad');
|
||||
const candCell = (c.raw_candidates != null && c.raw_candidates !== c.candidates)
|
||||
? `${c.candidates} <span style="color:var(--muted)">/ 文件 ${c.raw_candidates}</span>`
|
||||
: `${c.candidates}`;
|
||||
tr.innerHTML = `<td>${esc(c.name)}${c.api_base_url ? `<div style="color:var(--muted);font-size:0.75rem">${esc(c.api_base_url)}</div>` : ''}</td><td>${candCell}</td><td>${c.target_count}</td><td>${c.health_pct}%</td><td>${c.gap}</td><td><span class="tag ${tag}">${c.status}</span></td><td><button class="ghost" data-edit="${c.id}">改目标</button></td>`;
|
||||
tb.appendChild(tr);
|
||||
const o = document.createElement('option');
|
||||
o.value = c.id;
|
||||
o.textContent = `${c.name} (${c.code})`;
|
||||
sel.appendChild(o);
|
||||
}
|
||||
if (keep && [...sel.options].some(o => o.value === keep)) sel.value = keep;
|
||||
if (s.cpas.length <= 1) {
|
||||
$('manualCpaWrap').style.display = 'none';
|
||||
$('manualCpaSingle').style.display = 'block';
|
||||
$('manualCpaSingle').textContent = s.cpas.length === 1
|
||||
? `补号计入:${s.cpas[0].name}`
|
||||
: '请先在数据库中配置账号池';
|
||||
} else {
|
||||
$('manualCpaWrap').style.display = 'block';
|
||||
$('manualCpaSingle').style.display = 'none';
|
||||
}
|
||||
$('btnManual').disabled = !s.cpas.length;
|
||||
document.querySelectorAll('#cpaBody [data-edit]').forEach(btn => {
|
||||
btn.onclick = async () => {
|
||||
const id = +btn.dataset.edit;
|
||||
const row = lastOverview.stats.cpas.find(x => x.id === id);
|
||||
const v = prompt('新目标阈值', row.target_count);
|
||||
if (v == null) return;
|
||||
const rr = await api(`/api/cpas/${id}`, { method: 'PUT', body: JSON.stringify({ target_count: parseInt(v, 10) }) });
|
||||
if (rr && rr.ok) { toast('已保存'); await refreshData(); }
|
||||
};
|
||||
});
|
||||
|
||||
if (j.pipeline) {
|
||||
const p = j.pipeline;
|
||||
const pst = p.state || {};
|
||||
const ts = pst.last_run_at ? new Date(pst.last_run_at * 1000).toLocaleString() : '-';
|
||||
const rb = p.register_busy ? '补号中' : '';
|
||||
const pb = p.lock_busy ? '流水线中' : '';
|
||||
const ib = p.inspect_busy ? '巡检中' : '';
|
||||
const busy = [rb, pb, ib].filter(Boolean).join(' ') || '空闲';
|
||||
$('pipeHint').textContent = `上次 ${ts} | 迁出 ${pst.last_run_moved ?? 0} | 码 ${pst.last_run_return_code ?? '-'} | ${busy}`;
|
||||
$('pipeStatus').textContent = [
|
||||
`上次运行: ${ts}`,
|
||||
`迁出 JSON: ${pst.last_run_moved ?? 0}`,
|
||||
`返回码: ${pst.last_run_return_code ?? '-'}`,
|
||||
`错误: ${pst.last_error || '-'}`,
|
||||
`锁: ${p.lock_busy ? '占用' : '空闲'}`,
|
||||
`定时: ${p.auto_enabled ? '开' : '关'} / 间隔 ${p.interval_min} 分`,
|
||||
`run.py → ${p.paths.run_script}`,
|
||||
`OAuth → ${p.paths.oauth_dir}`,
|
||||
`目标 → ${p.paths.target_dir}`,
|
||||
`钉钉: ${p.dingtalk_configured ? '已配置' : '未配置'}`,
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
const ban = $('taskBanner');
|
||||
const at = j.active_task;
|
||||
if (at && (at.status === 'running' || at.status === 'queued')) {
|
||||
ban.classList.remove('idle');
|
||||
const name = at.cpa_name ? `池: ${at.cpa_name}` : '';
|
||||
const prog = (at.total > 0) ? ` ${at.done ?? 0}/${at.total}` : '';
|
||||
ban.textContent = `进行中 #${at.id} ${at.task_type} ${name}${prog} — ${at.message || ''}`;
|
||||
} else {
|
||||
ban.classList.add('idle');
|
||||
ban.textContent = '';
|
||||
}
|
||||
|
||||
const rtb = $('recentTasksBody');
|
||||
rtb.innerHTML = '';
|
||||
const list = j.recent_tasks || [];
|
||||
if (!list.length) {
|
||||
const tr = document.createElement('tr');
|
||||
tr.innerHTML = '<td colspan="6" style="color:var(--muted)">暂无任务记录</td>';
|
||||
rtb.appendChild(tr);
|
||||
} else {
|
||||
for (const t of list) {
|
||||
const tr = document.createElement('tr');
|
||||
const stCls = t.status === 'error' ? 'st-err' : (t.status === 'running' || t.status === 'queued' ? 'st-run' : 'st-done');
|
||||
const ts = t.updated_at ? new Date(t.updated_at).toLocaleString() : '—';
|
||||
const prog = (t.total > 0) ? `${t.done ?? 0} / ${t.total}` : '—';
|
||||
tr.innerHTML = `<td>${t.id}</td><td>${esc(t.task_type)}</td><td class="${stCls}">${esc(t.status)}</td><td>${prog}</td><td class="task-msg" title="${esc(t.message)}">${esc(t.message)}</td><td style="color:var(--muted);white-space:nowrap">${ts}</td>`;
|
||||
rtb.appendChild(tr);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function refreshData() {
|
||||
const r = await api('/api/overview');
|
||||
if (!r || !r.ok) return;
|
||||
lastOverview = await r.json();
|
||||
renderDataOnly(lastOverview);
|
||||
}
|
||||
|
||||
document.querySelectorAll('.tabs button').forEach(b => {
|
||||
b.onclick = () => {
|
||||
document.querySelectorAll('.tabs button').forEach(x => x.classList.remove('active'));
|
||||
b.classList.add('active');
|
||||
document.querySelectorAll('.section').forEach(s => s.classList.remove('visible'));
|
||||
$('section-' + b.dataset.tab).classList.add('visible');
|
||||
};
|
||||
});
|
||||
|
||||
$('btnRefreshData').onclick = () => refreshData();
|
||||
$('btnSyncForms').onclick = async () => {
|
||||
await refreshData();
|
||||
if (lastOverview && lastOverview.settings) {
|
||||
applySettingsToForms(lastOverview.settings, 'all');
|
||||
toast('表单已与服务器同步');
|
||||
}
|
||||
};
|
||||
$('btnLogout').onclick = async () => { await api('/api/logout', { method: 'POST', body: '{}' }); location.href = '/'; };
|
||||
|
||||
$('saveInspect').onclick = async () => {
|
||||
await api('/api/settings', { method: 'POST', body: JSON.stringify({
|
||||
auto_inspect_enabled: $('autoEn').checked ? '1' : '0',
|
||||
inspect_interval_min: $('intervalMin').value,
|
||||
}) });
|
||||
toast('巡检设置已保存');
|
||||
await refreshData();
|
||||
if (lastOverview) applySettingsToForms(lastOverview.settings, ['inspect']);
|
||||
};
|
||||
$('saveConfig').onclick = async () => {
|
||||
await api('/api/settings', { method: 'POST', body: JSON.stringify({
|
||||
max_auto_register_per_tick: $('cfgMaxAutoReg').value,
|
||||
default_threads: $('cfgThreads').value,
|
||||
skip_oauth: $('cfgSkipOauth').checked ? '1' : '0',
|
||||
manual_default_proxy: $('cfgDefaultProxy').value.trim(),
|
||||
}) });
|
||||
toast('配置已保存');
|
||||
await refreshData();
|
||||
if (lastOverview) applySettingsToForms(lastOverview.settings, ['run']);
|
||||
};
|
||||
$('saveCliproxy').onclick = async () => {
|
||||
const body = {
|
||||
codex_stats_oauth_dir: $('cfgStatsOauthDir').value.trim(),
|
||||
cliproxy_management_base: $('cfgClipBase').value.trim(),
|
||||
cliproxy_probe_timeout_sec: $('cfgClipTimeout').value,
|
||||
};
|
||||
const k = $('cfgClipKey').value;
|
||||
if (k) body.cliproxy_management_key = k;
|
||||
await api('/api/settings', { method: 'POST', body: JSON.stringify(body) });
|
||||
toast('Cliproxy 设置已保存');
|
||||
await refreshData();
|
||||
if (lastOverview) applySettingsToForms(lastOverview.settings, ['clip']);
|
||||
};
|
||||
$('btnInspectNow').onclick = async () => {
|
||||
const r = await api('/api/tasks/inspect-now', { method: 'POST', body: '{}' });
|
||||
if (!r) return;
|
||||
const j = await r.json();
|
||||
if (r.status === 400) { toast(j.error || '配置不全'); return; }
|
||||
if (r.status === 409) { toast(j.error || '忙'); return; }
|
||||
toast(j.message || '已排队');
|
||||
refreshData();
|
||||
};
|
||||
$('btnManual').onclick = async () => {
|
||||
const r = await api('/api/tasks/manual', { method: 'POST', body: JSON.stringify({
|
||||
cpa_id: parseInt($('manualCpa').value, 10),
|
||||
count: parseInt($('manualCount').value, 10),
|
||||
use_proxy_pool: $('manualS5').checked,
|
||||
}) });
|
||||
if (!r) return;
|
||||
const j = await r.json().catch(() => ({}));
|
||||
if (r.status === 409) { toast(j.error || '忙'); return; }
|
||||
if (!r.ok) { toast(j.error || '失败'); return; }
|
||||
toast('任务已启动');
|
||||
refreshData();
|
||||
};
|
||||
$('savePipe').onclick = async () => {
|
||||
await api('/api/settings', { method: 'POST', body: JSON.stringify({
|
||||
pipeline_auto_enabled: $('pipeAuto').checked ? '1' : '0',
|
||||
pipeline_interval_min: $('pipeInterval').value,
|
||||
pipeline_python_bin: $('pipePy').value.trim(),
|
||||
run_subprocess_timeout_sec: $('pipeTimeout').value,
|
||||
cpa_exit_on_empty: $('pipeExit0').checked ? '1' : '0',
|
||||
pipeline_run_script: $('pipeRunScript').value.trim(),
|
||||
pipeline_oauth_dir: $('pipeOauth').value.trim(),
|
||||
cpa_target_dir: $('pipeTarget').value.trim(),
|
||||
dingtalk_webhook: $('pipeDing').value.trim(),
|
||||
dingtalk_secret: $('pipeDingSec').value.trim(),
|
||||
}) });
|
||||
toast('流水线设置已保存');
|
||||
await refreshData();
|
||||
if (lastOverview) applySettingsToForms(lastOverview.settings, ['pipe']);
|
||||
};
|
||||
$('btnPipeOnce').onclick = async () => {
|
||||
const r = await api('/api/pipeline/run-once', { method: 'POST', body: '{}' });
|
||||
if (!r) return;
|
||||
const j = await r.json().catch(() => ({}));
|
||||
if (r.status === 409) { toast(j.error || '忙'); return; }
|
||||
if (!r.ok) { toast(j.error || '失败'); return; }
|
||||
toast('流水线任务已启动');
|
||||
refreshData();
|
||||
};
|
||||
|
||||
async function loadProxies() {
|
||||
const r = await api('/api/proxies');
|
||||
if (!r || !r.ok) return;
|
||||
const j = await r.json();
|
||||
const el = $('proxyList');
|
||||
el.innerHTML = '';
|
||||
for (const p of j.proxies) {
|
||||
const div = document.createElement('div');
|
||||
div.className = 'proxy-item';
|
||||
div.innerHTML = `<span>${esc(p.url)} <span style="color:var(--muted)">${esc(p.label)}</span></span><button class="ghost" data-del="${p.id}">删除</button>`;
|
||||
el.appendChild(div);
|
||||
}
|
||||
el.querySelectorAll('[data-del]').forEach(b => {
|
||||
b.onclick = async () => {
|
||||
await fetch('/api/proxies/' + b.dataset.del, { method: 'DELETE', credentials: 'same-origin' });
|
||||
loadProxies();
|
||||
};
|
||||
});
|
||||
}
|
||||
$('btnAddProxy').onclick = async () => {
|
||||
const url = $('newProxyUrl').value.trim();
|
||||
if (!url) return;
|
||||
await api('/api/proxies', { method: 'POST', body: JSON.stringify({ url, label: $('newProxyLabel').value.trim() }) });
|
||||
$('newProxyUrl').value = '';
|
||||
$('newProxyLabel').value = '';
|
||||
toast('已添加');
|
||||
loadProxies();
|
||||
};
|
||||
document.querySelector('[data-tab="proxy"]').addEventListener('click', loadProxies);
|
||||
|
||||
let logAutoTimer = null;
|
||||
async function loadLogTail() {
|
||||
const name = $('logSource').value;
|
||||
const lines = $('logLines').value || '400';
|
||||
const r = await api(
|
||||
`/api/logs/tail?name=${encodeURIComponent(name)}&lines=${encodeURIComponent(lines)}`
|
||||
);
|
||||
if (!r || !r.ok) {
|
||||
$('logPre').textContent = r ? ('加载失败 HTTP ' + r.status) : '未登录或网络错误';
|
||||
return;
|
||||
}
|
||||
const j = await r.json();
|
||||
if (j.error) {
|
||||
$('logPre').textContent = j.error;
|
||||
$('logPath').textContent = '';
|
||||
return;
|
||||
}
|
||||
$('logPath').textContent = j.path || '';
|
||||
$('logPre').textContent = j.content || '';
|
||||
}
|
||||
$('btnLogReload').onclick = () => loadLogTail();
|
||||
function syncLogAutoTimer() {
|
||||
clearInterval(logAutoTimer);
|
||||
logAutoTimer = null;
|
||||
if ($('logAuto').checked) {
|
||||
logAutoTimer = setInterval(() => {
|
||||
if ($('section-logs').classList.contains('visible')) loadLogTail();
|
||||
}, 15000);
|
||||
}
|
||||
}
|
||||
$('logAuto').onchange = syncLogAutoTimer;
|
||||
document.querySelector('[data-tab="logs"]').addEventListener('click', () => {
|
||||
loadLogTail();
|
||||
syncLogAutoTimer();
|
||||
});
|
||||
|
||||
(async () => {
|
||||
await refreshData();
|
||||
if (lastOverview && lastOverview.settings) {
|
||||
applySettingsToForms(lastOverview.settings, 'all');
|
||||
}
|
||||
})();
|
||||
setInterval(refreshData, 8000);
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,36 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>登录 — Codex 自动维护</title>
|
||||
<style>
|
||||
* { box-sizing: border-box; }
|
||||
body { font-family: system-ui, sans-serif; background: #0f1419; color: #e6edf3; min-height: 100vh; display: flex; align-items: center; justify-content: center; margin: 0; }
|
||||
.card { background: #161b22; border: 1px solid #30363d; border-radius: 12px; padding: 2rem; width: 100%; max-width: 360px; }
|
||||
h1 { margin: 0 0 1rem; font-size: 1.25rem; }
|
||||
input { width: 100%; padding: 10px 12px; border-radius: 8px; border: 1px solid #30363d; background: #0d1117; color: #e6edf3; margin-bottom: 1rem; }
|
||||
button { width: 100%; padding: 10px; border: 0; border-radius: 8px; background: #238636; color: #fff; font-weight: 600; cursor: pointer; }
|
||||
button:hover { background: #2ea043; }
|
||||
.err { color: #f85149; font-size: 0.875rem; margin-top: 0.5rem; display: none; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="card">
|
||||
<h1>Codex 自动维护</h1>
|
||||
<input type="password" id="pw" placeholder="密码" autocomplete="current-password" />
|
||||
<button type="button" id="go">登录</button>
|
||||
<p class="err" id="err"></p>
|
||||
</div>
|
||||
<script>
|
||||
document.getElementById('go').onclick = async () => {
|
||||
const err = document.getElementById('err');
|
||||
err.style.display = 'none';
|
||||
const r = await fetch('/api/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ password: document.getElementById('pw').value }) });
|
||||
if (r.ok) location.href = '/';
|
||||
else { err.textContent = '密码错误'; err.style.display = 'block'; }
|
||||
};
|
||||
document.getElementById('pw').addEventListener('keydown', e => { if (e.key === 'Enter') document.getElementById('go').click(); });
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,48 @@
|
||||
#!/usr/bin/env python3
|
||||
"""验证批量补号链路:run_batch 并行、计数、register context 清理(不真实打注册接口)。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
if ROOT not in sys.path:
|
||||
sys.path.insert(0, ROOT)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
import run as run_module
|
||||
from maintain.batch_register import run_batch
|
||||
|
||||
calls: list[int] = []
|
||||
|
||||
def fake_do_one(index: int, config, proxy: str, skip_oauth: bool) -> dict:
|
||||
calls.append(index)
|
||||
run_module._counter["success"] += 1
|
||||
return {}
|
||||
|
||||
orig = run_module._do_one
|
||||
run_module._do_one = fake_do_one # type: ignore[assignment]
|
||||
try:
|
||||
ok, fail = run_batch(
|
||||
count=5,
|
||||
threads=3,
|
||||
proxy="",
|
||||
skip_oauth=False,
|
||||
cpa_id=1,
|
||||
cpa_code="default",
|
||||
on_progress=None,
|
||||
)
|
||||
assert ok == 5 and fail == 0, (ok, fail)
|
||||
assert len(calls) == 5 and set(calls) == {1, 2, 3, 4, 5}, calls
|
||||
assert getattr(run_module._register_ctx, "cpa_id", None) is None
|
||||
assert getattr(run_module._register_ctx, "cpa_code", None) is None
|
||||
finally:
|
||||
run_module._do_one = orig # type: ignore[assignment]
|
||||
|
||||
print("verify_batch_register: OK (mocked _do_one, count=5 threads=3)")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -1,2 +1,4 @@
|
||||
curl_cffi>=0.7.0
|
||||
requests>=2.31.0
|
||||
flask>=3.0.0
|
||||
apscheduler>=3.10.0
|
||||
@@ -18,10 +18,10 @@ from datetime import datetime, timezone, timedelta
|
||||
# ║ 修改以下变量即可,直接 python run.py 运行 ║
|
||||
# ╚══════════════════════════════════════════════════════════╝
|
||||
|
||||
THREADS = 8 # 并行线程数 (1 = 单线程顺序执行)
|
||||
COUNT = 16 # 注册账号数量
|
||||
THREADS = 1 # 并行线程数 (1 = 单线程顺序执行)
|
||||
COUNT = 50 # 注册账号数量
|
||||
SKIP_OAUTH = False # True = 只注册不做 OAuth 获取 token
|
||||
PROXY = "http://127.0.0.1:10808" # 代理地址
|
||||
PROXY = "http://127.0.0.1:7897" # 代理地址
|
||||
|
||||
# ══════════════════════════════════════════════════════════
|
||||
|
||||
@@ -37,6 +37,28 @@ ACCOUNTS_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "account
|
||||
_lock = threading.Lock()
|
||||
_counter = {"success": 0, "failed": 0}
|
||||
|
||||
# 供控制台批量任务写入 cpa_id / cpa_code(线程局部,避免并行任务互相污染)
|
||||
_register_ctx = threading.local()
|
||||
|
||||
|
||||
def set_register_context(*, cpa_id: int | None = None, cpa_code: str | None = None) -> None:
|
||||
_register_ctx.cpa_id = cpa_id
|
||||
_register_ctx.cpa_code = cpa_code
|
||||
|
||||
|
||||
def clear_register_context() -> None:
|
||||
_register_ctx.cpa_id = None
|
||||
_register_ctx.cpa_code = None
|
||||
|
||||
|
||||
def _merge_register_context(record: dict) -> None:
|
||||
cid = getattr(_register_ctx, "cpa_id", None)
|
||||
code = getattr(_register_ctx, "cpa_code", None)
|
||||
if cid is not None:
|
||||
record["cpa_id"] = cid
|
||||
if code:
|
||||
record["cpa_code"] = code
|
||||
|
||||
|
||||
def do_register(config: RegisterConfig) -> RegisterResult:
|
||||
reg = AccountRegister(config=config)
|
||||
@@ -75,9 +97,11 @@ def _decode_jwt_payload(token: str) -> dict:
|
||||
return {}
|
||||
|
||||
|
||||
def _email_to_filename(email: str) -> str:
|
||||
"""将邮箱转为文件名: @ 和 . 替换为 _"""
|
||||
return email.replace("@", "_").replace(".", "_")
|
||||
def _email_to_filename(email: str | None) -> str:
|
||||
"""将邮箱转为文件名: @ 和 . 替换为 _;空值回退 unknown"""
|
||||
if not email:
|
||||
return "unknown"
|
||||
return str(email).replace("@", "_").replace(".", "_")
|
||||
|
||||
|
||||
def save_account(record: dict, *, is_failed: bool = False):
|
||||
@@ -96,6 +120,7 @@ def save_account(record: dict, *, is_failed: bool = False):
|
||||
target_dir = os.path.join(ACCOUNTS_DIR, subdir)
|
||||
os.makedirs(target_dir, exist_ok=True)
|
||||
|
||||
_merge_register_context(record)
|
||||
email = record.get("email", "unknown")
|
||||
filename = _email_to_filename(email)
|
||||
filepath = os.path.join(target_dir, f"{filename}.json")
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
#!/usr/bin/env python3
|
||||
"""CPA 定时同步入口:定时执行 run.py,迁出 oauth JSON,钉钉通知。
|
||||
|
||||
用法:
|
||||
cd /path/to/protocol_chatgpt
|
||||
pip install -r requirements.txt
|
||||
cp .env.cpa-runner.example .env.cpa-runner # 按需修改
|
||||
python scripts/cpa_runner.py
|
||||
|
||||
若维护台已开启「流水线 → 启用定时流水线」,请勿再运行本脚本(会抢同一套 oauth 目录与全局锁逻辑外的文件锁)。
|
||||
|
||||
仅在不跑 `python -m maintain`、或维护台未启用定时流水线时使用;勿起第二个 cpa_runner(`cpa_runner.lock`)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
REPO = Path(__file__).resolve().parent.parent
|
||||
sys.path.insert(0, str(REPO))
|
||||
|
||||
from maintain.cpa_runner_core import main_blocking # noqa: E402
|
||||
|
||||
if __name__ == "__main__":
|
||||
main_blocking()
|
||||
Reference in new issue
Block a user