194 lines
7.1 KiB
Python
194 lines
7.1 KiB
Python
"""配置接口:**配置存在数据库里,界面上保存后立刻生效,不用重启服务**。
|
||
|
||
三个口子:
|
||
|
||
* ``GET /api/v1/config`` 全量配置视图:值 + 中文说明 + 谁给的这个值
|
||
* ``PUT /api/v1/config/{group}`` 保存一组配置(site / security / hub / hub_sync / storage / server)
|
||
* ``POST /api/v1/config/reload`` 让本进程(或多进程部署里的每个进程)马上重读库
|
||
|
||
约定:值传 ``null`` = 把这一项从库里删掉、回落到配置文件与默认值;密钥类配置项
|
||
留空 = 不改这一项(接口从不回显明文)。引导配置(MySQL 地址、监听端口、JWT 密钥)
|
||
只读,改了要重启,原因见 :mod:`app.dbconfig`。
|
||
|
||
权限沿用 ``system:setting``;每次保存都写一条操作日志,日志里只有配置项名与新值,
|
||
密钥一律以"已修改"代替。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import logging
|
||
|
||
from fastapi import APIRouter, Depends, Request
|
||
from pydantic import BaseModel, ConfigDict
|
||
from sqlalchemy.orm import Session
|
||
|
||
from .. import dbconfig, hubconfig, storage
|
||
from ..storage import convert
|
||
from ..db import get_db
|
||
from ..deps import CurrentUser, client_ip, require_permission
|
||
from ..envelope import bad_request, ok
|
||
|
||
router = APIRouter(tags=["config"])
|
||
logger = logging.getLogger("unisoa.config.api")
|
||
|
||
|
||
class ConfigPatch(BaseModel):
|
||
"""一组配置的增量提交:没出现的配置项不动。
|
||
|
||
``values`` 是新写法;``value`` 是早期 ``PUT /settings/{key}`` 的字段名,
|
||
两个都收,老前端不用改。
|
||
"""
|
||
|
||
model_config = ConfigDict(extra="forbid")
|
||
|
||
values: dict[str, object] | None = None
|
||
value: dict[str, object] | None = None
|
||
|
||
def payload(self) -> dict[str, object]:
|
||
if self.values is not None:
|
||
return self.values
|
||
if self.value is not None:
|
||
return self.value
|
||
raise dbconfig.ConfigValidationError('要按 {"values": {"配置项": "值"}} 提交')
|
||
|
||
|
||
def _log_change(db: Session, user: CurrentUser, request: Request, group: str, changed: dict) -> None:
|
||
from .. import models
|
||
|
||
if not changed:
|
||
return
|
||
parts = []
|
||
for name, new_value in changed.items():
|
||
item = dbconfig.BY_NAME.get(name)
|
||
label = item.label if item else name
|
||
if item is not None and item.secret:
|
||
parts.append(f"{label}=(已更新,值不记录)" if new_value is not None else f"{label}=(已恢复默认)")
|
||
elif new_value is None:
|
||
parts.append(f"{label}=(已恢复默认)")
|
||
else:
|
||
parts.append(f"{label}={new_value}")
|
||
db.add(
|
||
models.OperationLog(
|
||
action="config_update",
|
||
target=f"config:{group}",
|
||
detail=";".join(parts)[:2000],
|
||
person=str(user.person.id),
|
||
person_name=user.display_name,
|
||
identity=user.ref,
|
||
ip=client_ip(request),
|
||
)
|
||
)
|
||
db.commit()
|
||
|
||
|
||
@router.get("/config")
|
||
def read_config(_: CurrentUser = Depends(require_permission("system:setting"))) -> dict:
|
||
"""当前生效的全部配置:值、中文说明、取值范围,以及这一项是谁给的。"""
|
||
return ok(dbconfig.view())
|
||
|
||
|
||
@router.get("/config/{group}")
|
||
def read_config_group(
|
||
group: str,
|
||
_: CurrentUser = Depends(require_permission("system:setting")),
|
||
) -> dict:
|
||
try:
|
||
return ok(dbconfig.group_view(group))
|
||
except dbconfig.ConfigValidationError as exc:
|
||
raise bad_request(str(exc)) from exc
|
||
|
||
|
||
@router.put("/config/{group}")
|
||
def update_config_group(
|
||
group: str,
|
||
body: ConfigPatch,
|
||
request: Request,
|
||
user: CurrentUser = Depends(require_permission("system:setting")),
|
||
db: Session = Depends(get_db),
|
||
) -> dict:
|
||
"""保存一组配置。**存库即生效**:附件落哪儿、Hub 走不走、上传上限多少,下一次请求就按新值走。"""
|
||
try:
|
||
changed = dbconfig.apply(db, group, body.payload())
|
||
except dbconfig.ConfigValidationError as exc:
|
||
raise bad_request(str(exc)) from exc
|
||
if group in {"storage", "server"}:
|
||
# 存储客户端与探活结果跟着新配置重建,免得继续吃旧连接
|
||
storage.reset_cache()
|
||
if group in {"preview", "storage"}:
|
||
# 「装了没有」这个结论缓存了 5 分钟:刚改过程序路径、或者刚在服务器上装完
|
||
# LibreOffice 就保存,得当场重探一次,否则界面上改了要等半天才见效
|
||
convert.reset_probe()
|
||
if group in {"hub", "hub_sync"}:
|
||
hubconfig.reload()
|
||
_log_change(db, user, request, group, changed)
|
||
payload = dbconfig.group_view(group)
|
||
payload["changed"] = sorted(changed)
|
||
payload["effective_immediately"] = True
|
||
return ok(payload)
|
||
|
||
|
||
@router.post("/config/reload")
|
||
def reload_config(
|
||
request: Request,
|
||
user: CurrentUser = Depends(require_permission("system:setting")),
|
||
db: Session = Depends(get_db),
|
||
) -> dict:
|
||
"""丢弃本进程的配置快照,重新读库。
|
||
|
||
单进程部署不需要点它(保存之后本进程立刻生效);用 uvicorn 多 worker 跑的
|
||
时候,其它 worker 收到失效广播就立刻重读,没订阅上广播才最多等
|
||
``OA_CONFIG_CACHE_SECONDS``(2 秒)。
|
||
"""
|
||
dbconfig.reload()
|
||
storage.reset_cache()
|
||
hubconfig.reload()
|
||
# 「装了没有 LibreOffice」也重新找一遍:这一档在多进程部署里就是让每个进程都当场跟上
|
||
convert.reset_probe()
|
||
from .. import models
|
||
|
||
db.add(
|
||
models.OperationLog(
|
||
action="config_reload",
|
||
target="config",
|
||
detail="重新读取数据库里的运行配置",
|
||
person=str(user.person.id),
|
||
person_name=user.display_name,
|
||
identity=user.ref,
|
||
ip=client_ip(request),
|
||
)
|
||
)
|
||
db.commit()
|
||
return ok({"revision": dbconfig.revision(), "cache_seconds": dbconfig.cache_seconds()})
|
||
|
||
|
||
@router.get("/settings")
|
||
def list_settings(
|
||
_: CurrentUser = Depends(require_permission("system:setting")),
|
||
db: Session = Depends(get_db),
|
||
) -> dict:
|
||
"""库里的配置行概况(老接口,键名沿用 ``key`` / ``value``),密钥不回显。"""
|
||
return ok(dbconfig.rows_overview(db))
|
||
|
||
|
||
@router.put("/settings/{key}")
|
||
def update_setting(
|
||
key: str,
|
||
body: ConfigPatch,
|
||
request: Request,
|
||
user: CurrentUser = Depends(require_permission("system:setting")),
|
||
db: Session = Depends(get_db),
|
||
) -> dict:
|
||
"""老写入口 ``PUT /settings/{key}``:``key`` 就是配置组名,效果与
|
||
``PUT /config/{group}`` 一样,存库即生效。"""
|
||
group = key if key in dbconfig.BY_GROUP else {"runtime": "site", "hub": "hub"}.get(key, key)
|
||
if group not in dbconfig.BY_GROUP:
|
||
raise bad_request(f"没有「{key}」这一组配置,可写的是:" + "、".join(dbconfig.GROUP_KEYS))
|
||
try:
|
||
changed = dbconfig.apply(db, group, body.payload())
|
||
except dbconfig.ConfigValidationError as exc:
|
||
raise bad_request(str(exc)) from exc
|
||
storage.reset_cache()
|
||
hubconfig.reload()
|
||
_log_change(db, user, request, group, changed)
|
||
return ok({"key": key, "changed": sorted(changed), "effective_immediately": True})
|