unis-oa/backend/scripts/what_config.py

122 lines
5.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#!/usr/bin/env python3
"""部署自查:这一趟到底读的哪一份配置文件。
换环境、装 systemd、发版之后先跑它一眼看明白:环境是哪一档、叠了哪几份文件、
关键引导项的生效值是谁给的、生产档还有哪些没改。
python3 scripts/what_config.py 按当前环境变量打印
OA_ENV=prod python3 scripts/what_config.py 假装是生产档,先看会读哪两份
OA_CONFIG_DIR=/etc/unisoa python3 scripts/what_config.py
python3 scripts/what_config.py --check 有体检告警就退出码 1(部署脚本当闸门)
只读配置文件与环境变量:不连数据库、不起服务、不看界面上保存过的运行配置,
所以随时能跑,也不会改到任何东西。口令与密钥只说"配了没有",永不打印值。
"""
from __future__ import annotations
import argparse
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[0].parent))
from app import config # noqa: E402
#: 每份配置文件在整叠里扮演什么角色
PURPOSE_NOTES = {
"base": "公共基础值,各环境共用",
"env": "本环境差异,逐键盖在基础值上",
"single": "OA_CONFIG 指定的文件,只读它这一份",
}
#: 某一项的出厂值来自哪一层(config.layer_of 的返回值)
LAYER_LABELS = {
"base": "基础文件",
"override": "挂载目录里的基础文件",
"env_code": "代码目录里的本档文件",
"env": "本环境文件",
"single": "指定文件",
"": "代码默认值",
}
def _switch(value: object) -> str:
"""引导项的开关值:``bootstrap_value`` 已经按默认值类型洗成 bool 了。"""
return "开" if value else "关"
def _set(name: str) -> bool:
return bool(str(config.bootstrap_value(name) or "").strip())
def report() -> list[str]:
"""一页自述。密钥与口令只报配了没有。"""
out: list[str] = []
out.append(f"环境 {config.env_name()}({config.env_source()})")
if config.is_production():
out.append(" 这一档算生产,启动会做上线体检")
out.append(f"主文件 {config.config_path()}")
layers = config.layers_view()
found = [layer for layer in layers if layer["loaded"]]
out.append(f"配置文件 {'按顺序叠,后一份盖在前一份上:' if len(layers) > 1 else '只有这一份:'}")
pad = " "
for layer in layers:
mark = "读到" if layer["loaded"] else "缺这档"
out.append(f"{pad}[{mark}] {layer['path']} —— {PURPOSE_NOTES.get(layer['purpose'], '')}")
secret = str(config.bootstrap_value("jwt_secret") or "")
out.append(
"MySQL "
f"{config.bootstrap_value('db_host')}:{config.bootstrap_value('db_port')}/{config.bootstrap_value('db_name')} "
f"账号 {config.bootstrap_value('db_user')} "
f"口令{'已配' if _set('db_password') else '未配'} "
f"自动建表{_switch(config.bootstrap_value('auto_create_schema'))} "
f"可建库名 {config.bootstrap_value('db_create_allowlist') or '(空 = 一个都不许建)'} "
f"({LAYER_LABELS.get(config.layer_of(('database', 'host')), '')})"
)
out.append(
f"监听 {config.bootstrap_value('host')}:{config.bootstrap_value('port')} "
f"({LAYER_LABELS.get(config.layer_of(('server', 'port')), '')})"
)
out.append(
f"令牌签名 {'已配' if secret.strip() else '未配'}({len(secret)} 位,"
f"{LAYER_LABELS.get(config.layer_of(('security', 'jwt_secret')))}) 算法 {config.bootstrap_value('jwt_algorithm')}"
)
named = config.bootstrap_explicit("admin_account")
out.append(
f"内置超管 {config.admin_account_name()}"
f"({'配置文件/环境变量点名改名' if named else '用数据库里记着的账号名'}) "
f"初始口令{'已配' if config.bootstrap_explicit('admin_password') else '未配,走默认值'}"
f"(只在库里首次建号时用) "
f"演示数据{_switch(config.bootstrap_value('seed_demo'))}"
)
fixed = config.env_overrides()
out.append("环境变量 " + (f"钉住了 {len(fixed)} 项:{'、'.join(fixed)}" if fixed else "没有钉住任何配置项"))
problems = config.warnings()
if problems:
out.append(f"上线体检 {len(problems)} 项待处理:")
out.extend(f" - {item}" for item in problems)
elif config.is_production():
out.append("上线体检 全部通过")
else:
out.append("上线体检 开发档不做(只有 prod / staging / gray 会查)")
out.append(" 注:界面上保存过的运行配置在数据库里,这里不看(跑起来才算)")
return out
def main() -> int:
parser = argparse.ArgumentParser(
description="看这一趟用的是哪一份配置文件(档位由 OA_ENV / OA_PROFILE 或 config.toml 的 [env] name 决定)"
)
parser.add_argument("--check", action="store_true", help="生产档体检没过就返回退出码 1,供部署脚本当闸门")
args = parser.parse_args()
print("\n".join(report()))
# 退出码只在 --check 时较真:默认这一趟只是"看一眼",有告警也报 0。
# 不然 scripts/prod-api.sh 那种 set -o pipefail 的启动脚本会先被启动前的
# 那句自查告警拦停,把"只提醒不拦启动"变成"提醒即拦停"。
return 1 if args.check and config.warnings() else 0
if __name__ == "__main__":
sys.exit(main())