|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""启动前自检(只读):部署卡死时先跑这一条。 |
| 3 | +
|
| 4 | +与 `create_user.py` / `backup_db.py` 同目录同风格。**绝不写库、不迁移、不启服务、 |
| 5 | +不落凭证明文**——doctor 自己变成故障源就失去意义了。 |
| 6 | +
|
| 7 | +用法: |
| 8 | + python3 scripts/doctor.py # 全量检查 |
| 9 | + python3 scripts/doctor.py --skip-upstream # 离线部署:跳过上游连通性 |
| 10 | + python3 scripts/doctor.py --json # 机读输出(CI 用) |
| 11 | + python3 scripts/doctor.py --port 8000 # 指定要探测的端口 |
| 12 | +
|
| 13 | +退出码:0 = 没有 FAIL(WARN 不拦);1 = 有 FAIL。 |
| 14 | +""" |
| 15 | + |
| 16 | +from __future__ import annotations |
| 17 | + |
| 18 | +import argparse |
| 19 | +import json |
| 20 | +import sys |
| 21 | +from pathlib import Path |
| 22 | + |
| 23 | +from pydantic import ValidationError |
| 24 | + |
| 25 | +sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) |
| 26 | + |
| 27 | +from src import doctor # noqa: E402 |
| 28 | +from src.config import Settings, load_settings # noqa: E402 |
| 29 | +from src.webapp.static import frontend_dist # noqa: E402 |
| 30 | + |
| 31 | +#: 需要探测连通性的渠道端点。只取配置里的**当前**端点,不枚举白名单: |
| 32 | +#: 白名单里可能有用户永远不用的站点,逐条探测只会制造噪声与慢启动。 |
| 33 | +_UPSTREAM_FIELDS = ( |
| 34 | + ("codebuddy", "codebuddy_api_endpoint"), |
| 35 | + ("codebuddy_intl", "codebuddy_intl_api_endpoint"), |
| 36 | + ("zen", "zen_api_endpoint"), |
| 37 | + ("kilo", "kilo_api_endpoint"), |
| 38 | + ("qoder", "qoder_api_endpoint"), |
| 39 | + ("codearts", "codearts_api_endpoint"), |
| 40 | + ("officeace", "officeace_api_endpoint"), |
| 41 | + ("raccoon", "raccoon_api_endpoint"), |
| 42 | + ("lingxi", "lingxi_api_endpoint"), |
| 43 | +) |
| 44 | + |
| 45 | + |
| 46 | +def upstream_endpoints(settings: Settings) -> list[tuple[str, str]]: |
| 47 | + """配置里当前生效的渠道端点(去重,保持声明顺序)。""" |
| 48 | + seen: set[str] = set() |
| 49 | + endpoints: list[tuple[str, str]] = [] |
| 50 | + for name, field in _UPSTREAM_FIELDS: |
| 51 | + url = getattr(settings, field, "").strip() |
| 52 | + if not url or url in seen: |
| 53 | + continue |
| 54 | + seen.add(url) |
| 55 | + endpoints.append((name, url)) |
| 56 | + return endpoints |
| 57 | + |
| 58 | + |
| 59 | +def collect(settings: Settings, *, port: int | None = None, |
| 60 | + skip_upstream: bool = False) -> list[doctor.Check]: |
| 61 | + """跑完全部检查;任一项内部异常都折算成 FAIL 而不是让脚本崩掉。""" |
| 62 | + checks = [ |
| 63 | + doctor.check_python(sys.version_info[:3]), |
| 64 | + doctor.check_dependencies(), |
| 65 | + doctor.check_app_secret(settings), |
| 66 | + doctor.check_data_dir(settings), |
| 67 | + doctor.check_data_permissions(settings), |
| 68 | + doctor.check_host_config(settings), |
| 69 | + doctor.check_database(settings), |
| 70 | + doctor.check_port(settings.host, settings.port if port is None else port), |
| 71 | + doctor.check_frontend(frontend_dist()), |
| 72 | + ] |
| 73 | + if not skip_upstream: |
| 74 | + checks.extend(doctor.check_upstreams(upstream_endpoints(settings))) |
| 75 | + return checks |
| 76 | + |
| 77 | + |
| 78 | +def render(checks: list[doctor.Check], *, as_json: bool = False) -> str: |
| 79 | + """排版:JSON 给 CI,纯文本给人。""" |
| 80 | + if as_json: |
| 81 | + return json.dumps( |
| 82 | + [{"name": c.name, "status": c.status, "detail": c.detail} for c in checks], |
| 83 | + ensure_ascii=False, indent=2) |
| 84 | + width = max(len(c.name) for c in checks) if checks else 0 |
| 85 | + lines = [f"[{c.status}] {c.name.ljust(width)} {c.detail}".rstrip() for c in checks] |
| 86 | + return "\n".join(lines) |
| 87 | + |
| 88 | + |
| 89 | +def summarize(checks: list[doctor.Check]) -> str: |
| 90 | + """"N 项通过 / M 项警告 / K 项失败"。""" |
| 91 | + passed = sum(1 for c in checks if c.status == doctor.PASS) |
| 92 | + warned = sum(1 for c in checks if c.status == doctor.WARN) |
| 93 | + failed = sum(1 for c in checks if c.status == doctor.FAIL) |
| 94 | + return f"{passed} 项通过,{warned} 项警告,{failed} 项失败" |
| 95 | + |
| 96 | + |
| 97 | +def load_settings_tolerant() -> tuple[Settings, str | None]: |
| 98 | + """构造 Settings;`APP_SECRET` 缺失时降级为占位值并返回原因。 |
| 99 | +
|
| 100 | + doctor 的用途之一就是**诊断 `APP_SECRET` 没配**——若这里直接让 |
| 101 | + pydantic 的 `ValidationError` 打出来,其余六项检查全被挡住,等于在最需要 |
| 102 | + 自检的场景下自检不可用。降级后用 `CredentialCipher` 判定为 FAIL 并继续跑。 |
| 103 | + """ |
| 104 | + try: |
| 105 | + return load_settings(), None |
| 106 | + except ValidationError: |
| 107 | + # `.env` 里其它键在这次降级里读不到:APP_SECRET 是唯一必填项, |
| 108 | + # 缺它基本等价于「还没建 .env」,其余项按默认值检查即可。 |
| 109 | + return Settings(_env_file=None, APP_SECRET=""), "APP_SECRET 未配置" |
| 110 | + |
| 111 | + |
| 112 | +def main(argv: list[str] | None = None) -> int: |
| 113 | + parser = argparse.ArgumentParser(description="启动前自检(只读,不启服务)") |
| 114 | + parser.add_argument("--port", type=int, help="要探测的端口(默认取 PORT)") |
| 115 | + parser.add_argument("--skip-upstream", action="store_true", |
| 116 | + help="跳过上游连通性探测(离线部署)") |
| 117 | + parser.add_argument("--json", action="store_true", help="以 JSON 输出") |
| 118 | + args = parser.parse_args(argv) |
| 119 | + |
| 120 | + settings, problem = load_settings_tolerant() |
| 121 | + if problem is not None: |
| 122 | + print(f"配置读取降级:{problem};其余检查按默认值继续", file=sys.stderr) |
| 123 | + checks = collect(settings, port=args.port, skip_upstream=args.skip_upstream) |
| 124 | + print(render(checks, as_json=args.json)) |
| 125 | + if not args.json: |
| 126 | + print(summarize(checks)) |
| 127 | + return 0 if all(c.ok for c in checks) else 1 |
| 128 | + |
| 129 | + |
| 130 | +if __name__ == "__main__": |
| 131 | + raise SystemExit(main()) |
0 commit comments