Compare commits

...

30 Commits

Author SHA1 Message Date
狐友 GXXP & LEN b2248a9b64 feat(settings): 存储与备份只读摘要页对齐验收
build / build (push) Successful in 2m12s
- 单一「存储与备份」页:目录、最近成功/失败、归档占用、磁盘剩余四张卡片 + 备份目录条
- 四条容量告警按磁盘可用/配额已用阈值给出 正常/注意/需处理,缺数显示 未知 而非正常
- 批次表默认 20 条 + 加载更多,展示失败原因与单条复制;60 秒自动刷新
- 未接入/未上报/过期/不完整/不可用分状态措辞,不用 0 冒充
- 移除计划编辑、下发、立即备份与库内诊断块(写端点保留)
- compose 接线 LIBRARY_CAPACITY_BUDGET_BYTES 与 BACKUP_HOST_* 只读元数据
2026-11-24 11:53:49 +08:00
zheromiku 660320d646 Merge pull request 'fix(cd): 核验主站首页的 SSO 同源改写' (#29) from fix/cd-serving-proof into main
build / build (push) Successful in 1m46s
2026-11-23 22:00:48 +08:00
姚章浩 0e33f21206 fix(cd): 校验主站单点登录代理处理后的首页
build / build (push) Successful in 1m51s
2026-11-23 21:58:48 +08:00
zheromiku 83bba09cde Merge pull request 'fix(cd): 派发前交接并校验验收归档' (#28) from fix/cd-verified-bundle-handoff into main
build / build (push) Successful in 1m53s
2026-11-23 21:48:05 +08:00
姚章浩 868924d074 fix(cd): 核验容器引擎使用的镜像清单摘要
build / build (push) Successful in 1m53s
2026-11-23 21:46:03 +08:00
姚章浩 03e622e9c7 fix(cd): 派发前交接并核验主站候选归档
build / build (push) Successful in 2m10s
2026-11-23 21:10:50 +08:00
zheromiku 9eef078ed0 Merge pull request 'fix(settings): CYWL-4 知识库绑定与主站基线对齐' (#23) from hifox-agent/len/CYWL-4-fix into main
build / build (push) Successful in 1m56s
Reviewed-on: #23
2026-11-23 14:32:01 +08:00
姚章浩 2ca98a6a35 fix(settings): 将 CYWL-4 对齐主站源码基线
build / build (push) Successful in 1m50s
2026-11-23 14:26:53 +08:00
zheromiku 746b982c43 Merge pull request 'chore(repo): 纳入云治理主站运行基线' (#27) from integrate/cloud-main-baseline into main
build / build (push) Successful in 1m54s
2026-11-23 14:23:57 +08:00
姚章浩 5ff6768027 chore(repo): 同步主干候选发布校验
build / build (push) Successful in 1m46s
2026-11-23 14:20:48 +08:00
zheromiku 2a639392e4 Merge pull request 'fix(cd): 支持已合入主干的现场基线' (#26) from fix/candidate-merged-baseline into main
build / build (push) Successful in 1m29s
2026-11-23 14:19:47 +08:00
姚章浩 9cfe2114b1 fix(cd): 兼容应用与集成测试共用的 QA 凭据文件
build / build (push) Successful in 1m32s
2026-11-23 13:54:07 +08:00
姚章浩 1e7e986b70 chore(repo): 纳入云治理主站运行基线
build / build (push) Successful in 1m47s
2026-11-23 13:50:49 +08:00
姚章浩 8faabdcf9e fix(cd): 支持已合入主干的现场基线
build / build (push) Successful in 1m40s
2026-11-23 13:48:07 +08:00
zheromiku 922ff66533 Merge pull request 'feat(cd): 接入候选构建与批次验收' (#25) from feat/candidate-release-batch into main
build / build (push) Successful in 1m25s
2026-11-23 13:31:41 +08:00
姚章浩 0246db357f fix(cd): 校验候选部署入口并隔离凭据
build / build (push) Successful in 1m30s
2026-11-23 13:28:40 +08:00
姚章浩 1beaa31771 feat(cd): 接入候选构建与批次验收
build / build (push) Successful in 1m30s
2026-11-23 13:20:25 +08:00
zheromiku 8c76c54d8e Merge pull request 'fix(deploy): 兼容 HiFox 确认事件跨秒写入' (#22) from fix/hifox-approval-timestamps into main
build / build (push) Successful in 1m28s
2026-11-23 03:03:32 +08:00
姚章浩 084ee1b176 fix(deploy): 兼容 HiFox 确认事件跨秒写入
build / build (push) Successful in 1m29s
任务更新时间与状态事件分别写入,允许小幅时间偏差。
仍以最近事件验证操作者,并要求验收证据早于两条时间记录。
2026-11-23 03:01:42 +08:00
zheromiku 71971e8164 Merge pull request 'feat(deploy): 接通 HiFox 待发布自动触发' (#21) from feat/hifox-release-trigger into main
build / build (push) Successful in 1m28s
2026-11-23 02:59:40 +08:00
姚章浩 47428a8b58 feat(deploy): 接通 HiFox 待发布自动触发
build / build (push) Successful in 1m27s
将发布人的状态变更与业务验收报告绑定,复用 Gitea 发布及回滚链路。
从部署回执写入运行身份、镜像及主站登录入口,避免重复调度和回写。
2026-11-23 02:57:46 +08:00
zheromiku 91988a0d3b Merge pull request 'feat(deploy): 接通云治理主站的人工确认发布流水线' (#20) from ci-trial-governance-cd into main
build / build (push) Successful in 1m29s
2026-11-23 02:26:47 +08:00
姚章浩 07a0ee2644 fix(deploy): 使用 Gitea 单次人工确认发布
build / build (push) Successful in 1m46s
2026-11-23 02:24:18 +08:00
姚章浩 0b5de6ef7e feat(deploy): 接通云治理主站的人工确认发布流水线
build / build (push) Successful in 2m0s
2026-11-23 01:35:18 +08:00
zheromiku d7d636792d Merge pull request 'feat(qa): 自动准备知识治理测试环境' (#18) from feat/qa-environment-runner into main
build / build (push) Successful in 1m28s
2026-11-22 19:37:29 +08:00
姚章浩 89c484cdc4 feat(qa): 自动准备知识治理测试环境
build / build (push) Successful in 1m29s
为 HiFox QA 检出提供环境检查、锁定依赖、专用 RDS 迁移、服务探活、测试和进程清理。已在 QA 虚拟机通过 make verify,并验证缺少 RDS 配置、错误提交和端口冲突的阻断。
2026-11-22 19:30:49 +08:00
姚章浩 5e3362e2b0 docs(dev): 补充开发与测试环境指南
build / build (push) Successful in 1m29s
从 README 提供依赖、前后端启动、测试命令和非生产 RDS 准备步骤。已在独立 QA 检出通过 make verify,Vite 健康代理和 Chromium 页面冒烟通过。
2026-11-22 19:18:48 +08:00
zheromiku edd07a65d6 Merge pull request 'docs(ops): 更新架构、平台接入及反代运维手册' (#16) from docs/governance-ops-090-main into main
build / build (push) Successful in 1m28s
2026-11-22 13:17:09 +08:00
姚章浩 7c120b3adc test(qawemail): 用绝对域名断言不可解析主机
build / build (push) Successful in 1m57s
构建机 resolv.conf 带 search 域(Tailscale tailf49802.ts.net)时,
smtp.kg-test.invalid 会被拼成 ...tailf49802.ts.net 并由 Fake-IP DNS
解析成功,断言实际测的是构建机搜索域。改成带末尾点的绝对名后与
搜索域无关,仍保持“不可解析主机必须判非法”的原意。
2026-11-22 13:14:52 +08:00
姚章浩 ea159ca2fb docs(ops): 补充治理架构、平台接入与测试反代手册
build / build (push) Failing after 1m37s
2026-11-22 13:10:44 +08:00
38 changed files with 4624 additions and 3088 deletions
+82
View File
@@ -0,0 +1,82 @@
name: deploy-production
on:
workflow_dispatch:
inputs:
action:
description: deploy 或 writeback
required: true
default: deploy
sha:
description: 验收过的完整提交 SHA
required: true
bundle:
description: release.json 的完整 SHA256
required: true
task:
description: 对应的 HiFox 任务 UUID
required: true
confirm:
description: deploy-production 或 retry-writeback
required: true
approval_event:
description: HiFox 自动触发填写的状态事件 UUID
required: false
acceptance_digest:
description: HiFox 自动触发填写的验收记录摘要
required: false
concurrency:
group: cloud-test-governance-main-production
cancel-in-progress: false
permissions:
contents: read
jobs:
guard:
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- name: 核对手动入口及发布输入
run: |
set -eu
test "$GITHUB_EVENT_NAME" = workflow_dispatch
test "$GITHUB_REPOSITORY" = Weknora/knowledge-governance
test "$GITHUB_REF" = refs/heads/main
case "$GITHUB_SERVER_URL" in
https://gitea.zheromiku.top|http://192.168.50.223:3000) ;;
*) exit 1 ;;
esac
git init -q .
git fetch -q --depth 200 "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git" refs/heads/main
git checkout -q --detach "$GITHUB_SHA"
test "$(git rev-parse HEAD)" = "$GITHUB_SHA"
python3 scripts/production_cd.py guard --event "$GITHUB_EVENT_PATH"
publish:
needs: [guard]
runs-on: kg-production-cd
timeout-minutes: 40
steps:
- name: 取同一提交的控制端代码
run: |
set -eu
test "$GITHUB_EVENT_NAME" = workflow_dispatch
test "$GITHUB_REPOSITORY" = Weknora/knowledge-governance
test "$GITHUB_REF" = refs/heads/main
case "$GITHUB_SERVER_URL" in
https://gitea.zheromiku.top|http://192.168.50.223:3000) ;;
*) exit 1 ;;
esac
git init -q .
git fetch -q --depth 200 "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git" refs/heads/main
git checkout -q --detach "$GITHUB_SHA"
test "$(git rev-parse HEAD)" = "$GITHUB_SHA"
- name: 调用云主站受限发布入口并读回回执
env:
KG_CD_SSH_KEY: ${{ secrets.KG_CD_SSH_KEY }}
KG_CD_KNOWN_HOSTS: ${{ secrets.KG_CD_KNOWN_HOSTS }}
KG_CD_SSH_HOST: ${{ vars.KG_CD_SSH_HOST }}
KG_CD_SSH_PORT: ${{ vars.KG_CD_SSH_PORT }}
run: python3 scripts/production_cd.py send --event "$GITHUB_EVENT_PATH"
+80
View File
@@ -0,0 +1,80 @@
name: prepare-candidate
on:
workflow_dispatch:
inputs:
plan:
description: 'Release task UUID, exact SHA, baseline, requirement PRs and additional reviewed commits (JSON)'
required: true
mode:
description: 'verify or prepare'
required: true
default: verify
permissions:
contents: read
concurrency:
group: knowledge-governance-candidate
cancel-in-progress: false
jobs:
guard:
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- name: Verify release scope and CI
env:
KG_CANDIDATE_READ_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
set -eu
test "$GITHUB_EVENT_NAME" = workflow_dispatch
test "$GITHUB_REPOSITORY" = Weknora/knowledge-governance
case "$GITHUB_SERVER_URL" in
https://gitea.zheromiku.top|http://192.168.50.223:3000) ;;
*) exit 1 ;;
esac
case "$GITHUB_REF" in refs/heads/*) ;; *) exit 1 ;; esac
git init -q .
git remote add origin "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git"
auth() { git -c credential.helper='!f() { printf "username=x-access-token\npassword=%s\n" "$KG_CANDIDATE_READ_TOKEN"; }; f' "$@"; }
auth fetch -q origin "$GITHUB_REF" +refs/heads/main:refs/remotes/origin/main
git checkout --detach -q "$GITHUB_SHA"
test "$(git rev-parse HEAD)" = "$GITHUB_SHA"
export KG_CANDIDATE_FORGE="$GITHUB_SERVER_URL"
python3 scripts/candidate_release.py guard --event "$GITHUB_EVENT_PATH" --repo .
prepare:
if: ${{ inputs.mode == 'prepare' && gitea.ref == 'refs/heads/main' }}
needs: [guard]
runs-on: kg-candidate
timeout-minutes: 45
steps:
- name: Build and deploy isolated candidate
env:
KG_CANDIDATE_ACCESS: ${{ secrets.KG_CANDIDATE_ACCESS }}
run: |
set -eu
test "$GITHUB_REPOSITORY" = Weknora/knowledge-governance
test "$GITHUB_EVENT_NAME" = workflow_dispatch
test "$GITHUB_REF" = refs/heads/main
test -n "$KG_CANDIDATE_ACCESS"
python3 - <<'PY'
import json, os, sys
from urllib.error import HTTPError
from urllib.request import ProxyHandler, Request, build_opener
with open(os.environ['GITHUB_EVENT_PATH']) as source:
event = json.load(source)
if event.get('inputs', {}).get('mode') != 'prepare':
sys.exit('candidate workflow mode is not prepare')
data = json.dumps({'run': os.environ['GITHUB_RUN_ID'], 'plan': json.loads(event['inputs']['plan'])}).encode()
request = Request('http://127.0.0.1:38984/prepare', data=data, headers={
'Authorization': 'Bearer ' + os.environ['KG_CANDIDATE_ACCESS'], 'Content-Type': 'application/json'})
opener = build_opener(ProxyHandler({}))
try:
with opener.open(request, timeout=2540) as response:
print(response.read(65536).decode())
except HTTPError as exc:
print(exc.read(4096).decode(), file=sys.stderr)
sys.exit(1)
PY
+8
View File
@@ -27,6 +27,14 @@ BUILD_TIME ?= $(shell date -u +%Y-%m-%dT%H:%M:%SZ)
verify:
$(PY) scripts/ci_checks.py
.PHONY: qa qa-doctor qa-self-test
qa:
$(PY) scripts/qa_env.py run
qa-doctor:
$(PY) scripts/qa_env.py doctor
qa-self-test:
$(PY) -m unittest discover -s scripts -p test_qa_env.py -v
# 清单:哪些是必需项、在哪个档案(local / ci)下必需
list:
$(PY) scripts/ci_checks.py --list
+2 -12
View File
@@ -77,7 +77,7 @@ IT、行政等是待扩展的业务资料范围,不是已经完成的新连接
|---|---|---|
| React/Vite + Web Nginx | 提供静态页面,同源转发 `/api/` 和 `/health` | [前端开发代理](web/vite.config.ts)、[Compose 的 Nginx 配置](deploy/nginx.conf) |
| Go API + 治理 PostgreSQL | 认证、角色、来源、绑定、审核、任务与发布记录。云测试使用独立逻辑库 `knowledge_governance_test` | [API](cmd/api)、[接口契约](api/openapi.yaml) |
| 普通 worker + 测试 WeKnora | worker 取件、上传、轮询并记录验收结果。WeKnora 负责解析、切片和索引 | [worker](cmd/worker)、[来源认证](docs/SOURCE_AUTH_CONFIGURATION.md) |
| 普通 worker + 测试 WeKnora | worker 取件、上传、轮询并记录验收结果。WeKnora 负责解析、切片和索引 | [worker](cmd/worker)、[来源接入](docs/OPERATIONS_RUNBOOK.md#接入外部平台)、[来源认证](docs/SOURCE_AUTH_CONFIGURATION.md) |
| 发布 worker + 生产 WeKnora | 按已锁定的批次和目标执行受控发布与读回。问答端通过下游服务使用已发布知识 | [发布 worker](cmd/release-worker)、[操作手册](docs/OPERATIONS_RUNBOOK.md) |
从自己的电脑做系统设置验收,使用 SSH 转发后的 `http://127.0.0.1:28189/`。云测试主控制台使用受限内网入口 `http://100.85.111.121:8088/`。仓内 Compose 则将宿主 `8088` 映射到 Web 容器 `8080`。选择入口时先确认要看的部署。隧道命令、生产 `090` 服务地址和 HTTPS 反代示例见[运维手册](docs/OPERATIONS_RUNBOOK.md#入口与反向代理)。
@@ -109,17 +109,7 @@ IT、行政等是待扩展的业务资料范围,不是已经完成的新连接
## 开发与 CI
开发环境使用 Go 1.26、Node.js 22、npm 和 Python 3。前端可独立开发。先准备一个获准用于开发的测试治理 API,在开发机的 `localhost:8088` 上确认 `/health` 可达。Vite 按仓内配置将 `/api` 和 `/health` 转给该地址,浏览器中的操作会作用于所连的环境。
```bash
# 仓库根目录,检查测试后端及前端依赖,再启动开发页面
curl -fsS --max-time 5 http://localhost:8088/health
cd web
npm ci
npm run dev -- --host 127.0.0.1
```
打开 Vite 打印的地址。修改组件后运行 `npm test` 和 `npm run build`。后端改动在仓库根目录用 `go test ./internal/backupinventory` 这类按包测试缩小范围,再运行下方完整门禁。涉及持久化的联调使用独立测试 RDS 逻辑库,启动 API 或 worker 前核实库名和迁移版本。真实页面的通过条件见[运维手册](docs/OPERATIONS_RUNBOOK.md#开发测试和现场验收)。
本机和 QA 虚拟机的依赖安装、前后端启动、测试命令及 PostgreSQL 测试库准备见 [开发与测试指南](docs/DEVELOPMENT_AND_TESTING.md)。页面验收标准见[运维手册](docs/OPERATIONS_RUNBOOK.md#开发测试和现场验收)。
```bash
make verify # 完整检查入口:本地与 CI 使用同一套规则
+8
View File
@@ -52,6 +52,14 @@ services:
# 「整库版本」页:只读已封存的整库候选产物。归档根由 `libraryctl capture`
# 在主机上写入(私有 0700),这里只挂只读;留空 = 未接线(页面降级展示原因)。
LIBRARY_ARCHIVE_ROOT: "${LIBRARY_ARCHIVE_ROOT:-/var/lib/knowledge-governance/library}"
# 「存储与备份」摘要页的归档配额(字节)。留空 = 未设置,页面显示"配额未设置";
# 显式写 0 会被 appconfig 拒绝(必须为正整数),所以只能用空串表示未设置。
LIBRARY_CAPACITY_BUDGET_BYTES: "${LIBRARY_CAPACITY_BUDGET_BYTES:-}"
# 宿主每 5 分钟上报的整库备份元数据快照(collector 写入,平台只读)。
# 留空 = 未接线,页面按验收显示"主机未上报";路径必须是宿主机侧绝对路径。
BACKUP_HOST_METADATA_PATH: "${BACKUP_HOST_METADATA_PATH:-}"
BACKUP_HOST_METADATA_MAX_AGE: "${BACKUP_HOST_METADATA_MAX_AGE:-15m}"
BACKUP_HOST_READONLY_HOST_PATH: "${BACKUP_HOST_READONLY_HOST_PATH:-}"
# 主机侧封存 agent 的 unix socket:api 只用它判断"能不能从页面发起",
# worker 用它投递作业。容器里没有 Docker socket,也没有来源凭据。
LIBRARY_AGENT_SOCKET: "${LIBRARY_AGENT_SOCKET:-/run/library-agent/agent.sock}"
+44
View File
@@ -0,0 +1,44 @@
# 知识治理候选和批次验收
「知识治理版本与发布 Agent」管理一条 HiFox 发布任务。开发和合并按正常 PR 流程处理。三生三测仍由业务任务进入「测试中」触发,现有白小浅和三生三测规则无需改动。正式发布由发布负责人确认,沿用 [主站 CD](PRODUCTION_CD_RUNBOOK.md)。
## 发起候选
1. 发布负责人在发布任务的评论中填写下列 `kg-release-v1` 代码块。`base` 填主站实际运行的完整提交 SHA,`sha` 填选定的 `main` 完整提交 SHA。每条 `items` 关联一个已合入 `main` 的 PR 和一个 HiFox 业务任务 UUID。PR 的标题、正文或来源分支应包含该任务编号。`extra` 列出这段主干历史中经负责人确认一同发布的其他主干提交,通常为空。
````markdown
```kg-release-v1
{"task":"<发布任务 UUID>","base":"<当前主站 SHA>","sha":"<候选 SHA>","items":[{"task":"<业务任务 UUID>","pr":123}],"extra":[]}
```
````
2. Agent 执行 `candidate_coordinator.py prepare <发布任务 UUID>`。Gitea 核对候选 SHA 的 CI、每个 PR 的落地提交和完整主干范围。需准备候选时,独立 Runner 通过回环入口调度本机执行器。执行器复查发布负责人评论、Gitea 作业证明和当前主站 SHA 后,从准确提交构建镜像并封存。
3. 执行器在独立验收数据库上启动同份归档,核验 API 提交、三个运行镜像、迁移账本、Web 入口及归档摘要。在发布任务和业务任务回填候选版本与地址。对「待测试」业务任务,由执行器转「测试中」。本地候选地址绑定回环,验收 Agent 应和执行器同机,或使用经工程侧验证的私有转发。
4. `candidate_coordinator.py status <发布任务 UUID>` 读取候选回执或对应 Gitea 运行链接。遇到调度结果不明,先从 Gitea 读回运行再决定恢复路径。
## 登记验收
业务验收报告分别放在原业务任务,批次共享功能回归报告放在发布任务。保持测试角色原有输出,使用获授权的验收人或测试 Agent 在对应任务评论追加以下结构化结论。报告应保留用例明细和原始证据链接。该段的 `required` 是本轮登记的必测用例数。
````markdown
```kg-qa-v1
{"sha":"<完整提交 SHA>","bundle":"<归档清单 SHA256>","url":"<候选地址>","verdict":"passed","required":3,"passed":3,"failed":0,"blocked":0}
```
````
执行 `candidate_coordinator.py register <发布任务 UUID>`。脚本复验运行身份,逐项核对报告作者、候选版本和归档、时序与必测结果。全项通过后在发布任务登记附原始报告链接的汇总,再写入并读回 `cd_acceptance`。验收候选只接受专用 RDS 模式。
HiFox 触发器按[主站 CD 手册](PRODUCTION_CD_RUNBOOK.md)在派发前交接并校验验收归档。交接失败时可修复后重试同一事件,已派发事件仍回放原记录。发布负责人完成确认后,将发布任务转入「待发布」。已有自动化使用该 UUID 和归档部署并回写。部署后回写失败时使用现有回执重试回写。
## 执行器配置
- 版本管理机使用 Python 3.11 及以上、Docker Compose、HiFox CLI 和已有 Gitea 凭据。候选执行器通过 `candidate_worker.py <仓库工作树> <访问文件>` 绑定 `127.0.0.1:38984`,仓库工作树允许读取 `origin/main`。执行器通过现有 Gitea 凭据读取作业与日志。运行账户需能以 `weknora-test` 执行只读版本检查。
- 为候选执行器单独配置 `kg-candidate` Runner。作业使用同机回环网络,通过仓库 Secrets 的 `KG_CANDIDATE_ACCESS` 访问执行器。访问文件由执行器用户持有,内容为独立 64 位十六进制随机凭据。候选作业使用的容器须无宿主 Docker socket 和生产密钥挂载。
- 业务验收使用 `~/.config/knowledge-governance/{qa.json,qa.pgpass,rds-ca.pem}`。复用 `qa_env.py` 的专用 `kg_qa_` RDS 库和角色校验。`qa.pgpass` 可包含同一端点的应用库和集成测试库条目,候选只读取 `qa.json` 指定的库和角色。验收使用专用账号与测试数据。需要验证外部系统的用例须先准备各自的隔离资源。
- 候选执行器采用单验收槽。新批次启动前由运维确认前一批验收结束,按上一批 `ready.json` 中的容器身份停止其 Compose 项目,归档原有配置和回执后释放槽位。保留已验收的归档及审批记录。
## 演练和当前环境
`prepare-candidate.yml` 的 `verify` 模式校验 Gitea 范围与 CI。可在评审分支验证。`prepare` 模式只接受 `main` 的调度。`candidate_release.py build` 和 `candidate_runtime.py <bundle>` 可在隔离开发机演练打包及冒烟。后者使用临时 Docker 数据库,退出后停止演练容器。
候选提交必须位于 `main` 的第一父链,并包含主站实际运行的提交。若现场版本从独立分支发布,先通过保留提交历史的合并将现场基线纳入 `main`。现场提交本身可以位于第二父链。候选计划须覆盖 `git rev-list --first-parent <现场 SHA>..<候选 SHA>` 的每一项,包括基线合并提交和已确认随批发布的工程提交。主站数据库仅用于正式应用,业务候选使用专用 QA 库。
+131
View File
@@ -0,0 +1,131 @@
# 知识治理平台开发与测试
以下命令从仓库根目录运行。日常开发可在 Ubuntu 宿主进行,指定提交的回归在 `hifox-qa` 的独立检出中运行。部署到阿里云测试服后的验收按 [操作 Runbook](OPERATIONS_RUNBOOK.md) 和 [用户流程验收](USER_FLOWS_ACCEPTANCE.md) 执行。
## QA 虚拟机一键回归
在 `hifox-qa` 检出提测提交后,运行下列入口。将 SHA 占位值换成提测记录里的完整提交 SHA。
```bash
make qa-doctor
KG_QA_SHA='<完整提交 SHA>' make qa
```
`make qa-doctor` 检查工具链、HiFox 机器在线状态、OMP 模型调用、测试库身份和已安装的迁移。`make qa` 安装锁定依赖,在专用测试库上通过 API 初始化和迁移,随后核对完整迁移序列、API 就绪状态、Web 首页及 Vite 健康代理。通过后执行 Go 和 Vitest 测试,结束时关闭本次启动的服务。每次运行的服务日志保存在 `~/.local/state/knowledge-governance/qa/`。需要提交前完整门禁时执行 `make verify`。
初次配置由负责人在 QA 虚拟机准备 `~/.config/knowledge-governance/`。以下示例使用虚构的 RDS 主机名。
| 文件 | 内容 |
| --- | --- |
| `qa.json` | 当前用户所有、权限 `0600`,字段 `host`、`port`、`database`、`user` |
| `qa.pgpass` | 当前用户所有、权限 `0600`,填写与 `qa.json` 匹配的口令条目 |
| `rds-ca.pem` | 对应实例的 CA 证书,用于校验 RDS 主机名 |
```json
{"host":"rds.example.test","port":5432,"database":"kg_qa_app","user":"kg_qa_app"}
```
专用非生产 RDS 库和角色以 `kg_qa_` 开头,权限和网络准备见第 2 节。首次运行接受空库,后续运行接受与当前提交兼容的迁移序列。缺库、认证失败、迁移不兼容和端口冲突均会使命令非零退出。浏览器业务 E2E 和专用集成库的 Go 测试按第 4 节执行。
## 1. 检出代码与安装依赖
准备 Git、Make、Python 3、Go 1.26(含同一工具链的 `gofmt`)、Node.js 22 和 npm。数据库检查另需 PostgreSQL 客户端 `psql`。首次安装依赖需要能访问 Go 和 npm 的依赖源。
```bash
# QA 在独立克隆中拉取提测分支,使用提测记录里的完整提交 SHA
export KG_TARGET_BRANCH='<提测分支名>' KG_TARGET_SHA='<完整提交 SHA>'
git fetch origin "$KG_TARGET_BRANCH" && git switch --detach "$KG_TARGET_SHA" &&
test "$(git rev-parse HEAD)" = "$KG_TARGET_SHA" && test -z "$(git status --porcelain)"
# 上面的命令链若失败,先解决检出或工作区问题再继续
# 检查当前 shell 的工具链,非交互任务也应设置相同的 PATH
export PATH="$(go env GOROOT)/bin:$PATH"
go version
command -v gofmt
node --version
npm --version
python3 --version
make deps-install
```
`make deps-install` 通过 `go mod download` 和 `npm ci` 安装依赖。Go 依赖由 `go.mod` / `go.sum` 约束,前端由 `web/package-lock.json` 锁定。依赖安装失败时先检查工具链、依赖源和锁文件,避免临时改写清单来绕过问题。
## 2. 准备开发和测试数据库
无库检查可直接跳到第 4 节。启动 API 或执行真库测试前,由数据库管理员在**非生产 PostgreSQL RDS** 上预建专用空库和登录角色。建议分配 `kg_qa_app` 给应用冒烟,`kg_qa_it` 给 Go 集成测试,各用独立角色。开发宿主另用开发专用库,避免与 QA 共享数据。库未分配时先申请,启动流程以库已存在为前提。
| 用途 | 所需权限 | 数据初始化 |
| --- | --- | --- |
| 应用启动与 UI 冒烟 | `CONNECT`,以及目标 schema 内的 `USAGE`、`CREATE` 和对应用对象的读写权限。迁移角色须能修改自己创建的对象。 | 首次 API 启动执行仓库内嵌迁移。用户表为空时创建初始管理员,首次登录必须修改密码。初始口令通过测试环境负责人交接。 |
| Go PostgreSQL 集成测试 | `CONNECT` 和目标测试库的 `CREATE` 权限,用于建立各用例自己的 schema。 | 用例创建隔离 schema、执行迁移、写入测试数据并清理。相同测试不要并发指向同一个库,避免固定 schema 名冲突。 |
两类角色均只授予对应非生产库所需的权限。使用空库和合成数据。密码由操作者在目标机配置到权限为 `0600` 的 PostgreSQL passfile,条目按 `host:port:database:user:password` 填写。使用 RDS CA 校验证书。以下命令先读回实际数据库、角色与 TLS 状态,核对三者再启动 API 或运行真库测试。
```bash
# 用获准的 RDS 主机名、端口、库名、角色和文件路径替换示例值
export PGHOST='<非生产 RDS 主机名>' PGPORT=5432
export PGDATABASE=kg_qa_app PGUSER=kg_qa_app
export PGPASSFILE="$HOME/.config/knowledge-governance/qa.pgpass"
export PGSSLROOTCERT="$HOME/.config/knowledge-governance/rds-ca.pem"
export PGSSLMODE=verify-full PGCONNECT_TIMEOUT=5
psql -X -v ON_ERROR_STOP=1 -c \
'SELECT current_database(), current_user, ssl FROM pg_stat_ssl WHERE pid = pg_backend_pid();'
```
如果是云厂商提供的私网地址,先确认执行机通过获准的网络路径可访问 RDS。库名、角色、TLS、连接权限或迁移权限有问题时,先交由环境负责人核对配置。实例上已有数据的库不能当作空库初始化。
## 3. 启动后端和前端
**终端 A,启动 API。** 在干净 shell 中执行第 2 节的应用库配置和连通性检查。使用独立测试配置,不加载现网 `.env`。
```bash
export DATABASE_URL="postgresql://${PGUSER}@${PGHOST}:${PGPORT}/${PGDATABASE}?sslmode=verify-full&connect_timeout=5"
export APP_ADDR=127.0.0.1:8088
export TEST_WEKNORA_ENABLED=false PP_SCAN_ENABLED=false
export RELEASE_WORKER_ENABLED=false PRODUCTION_RELEASE_REQUESTS_ENABLED=false
export DOBOTAI_OPS_READ_ENABLED=false DOBOTAI_OPS_DIRECTORY_SYNC_ENABLED=false
go run ./cmd/api
```
API 会在监听前连接 PostgreSQL、应用迁移并初始化管理员。Web 页面和同步 API 联调只需运行 API 与 Vite。需要验证后台队列时,另用相同的隔离应用库配置启动普通 worker(`go run ./cmd/worker`)。涉及取件或来源刷新的任务还依赖容器内 `/app/scripts` 及获准的来源接线,按部署说明准备。发布 worker 无需启动。
Vite 通过 `localhost:8088` 转发 `/api` 和健康检查。如果 `8088` 已被其他部署占用,使用端口空闲的 QA 虚拟机运行本节。仅改前端时,可复用一个获准联调的测试 API,但需要先确认 `localhost:8088/health` 可达,并核对该地址指向的环境。
**终端 B,启动 Web。**
```bash
npm --prefix web run dev -- --host 127.0.0.1 --port 5173 --strictPort
```
在运行服务的机器打开 `http://127.0.0.1:5173/`。另开终端检查 API 与前端代理,再复查迁移记录。最后一条命令需要第 2 节的应用库配置。
```bash
curl --fail --silent --show-error http://127.0.0.1:8088/health
curl --fail --silent --show-error http://127.0.0.1:5173/health
psql -X -v ON_ERROR_STOP=1 -c \
'SELECT version FROM schema_migrations ORDER BY version DESC LIMIT 1;'
```
空库首次启动后,用专用测试账号登录,按当次验收标准验证页面及接口。联调结束在两个终端按 `Ctrl+C` 停服务,数据库由环境管理员按测试数据保留规则管理。
## 4. 选择测试命令
| 目的 | 命令 |
| --- | --- |
| 查看检查及适用范围 | `make list` |
| 后端包测试 | `make tests-go` |
| 单个 Go 包及相关子包 | `go test -count=1 ./internal/httpapi/...` |
| 前端 Vitest 套件 | `make tests-web` |
| 单个前端测试文件 | `npm --prefix web test -- src/App.test.tsx` |
| 完整提交前检查,与 CI 共用入口 | `make verify` |
`make verify` 包含安装、格式、静态检查、构建、测试、版本和安全检查,并写出 `ci-report.json`。在未导入真库测试配置的 shell 中运行。若检出时用了 `--no-tags`,先执行 `git fetch --tags origin`,以便版本检查读取正式标签对应的提交。依赖安装与安全检查需要相应网络或缓存。允许跳过的外部依赖用例见 [test-scope.json](../scripts/test-scope.json),真库测试应单独执行并记录结果。
在应用冒烟之外验证真实 PostgreSQL 行为时,重新按第 2 节切换并核对 **集成测试库和角色**,然后执行目标用例。下面以 UI 设置版本切换用例为例。
```bash
TEST_DATABASE_URL="postgresql://${PGUSER}@${PGHOST}:${PGPORT}/${PGDATABASE}?sslmode=verify-full&connect_timeout=5" \
go test -count=1 -v ./internal/platform/postgres -run '^TestUISettingsActivationRetiresPreviousRevisionIntegration$'
```
检查输出出现目标用例的 `PASS`。用例被跳过或没有匹配时,应补齐配置或纠正用例名后重跑。前端 Vitest 负责组件与业务逻辑检查,浏览器 E2E 应单独执行并按 Feature 保存证据。提测记录至少包括完整提交 SHA、执行命令、退出码,以及失败用例的日志或浏览器截图。
+4
View File
@@ -5,6 +5,8 @@
管理员配置连接和发布授权,文档工程师维护资料,只读成员查看进度。先确定要操作的环境,再按下面的接线与验收步骤进入业务流程。
云测试治理主站自身的应用升级见[主站应用 CD](PRODUCTION_CD_RUNBOOK.md)。
## 入口与反向代理
| 请求从哪里发出 | 地址或路径 | 实际目的地 |
@@ -47,6 +49,8 @@ docker inspect -f '{{.Name}} {{index .Config.Labels "release"}}' kg-test-storage
本次已核实共享测试治理库到 `000082`。对内、对外独立启用的实现依赖 `000083`,待独立库联调或共享库迁移获准后,再验证单侧暂停、保存和刷新。生产 `070` 不在该套验收范围。
下文系统设置中的绑定、盘点和模型连接步骤适用于上表的测试候选版本。根据现场标签选择对应版本的代码和交付物。
## 接入外部平台
| 平台与用途 | 管理员或运维怎样接 | 接通的证据 |
+53
View File
@@ -0,0 +1,53 @@
# 云测试治理主站应用 CD
正式入口为 `http://100.85.111.121:8088/`。云端 Compose 项目为 `knowledge-governance-cloud-test`,工作目录 `/opt/knowledge-governance`,当前配置链为 `compose.json`,服务为 `api`、`web`、`worker`。Web 容器提供 `8088`,通过挂载的 nginx 配置代理 API 的 `127.0.0.1:18098`。应用 CD 与知识库内容发布各自保留原有授权流程。
## 建立验收产物
1. 从干净检出的完整提交构建一次 API、worker、web 镜像。构建调用方对三个镜像都注入 `org.opencontainers.image.revision=<完整 SHA>`。API 构建身份沿用 `scripts/version.py --identity` 输出,传给 Dockerfile 的版本、提交和构建时间参数。API 与 worker 各自记录镜像 ID,即使它们来自同一个 Dockerfile。
2. 封存后用同一份归档部署到隔离验收环境。输出目录必须是新路径,父目录应已存在。三个 `--api/--web/--worker` 参数是本地镜像的完整 ID。
```bash
python3 scripts/production_cd.py pack --sha "$SHA" --task "$TASK_UUID" \
--api "$API_ID" --web "$WEB_ID" --worker "$WORKER_ID" --output "$BUNDLE_DIR"
docker load -i "$BUNDLE_DIR/api.tar"
docker load -i "$BUNDLE_DIR/web.tar"
docker load -i "$BUNDLE_DIR/worker.tar"
```
3. 用验收环境自身的 Compose 和数据库启动这些镜像。用下面的命令读回验收环境运行身份。此处三个服务参数是实际的**测试容器名**。在业务验收入口执行实际用例并将输出、结果与报告链接放在同一份验收记录里。
```bash
python3 scripts/production_cd.py attest --sha "$SHA" --task "$TASK_UUID" \
--api "$QA_API" --web "$QA_WEB" --worker "$QA_WORKER" --test-url "$QA_URL" --directory "$BUNDLE_DIR"
BUNDLE_SHA=$(sha256sum "$BUNDLE_DIR/release.json" | cut -d' ' -f1)
```
4. 由验收人使用获授权的 HiFox CLI 登记业务结论,读回任务、验收字段和状态。`cd_acceptance` 是 JSON 字符串类型的 metadata,其解析结果为 `{"verdict":"passed","sha":"…","bundle":"…","evidence":"https://…"}`。录入人应先核对真实报告与运行身份。自动发布时,`evidence` 使用同一 HiFox 任务的验收报告评论链接(带 `#comment-<UUID>`)。评论须正文包含完整提交和归档清单摘要,并在发布人确认前完成。用 `task view --output json` 核对实际任务 UUID、空间、状态和验收字段。验收登记重试复用原归档摘要与原记录。以当前版本只接受一个任务,多个任务分别验收。
5. HiFox 触发器在派发 Gitea 前自动通过执行机的 `weknora-test` SSH 通道交接四个文件,并用主站控制器校验。人工 Actions 入口仍须由运维提前将四个文件放入云主站的 `/opt/knowledge-governance/cd/bundles/<release.json SHA256>/`。通过安全文件通道传到临时目录,核对摘要与内容后用同一文件系统上的目录重命名发布;已有目录先核对内容,匹配时复用。此目录仅供目标控制器读取,文件由该账号持有且组与其他用户无写权限。
## 在 HiFox 确认发布
验收、登记、上传归档都完成后,由发布人把原任务移入「待发布」。HiFox 的「知识治理|待发布自动执行 CD」把任务 UUID 交给专用发布 Agent,Agent 调用白名单内的 `scripts/hifox_release_trigger.py`。桥接脚本读取 HiFox 时间线,校验最近一次状态变更的操作者、状态、同任务验收报告及产物摘要,随后调度 Gitea `deploy-production@main`。Gitea 仍只开放 `workflow_dispatch`。目标控制器按完整输入校验 Gitea 运行,并在切换前复查 HiFox 状态和验收摘要。
相同状态事件复用已记录的 Gitea 运行。如果调度结果未知,核查对应 Gitea 运行与本机调度记录后再处理。旧任务已处于「待发布」时,在验收登记完成后重新进入该状态可发起新确认。
也可由发布人使用 Gitea Actions 中原有人工入口应急。分支选 `main`,使用 `action=deploy`、完整 `sha`、`bundle`、任务 UUID `task` 和 `confirm=deploy-production`,仅 HiFox Agent 填写 `approval_event` 和 `acceptance_digest`。
主站侧从 Gitea 读取运行、操作者和通过的校验作业,并验证输入摘要及工作流代码。候选代码可来自仓库内的任务分支,以实际验收 SHA 为准。切换前还核验必需 CI 状态、HiFox 验收记录、三份归档、线上源代码血缘及数据库迁移账本。切换复用 `scripts/deploy-api-web.sh`,仅更换三项 Compose `image`;保留原配置字节以备回滚。切换后自动读回三镜像、API 二进制 SHA、主站健康、API readiness 及实际提供的前端资源。HiFox 回写包含原始运行 URL、完整提交、摘要、镜像 ID 及核验证据。任务评论另含主站登录地址和已核验的运行版本,带 OCI 版本标签时显示其值,其余镜像显示完整提交。
目标机已有的 `schema_migrations` 必须与候选完全相同,API 与 worker 的库连接均须核对。应用会在启动时检查迁移。新增或改变的迁移先按独立流程审查、备份、执行并复验;CD 自身只读迁移账本。发布时运营方应保留 prior tag,保障用原 Compose 字节回滚。
## 失败恢复
- `rolled_back` 表示自动恢复了原 Compose、旧的镜像 ID、API SHA 与站点健康。`rollback_failed` 或 `cutover_started` 要求巡检现场、按回执恢复并复验。目标机互斥锁覆盖切换及回写。Gitea 的取消记录只能说明流水线结束,回滚以目标机回执和运行时读回为准。
- `DEPLOYED_HIFOX_PENDING` 表示镜像切换和核验已经完成。以同一 `sha`、`bundle`、`task` 人工发起 `action=writeback`、`confirm=retry-writeback`。脚本先读原目标回执并复验仍在运行的版本,随后补写 HiFox,保留原部署链接。状态与 metadata 的当前值以 HiFox 读回为准。重复调用核对记录后结束。
- 目标回执 `/opt/knowledge-governance/cd/receipts/<bundle>.json`,镜像切换前的 Compose 保存为同名 `.compose.backup`。SSH 超时或强制中断后,先读回执和当前运行态。已存在未决或失败回执时,重复部署被拒。保留原回执作为事故证据。
## 一次性配置与权限
- 目标机安装仓库 `scripts/{production_cd.py,cd_migration_probe.py,deploy-api-web.sh,production-cd-ssh.sh}` 到 `/opt/knowledge-governance/cd/bin/`。创建私有 `receipts/`、`bundles/`、`hifox-home/`,初始化 `source.git` 为 bare Git 仓,并将 `.gitea/required-contexts.txt` 安装到该目录。仅发布运维可更新这些文件。
- 填写目标机 `/opt/knowledge-governance/cd/deploy-production.yml`,内容与 Gitea 主分支的工作流逐字节相同。控制器用 Gitea 发布人账号 ID 和只读日志验证确认。目标端 `authorized_keys` 为 CI 单独公钥设置 `restrict,command="/opt/knowledge-governance/cd/bin/production-cd-ssh.sh"`。校验云主机 SSH host key 后将其按 `kg-governance-cd` 别名写入 `KG_CD_KNOWN_HOSTS`。对应独立 SSH 私钥保存在 `KG_CD_SSH_KEY`。Runner 标签为 `kg-production-cd`,使用 `KG_CD_SSH_HOST` 和 `KG_CD_SSH_PORT` 接入批准的 Tailscale 或本机 IPv6 隧道。
- 将受控 HiFox CLI 安装至 `bin/hifox`,由账号持有人在目标主机使用 `hifox-home` 对应的私有配置目录完成登录。身份须能读取指定空间的任务、写 `cd_release` metadata 并完成对应状态迁移。状态绑定前分别读回组织状态和实际任务类型,复用原有待发布、已发布 ID,保留其余工作流配置。
- 在专用发布 Agent 的 Ubuntu 开发机安装 `scripts/{production_cd.py,hifox_release_trigger.py,cd_bundle_handoff.py}` 到 `~/.local/lib/kg-hifox-release/`。该机使用受控 HiFox 登录和已配置的 Gitea Git 凭据助手,凭据不传入自动化指令。使用私有目录 `~/.local/state/kg-hifox-release/` 存放 `active-since`(UTC,`YYYY-MM-DDTHH:MM:SSZ`)及调度记录。首次接通时,将 `active-since` 设为通道启用时刻,历史状态事件不追发。发布期间需要 Agent 执行机和 HiFox Daemon 在线。
- 常规 push CI 负责验证和静态预览。这个 workflow 的唯一事件是 `workflow_dispatch`。`make verify` 的 `contracts` 子项运行 CD 用例。真实切换的验收要求对应候选、现场前置条件和发布人确认。
+1 -1
View File
@@ -3,7 +3,7 @@
> 这份文档是**破坏性变化与数据迁移步骤的落脚点**:`CHANGELOG.md` 里以 `**破坏性**` 开头的条目
> **必须**链接到本文(或本文的某个小节)。发布记录本身仍在 `CHANGELOG.md` —— 本文不维护第二份变更列表。
>
> 本仓 CI **只做 CI**:不打 tag、不发 Release、不部署。发布与部署都是**独立的人工审批动作**。
> 常规 CI 负责检查、构建与静态预览。版本 tag 与 Release 由人批准后执行。主站应用部署使用独立的[人工确认 CD](PRODUCTION_CD_RUNBOOK.md)。
## 一、正式发布(由人批准后执行)
+180
View File
@@ -0,0 +1,180 @@
#!/usr/bin/env python3
"""Coordinate candidate preparation and record independently authored QA evidence."""
import argparse
import json
from pathlib import Path
import re
import sys
from urllib.error import HTTPError
import candidate_release as candidate
import candidate_runtime as runtime
import hifox_release_trigger as hfx
import production_cd as cd
STATE = Path.home() / '.local/state/kg-candidate-release'
CLI = str(Path.home() / '.local/bin/hifox')
WORKFLOW = candidate.API + '/actions/workflows/prepare-candidate.yml/dispatches?return_run_details=true'
QA_AUTHORS = {cd.RELEASE_OWNER, '62a66d1e-4311-4b54-8004-bbb03c69c08c', 'bdf4f412-8c3f-45ab-84f4-638c60a43806'}
WAIT_TEST = 'b59c34ee-94f4-41a8-8577-dea73b2c6414'
TESTING = 'f8906482-bad7-4af8-9a3b-d52630eff3f7'
QA_FENCE = re.compile(r'^```kg-qa-v1\s*\n(\{.*?\})\s*\n```\s*$', re.MULTILINE | re.DOTALL)
def task(task_id):
cd.require(cd.matches(cd.UUID, task_id), 'provide the task UUID')
obj = hfx.hifox(CLI, 'task', 'view', task_id)
if not isinstance(obj, dict) or obj.get('id') != task_id or obj.get('spaceId') != cd.SPACE:
raise cd.CDError('task is outside the release space')
return obj
def timeline(task_id):
rows = hfx.hifox(CLI, 'api', 'get', f'/rest/v1/tasks/{task_id}/timeline')
cd.require(isinstance(rows, list), 'task timeline unavailable')
return [row for row in rows if row.get('event') == 'commented']
def owner_plan(task_id):
task(task_id)
matches = [candidate.FENCE.search(row.get('content') or '') for row in reversed(sorted(
timeline(task_id), key=lambda row: row.get('createdAt', ''))) if (row.get('actor') or {}).get('id') == cd.RELEASE_OWNER]
match = next((row for row in matches if row), None)
if match is None:
raise cd.CDError('release owner must post a kg-release-v1 plan on the release task')
plan = json.loads(match[1])
candidate.check_plan(plan)
cd.require(plan['task'] == task_id, 'release plan belongs to another task')
for item in plan['items']:
requirement = task(item['task'])
identifier = requirement.get('identifier')
pr = candidate.read_forge(candidate.API + f'/pulls/{item["pr"]}')
fields = ' '.join(str(v or '') for v in (pr.get('title'), pr.get('body'), (pr.get('head') or {}).get('ref')))
cd.require(isinstance(identifier, str) and re.search(rf'(?<![\w-]){re.escape(identifier)}(?!\w)', fields, re.IGNORECASE),
f"PR #{item['pr']} does not identify its HiFox requirement")
return plan
def queue(task_id):
plan = owner_plan(task_id)
STATE.mkdir(mode=0o700, parents=True, exist_ok=True)
key = cd.acceptance_digest(plan)
path = STATE / (key + '.dispatch.json')
with cd.deploy_lock(STATE / 'dispatch.lock'):
if path.exists():
result = cd.read_json(cd.immutable_file(path))
cd.require(result['state'] == 'queued', 'candidate dispatch outcome unknown; reconcile Gitea before retry')
return result
conf = Path.home() / '.config/knowledge-governance/qa.json'
runtime.qa_database(conf)
cd.record(path, {'state': 'submitting', 'plan': plan})
result = hfx.forge('POST', WORKFLOW, {'ref': 'main', 'inputs': {'plan': json.dumps(plan), 'mode': 'prepare'}})
run = str(result.get('workflow_run_id', ''))
cd.require(cd.matches(hfx.RUN_ID, run), 'missing candidate run ID; reconcile Gitea before retry')
receipt = {'state': 'queued', 'plan': plan, 'run': run, 'url': f'{cd.FORGE}/{cd.REPO}/actions/runs/{run}'}
cd.record(path, receipt)
return receipt
def add_comment(task_id, key, body):
marker = f'[KG candidate {key}]'
def existing():
return [row for row in timeline(task_id) if marker in (row.get('content') or '')]
if not existing():
hfx.hifox(CLI, 'task', 'comment', task_id, '--body', f'{marker}\n\n{body}')
rows = existing()
cd.require(len(rows) == 1 and cd.matches(cd.UUID, rows[0].get('id')) and body in rows[0].get('content', ''),
'candidate comment not uniquely verified')
return rows[0]['id']
def publish_candidate(plan, receipt, run):
body = (f'候选验收地址 {receipt["url"]}\n\n提交 `{receipt["sha"]}`\n\n'
f'归档 `{receipt["bundle"]}`\n\n'
f'构建记录 {cd.FORGE}/{cd.REPO}/actions/runs/{run}\n\n'
f'发布任务 {task(plan["task"])["url"]}')
key = 'ready ' + receipt['bundle']
add_comment(plan['task'], key, body)
for item in plan['items']:
item_id = item['task']
status = (task(item_id).get('status') or {}).get('id')
if status == TESTING:
cd.require(any(f'[KG candidate {key}]' in (row.get('content') or '') for row in timeline(item_id)),
f'{item_id}: another QA round is already in progress')
continue
cd.require(status == WAIT_TEST, f'{item_id}: requirement must be in 待测试')
add_comment(item_id, key, body)
cd.require((task(item_id).get('status') or {}).get('id') == WAIT_TEST,
f'{item_id}: task status changed during candidate handoff')
hfx.hifox(CLI, 'task', 'edit', item_id, '--status', TESTING)
cd.require((task(item_id).get('status') or {}).get('id') == TESTING, f'{item_id}: testing status not verified')
def register(task_id):
plan = owner_plan(task_id)
directory = STATE / cd.acceptance_digest(plan)
with cd.deploy_lock(directory / 'registration.lock'):
receipt = cd.read_json(cd.immutable_file(directory / 'ready.json'))
cd.require(receipt.get('mode') == 'acceptance', 'isolated smoke results are ineligible for publication')
runtime.attest(directory / 'bundle', receipt)
reports = {}
tasks = [item['task'] for item in plan['items']] + [task_id]
for item_id in tasks:
obj = task(item_id)
rows = sorted(timeline(item_id), key=lambda row: row.get('createdAt', ''), reverse=True)
for row in rows:
match = QA_FENCE.search(row.get('content') or '')
if not match or (row.get('actor') or {}).get('id') not in QA_AUTHORS:
continue
result = json.loads(match[1])
if result.get('bundle') == receipt['bundle']:
reports[item_id] = (row, result)
break
if item_id in reports:
row = reports[item_id][0]
cd.require(cd.matches(cd.UUID, row.get('id')) and obj.get('url', '').startswith('https://app.hifox.com/'),
'invalid QA evidence link')
candidate.check_qa(plan, receipt, reports, QA_AUTHORS)
fresh = owner_plan(task_id)
cd.require(fresh == plan, 'release plan changed during registration')
rel = task(task_id)
cd.require((rel.get('status') or {}).get('id') not in (cd.READY, cd.PUBLISHED),
'register QA before the owner moves the release task to 待发布')
sha, bundle = receipt['sha'], receipt['bundle']
links = '\n'.join(f'- {task(item)["url"]}#comment-{reports[item][0]["id"]}' for item in tasks)
body = f'批次验收通过\n\n提交 `{sha}`\n\n归档 `{bundle}`\n\n需求验收与批次回归报告\n{links}'
comment = add_comment(task_id, 'acceptance ' + bundle, body)
acceptance = {'verdict': 'passed', 'sha': sha, 'bundle': bundle, 'evidence': rel['url'] + '#comment-' + comment}
if cd.metadata(task(task_id), 'cd_acceptance') != acceptance:
hfx.hifox(CLI, 'task', 'metadata', 'set', task_id, 'cd_acceptance', json.dumps(json.dumps(acceptance)))
cd.require(cd.metadata(task(task_id), 'cd_acceptance') == acceptance, 'acceptance writeback not verified')
return acceptance
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('action', choices=('prepare', 'register', 'status'))
parser.add_argument('task')
args = parser.parse_args()
if args.action == 'prepare':
result = queue(args.task)
elif args.action == 'register':
result = register(args.task)
else:
plan = owner_plan(args.task)
key = cd.acceptance_digest(plan)
results = [STATE / key / 'ready.json', STATE / (key + '.dispatch.json')]
result = next((cd.read_json(cd.immutable_file(p)) for p in results if p.exists()), {'state': 'unprepared'})
print(json.dumps(result, ensure_ascii=False))
if __name__ == '__main__':
try:
main()
except HTTPError as exc:
sys.exit(f'Candidate coordinator: HTTP {exc.code}; reconcile Gitea before retry')
except (cd.CDError, runtime.qa_env.QAError, OSError, ValueError) as exc:
sys.exit(f'Candidate coordinator: {exc}')
+208
View File
@@ -0,0 +1,208 @@
#!/usr/bin/env python3
"""Validate a release batch and build its immutable candidate bundle."""
import argparse
import datetime
import json
import os
from pathlib import Path
import re
import subprocess
import sys
import tempfile
from types import SimpleNamespace
from urllib.request import Request
import hifox_release_trigger as integration
import production_cd as cd
API = f'/api/v1/repos/{cd.REPO}'
CONTEXTS = Path(__file__).resolve().parents[1] / '.gitea/required-contexts.txt'
FENCE = re.compile(r'^```kg-release-v1\s*\n(\{.*?\})\s*\n```\s*$', re.MULTILINE | re.DOTALL)
def read_forge(path):
token = os.getenv('KG_CANDIDATE_READ_TOKEN')
if not token:
return integration.forge('GET', path)
from urllib.request import ProxyHandler, build_opener
server = os.getenv('KG_CANDIDATE_FORGE', cd.FORGE)
cd.require(server in (cd.FORGE, 'http://192.168.50.223:3000'), 'untrusted Gitea origin')
request = Request(server + path, headers={'Authorization': 'token ' + token})
with build_opener(ProxyHandler({}), cd.NoRedirect()).open(request, timeout=20) as response:
return json.load(response)
def check_plan(plan):
cd.require(isinstance(plan, dict) and set(plan) == {'task', 'sha', 'base', 'items', 'extra'},
'invalid release plan fields')
cd.require(cd.matches(cd.UUID, plan['task']) and cd.matches(cd.SHA, plan['sha'])
and cd.matches(cd.SHA, plan['base']) and plan['base'] != plan['sha'], 'invalid release task or SHA range')
items = plan['items']
cd.require(isinstance(items, list) and 0 < len(items) <= 100, 'require one to 100 requirements')
for item in items:
cd.require(isinstance(item, dict) and set(item) == {'task', 'pr'} and cd.matches(cd.UUID, item['task'])
and item['task'] != plan['task'] and type(item['pr']) is int and item['pr'] > 0, 'invalid requirement or PR')
cd.require(len({i['task'] for i in items}) == len(items) == len({i['pr'] for i in items}),
'duplicate requirement or PR')
extra = plan['extra']
cd.require(isinstance(extra, list) and len(extra) <= 100 and all(cd.matches(cd.SHA, s) for s in extra)
and len(set(extra)) == len(extra), 'invalid additional reviewed commits')
def check_scope(plan, read_pr, first_parents):
check_plan(plan)
required = set(plan['extra'])
for item in plan['items']:
pr = read_pr(item['pr'])
sha = pr.get('merge_commit_sha')
cd.require(pr.get('merged') is True and (pr.get('base') or {}).get('ref') == 'main' and cd.matches(cd.SHA, sha),
f"PR #{item['pr']} must be merged into main")
cd.require(sha not in required, 'landed commit is listed in multiple scope entries')
required.add(sha)
cd.require(required == set(first_parents), 'commits outside the release scope, or planned commits absent from main range')
def instant(value):
cd.require(isinstance(value, str) and bool(re.search(r'(Z|[+-]\d\d:\d\d)$', value)), 'invalid QA timestamp')
return datetime.datetime.fromisoformat(value.replace('Z', '+00:00'))
def check_qa(plan, receipt, reports, authors):
check_plan(plan)
tasks = {item['task'] for item in plan['items']} | {plan['task']}
cd.require(set(reports) == tasks, 'require reports on every requirement and the release task')
cd.require(cd.matches(cd.HASH, receipt.get('bundle')) and receipt.get('sha') == plan['sha'], 'invalid candidate receipt')
for task, (comment, report) in reports.items():
cd.require((comment.get('actor') or {}).get('id') in authors, f'{task}: require authorized QA report author')
cd.require(all(report.get(k) == receipt[k] for k in ('sha', 'bundle', 'url')), f'{task}: report is for a different candidate')
cd.require(instant(comment.get('createdAt')) > instant(receipt['ready_at']), f'{task}: report predates candidate')
cd.require(not comment.get('updatedAt') or instant(comment['updatedAt']) >= instant(comment['createdAt']),
f'{task}: invalid report revision timestamp')
values = [report.get(field) for field in ('required', 'passed', 'failed', 'blocked')]
cd.require(all(type(v) is int for v in values) and values[0] > 0
and values == [values[0], values[0], 0, 0] and report.get('verdict') == 'passed',
f'{task}: required QA cases have not passed')
def git(*args, cwd=None, allowed=(0,)):
env = dict(os.environ, GIT_TERMINAL_PROMPT='0')
return cd.run(['git', *args], 'read candidate source', cwd=cwd, env=env, allowed=allowed,
timeout=120).decode().strip()
def verify_source(plan, repo):
check_plan(plan)
main_line = git('rev-list', '--first-parent', 'origin/main', cwd=repo).splitlines()
sha, base = plan['sha'], plan['base']
cd.require(sha in main_line, 'candidate must be on main first-parent history')
cd.require(git('merge-base', sha, base, cwd=repo, allowed=(0, 1)) == base,
'running baseline must be an ancestor of the candidate')
# A previously deployed branch may enter main as a second parent. Its reachable
# commits are already represented by the baseline, but the integration itself is in scope.
added = git('rev-list', '--first-parent', f'{base}..{sha}', cwd=repo).splitlines()
check_scope(plan, lambda n: read_forge(API + f'/pulls/{n}'), added)
contexts = {line.split('#', 1)[0].strip() for line in CONTEXTS.read_text().splitlines()} - {''}
cd.verify_contexts(read_forge(API + f'/commits/{sha}/status'), contexts)
def build(plan, repo, destination):
check_plan(plan)
verify_source(plan, repo)
sha = plan['sha']
destination = destination.resolve()
if destination.exists():
digest = cd.hash_file(destination / 'release.json')
cd.verify_bundle(destination, {'task': plan['task'], 'sha': sha, 'bundle': digest})
return digest
destination.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
with tempfile.TemporaryDirectory(prefix='kg-candidate-source-') as name:
src = Path(name) / 'source'
git('clone', '--no-checkout', '--shared', str(repo.resolve()), str(src))
git('checkout', '--detach', sha, cwd=src)
cd.require(git('rev-parse', 'HEAD', cwd=src) == sha and not git('status', '--porcelain', cwd=src),
'candidate checkout differs from selected commit')
identity = json.loads(cd.run([sys.executable, 'scripts/version.py', '--identity'], 'read build version', cwd=src))
cd.require(identity.get('commit_sha') == sha, 'version script returned another SHA')
flags = {'VERSION': identity['release_version'] or 'dev', 'RELEASE_VERSION': identity['release_version'] or '',
'BUILD_KIND': identity['build_kind'], 'COMMITS_SINCE_RELEASE': identity['commits_since_release'] or '',
'COMMIT_SHA': sha, 'BUILD_TIME': identity['built_at']}
common = ['docker', 'build', '--pull=false', '--label', f'{cd.REVISION}={sha}']
# Only pass the explicitly configured build proxy, never the agent's inherited credentials.
for variable in ('HTTP_PROXY', 'HTTPS_PROXY', 'NO_PROXY'):
value = os.getenv('KG_BUILD_' + variable)
if value:
cd.require('@' not in value, 'build proxy must not contain credentials')
common += ['--build-arg', f'{variable}={value}']
tags = {name: f'kg-release-candidate-{name}:{sha}' for name in ('backend', 'web')}
for role, dockerfile in (('backend', 'Dockerfile'), ('web', 'Dockerfile.web')):
args = common + ['-f', dockerfile, '-t', tags[role]]
if role == 'backend':
for key, value in flags.items():
args += ['--build-arg', f'{key}={value}']
subprocess.run(args + ['.'], cwd=src, check=True, timeout=1800)
image_ids = {key: cd.image_inspect(tag)['Id'] for key, tag in tags.items()}
# pack takes its migration list from this commit and validates the OCI revision and image IDs.
original = Path.cwd()
try:
os.chdir(src)
cd.pack(SimpleNamespace(sha=sha, task=plan['task'], api=image_ids['backend'], worker=image_ids['backend'],
web=image_ids['web'], output=destination))
finally:
os.chdir(original)
return cd.hash_file(destination / 'release.json')
def event_plan(event, env):
cd.require(env.get('GITHUB_EVENT_NAME') == 'workflow_dispatch' and env.get('GITHUB_REPOSITORY') == cd.REPO,
'candidate workflow requires an explicit dispatch in the governance repository')
inputs = event.get('inputs') or {}
mode = inputs.get('mode')
cd.require(mode in ('verify', 'prepare'), 'unknown candidate mode')
if mode == 'prepare':
cd.require(env.get('GITHUB_REF') == 'refs/heads/main', 'prepare requires the workflow from main')
plan = json.loads(inputs['plan'])
check_plan(plan)
return plan, mode
def proof(plan, mode):
return 'KG_CANDIDATE_PLAN_V1 ' + cd.acceptance_digest({'plan': plan, 'mode': mode})
def main():
parser = argparse.ArgumentParser(description=__doc__)
sub = parser.add_subparsers(dest='action', required=True)
guard = sub.add_parser('guard')
guard.add_argument('--event', required=True, type=Path)
guard.add_argument('--repo', required=True, type=Path)
for name in ('verify', 'build'):
arg = sub.add_parser(name)
arg.add_argument('--plan', required=True, type=Path)
arg.add_argument('--repo', required=True, type=Path)
if name == 'build':
arg.add_argument('--output', required=True, type=Path)
args = parser.parse_args()
if args.action == 'guard':
plan, mode = event_plan(cd.read_json(args.event), os.environ)
verify_source(plan, args.repo)
print(proof(plan, mode))
return
plan = cd.read_json(args.plan)
check_plan(plan)
if args.action == 'verify':
verify_source(plan, args.repo)
print(json.dumps({'state': 'verified', 'sha': plan['sha'], 'task': plan['task']}))
else:
digest = build(plan, args.repo, args.output)
print(json.dumps({'state': 'built', 'sha': plan['sha'], 'task': plan['task'], 'bundle': digest}))
if __name__ == '__main__':
try:
main()
except cd.CDError as exc:
sys.exit(f'Candidate: {exc}')
except (OSError, ValueError, KeyError, subprocess.SubprocessError) as exc:
sys.exit(f'Candidate: {type(exc).__name__}; check build or release input')
+155
View File
@@ -0,0 +1,155 @@
#!/usr/bin/env python3
"""Run the sealed candidate on an isolated acceptance stack."""
import argparse
import ipaddress
import json
from pathlib import Path
import re
import secrets
import sys
import tempfile
from types import SimpleNamespace
from urllib.parse import quote
import production_cd as cd
import qa_env
def isolated_subnet(exclude=()):
nets = cd.run(['docker', 'network', 'ls', '-q'], 'list Docker networks').decode().split()
data = json.loads(cd.run(['docker', 'network', 'inspect', *nets], 'read Docker networks')) if nets else []
occupied = [ipaddress.ip_network(row['Subnet']) for net in data for row in net['IPAM']['Config'] or []
if row.get('Subnet') and ':' not in row['Subnet']]
routes = json.loads(cd.run(['ip', '-j', '-4', 'route'], 'read host routes'))
occupied += [ipaddress.ip_network(route['dst'], strict=False) for route in routes if route['dst'] != 'default']
occupied += [ipaddress.ip_network(subnet) for subnet in exclude]
for subnet in ipaddress.ip_network('10.241.233.0/24').subnets(new_prefix=28):
if not any(subnet.overlaps(other) for other in occupied):
return str(subnet)
raise cd.CDError('no available candidate subnet')
def qa_database(path):
db = qa_env.database_config(path)
passfile, cert = [path.parent / name for name in ('qa.pgpass', 'rds-ca.pem')]
qa_env.private_file(passfile)
qa_env.private_file(cert)
endpoint = f"{db['host']}:{db['port']}:"
expected = f"{endpoint}{db['database']}:{db['user']}:"
entries = [line for line in passfile.read_text().splitlines() if line and not line.startswith('#')]
qa_entry = re.compile(re.escape(endpoint) + r'kg_qa_[a-z0-9_]{1,56}:kg_qa_[a-z0-9_]{1,56}:(?:[^:\\]|\\.)+')
cd.require(all(qa_entry.fullmatch(line) for line in entries), 'pgpass must contain only exact QA entries at the configured endpoint')
matching = [line for line in entries if line.startswith(expected)]
cd.require(len(matching) == 1, 'pgpass must contain exactly one entry for the configured QA database and role')
password = re.sub(r'\\(.)', r'\1', matching[0][len(expected):])
cd.require(bool(password), 'dedicated QA database password missing')
url = (f"postgresql://{db['user']}:{quote(password, safe='')}@{db['host']}:{db['port']}/{db['database']}"
'?sslmode=verify-full&sslrootcert=/run/qa/rds-ca.pem')
return url, cert
def ready(directory, bundle, test_database=None):
bundle = bundle.resolve()
manifest = cd.read_json(bundle / 'release.json')
digest = cd.hash_file(bundle / 'release.json')
request = {key: manifest[key] for key in ('sha', 'task')}
request['bundle'] = digest
cd.verify_bundle(bundle, request)
project = 'kg-batch-' + digest[:20] + ('-smoke' if test_database is None else '')
cf = directory / 'compose.json'
receipt_path = directory / 'ready.json'
cmd = ['docker', 'compose', '-p', project, '-f', str(cf)]
if cf.exists():
cd.require(receipt_path.exists(), 'candidate startup is unresolved; inspect its Compose project')
receipt = cd.read_json(cd.immutable_file(receipt_path))
cd.require(receipt['task'] == request['task'] and receipt['bundle'] == digest, 'candidate already holds another bundle')
attest(bundle, receipt)
return receipt
services = {}
env = {'APP_ADDR': '0.0.0.0:8080', 'TEST_WEKNORA_ENABLED': 'false', 'PP_SCAN_ENABLED': 'false',
'RELEASE_WORKER_ENABLED': 'false', 'PRODUCTION_RELEASE_REQUESTS_ENABLED': 'false',
'DOBOTAI_OPS_READ_ENABLED': 'false', 'DOBOTAI_OPS_DIRECTORY_SYNC_ENABLED': 'false'}
if test_database is None:
password = secrets.token_hex(24)
cd.atomic_write(directory / 'postgres.env', f'POSTGRES_USER=qa\nPOSTGRES_DB=governance\nPOSTGRES_PASSWORD={password}\n'.encode())
env['DATA' + 'BASE_URL'] = f'postgres://qa:{password}@postgres:5432/governance?sslmode=disable'
services['postgres'] = {'image': 'postgres:17-alpine', 'env_file': [str(directory / 'postgres.env')],
'tmpfs': ['/var/lib/postgresql/data'],
'healthcheck': {'test': ['CMD', 'pg_isready', '-U', 'qa', '-d', 'governance'],
'interval': '2s', 'timeout': '2s', 'retries': 20}}
else:
url, cert = qa_database(test_database)
env['DATA' + 'BASE_URL'] = url
cd.atomic_write(directory / 'rds-ca.pem', cert.read_bytes(), mode=0o444)
app_env = directory / 'app.env'
cd.atomic_write(app_env, ''.join(f'{k}={v}\n' for k, v in env.items()).encode())
names = {role: f'{project}-{role}' for role in cd.ROLES}
for role, item in manifest['images'].items():
archive = bundle / f'{role}.tar'
cd.verify_archive(archive, item['id'])
cd.run(['docker', 'load', '-i', str(archive)], 'load sealed candidate image', timeout=150)
services[role] = {'image': item['id'], 'container_name': names[role]}
for role in ('api', 'worker'):
services[role]['env_file'] = [str(app_env)]
if test_database is not None:
services[role]['volumes'] = [f'{directory / "rds-ca.pem"}:/run/qa/rds-ca.pem:ro']
services['api']['healthcheck'] = {'test': ['CMD', 'curl', '-fsS', 'http://127.0.0.1:8080/health'],
'interval': '2s', 'timeout': '3s', 'retries': 45}
if test_database is None:
services['api']['depends_on'] = {'postgres': {'condition': 'service_healthy'}}
services['worker'].update(command=['/app/worker'], depends_on={'api': {'condition': 'service_healthy'}})
services['web'].update(ports=['127.0.0.1::8080'], depends_on={'api': {'condition': 'service_healthy'}})
internal_subnet = isolated_subnet()
networks = {'default': {'internal': test_database is None, 'ipam': {'config': [{'subnet': internal_subnet}]}}}
if test_database is None:
# The private smoke network has no NAT. Only the web container gets an ingress network.
networks['ingress'] = {'ipam': {'config': [{'subnet': isolated_subnet([internal_subnet])}]}}
services['web']['networks'] = {'default': {}, 'ingress': {}}
cd.record(cf, {'services': services, 'networks': networks})
try:
cd.run(cmd + ['up', '-d', '--no-build', '--pull', 'never'], 'start candidate Compose project', timeout=130)
raw_ports = json.loads(cd.run(['docker', 'inspect', '--format', '{{json .NetworkSettings.Ports}}', names['web']],
'read candidate web binding'))
port = (raw_ports or {}).get('8080/tcp') or []
cd.require(len(port) == 1 and port[0].get('HostIp') == '127.0.0.1'
and re.fullmatch(r'[1-9][0-9]{0,4}', port[0].get('HostPort', '')),
'candidate web has no verified loopback binding')
receipt = {**request, 'url': f'http://127.0.0.1:{port[0]["HostPort"]}', 'containers': names,
'images': {role: image['id'] for role, image in manifest['images'].items()},
'mode': 'smoke' if test_database is None else 'acceptance'}
cd.wait_ready(lambda: attest(bundle, receipt), seconds=65)
receipt['ready_at'] = cd.stamp()
cd.record(receipt_path, receipt)
return receipt
except Exception:
cd.run(cmd + ['down', '--timeout', '3'], 'stop unsuccessful candidate Compose project', timeout=40)
raise
def attest(bundle, receipt):
cd.require(cd.hash_file(bundle / 'release.json') == receipt['bundle'], 'candidate bundle changed after deployment')
cd.attest(SimpleNamespace(sha=receipt['sha'], task=receipt['task'], directory=bundle,
test_url=receipt['url'], **receipt['containers']))
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('bundle', type=Path)
args = parser.parse_args()
with tempfile.TemporaryDirectory(prefix='kg-candidate-smoke-') as temp:
directory = Path(temp)
try:
print(json.dumps(ready(directory, args.bundle)))
finally:
if (directory / 'compose.json').exists():
digest = cd.hash_file(args.bundle / 'release.json')
cmd = ['docker', 'compose', '-p', 'kg-batch-' + digest[:20] + '-smoke', '-f', str(directory / 'compose.json')]
cd.run(cmd + ['down', '--timeout', '3'], 'remove disposable rehearsal containers', timeout=45)
if __name__ == '__main__':
try:
main()
except (cd.CDError, qa_env.QAError, OSError, ValueError) as exc:
sys.exit(f'Candidate runtime: {exc}')
+115
View File
@@ -0,0 +1,115 @@
#!/usr/bin/env python3
"""Local build worker for authenticated Gitea candidate jobs."""
import hmac
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import json
import os
from pathlib import Path
import sys
from urllib.error import URLError
import candidate_coordinator as coordinator
import candidate_release as candidate
import candidate_runtime as runtime
import production_cd as cd
def verify_job(run_id, plan, repo):
cd.require(isinstance(run_id, str) and run_id.isascii() and run_id.isdigit() and 0 < len(run_id) < 16,
'invalid candidate workflow run')
target = candidate.API + f'/actions/runs/{run_id}'
run = candidate.read_forge(target)
sha = run.get('head_sha')
cd.require(run.get('event') == 'workflow_dispatch' and run.get('path') == 'prepare-candidate.yml@refs/heads/main'
and run.get('status') == 'in_progress' and (run.get('actor') or {}).get('id') == 1
and cd.matches(cd.SHA, sha), 'untrusted candidate workflow run')
file = '.gitea/workflows/prepare-candidate.yml'
cd.require(candidate.git('show', f'{sha}:{file}', cwd=repo) == Path(__file__).resolve().parents[1].joinpath(file).read_text().strip(),
'candidate workflow differs from locally installed instructions')
jobs = candidate.read_forge(target + '/jobs').get('jobs', [])
guard = [job for job in jobs if job.get('name') == 'guard' and job.get('conclusion') == 'success']
cd.require(len(guard) == 1 and type(guard[0].get('id')) is int, 'candidate guard did not succeed')
# Gitea logs are plaintext and may prefix each line with a timestamp.
raw = coordinator.hfx.forge('GET', candidate.API + f'/actions/jobs/{guard[0]["id"]}/logs', raw=True)
cd.require(len(raw) <= 2**20, 'candidate guard log exceeded the read limit')
lines = raw.decode().splitlines()
cd.require(sum(line.strip().endswith(candidate.proof(plan, 'prepare')) for line in lines) == 1,
'candidate input does not match Gitea guard proof')
def main_site_sha():
raw = cd.run(['ssh', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=6', 'weknora-test',
'docker compose -p knowledge-governance-cloud-test -f /opt/knowledge-governance/compose.json '
'exec -T api /app/api --version-record-status'], 'read main site build identity',
allowed=(0, 1), timeout=15)
sha = json.loads(raw).get('commit_sha')
cd.require(cd.matches(cd.SHA, sha), 'main site did not report a full SHA')
return sha
def prepare(payload, repo):
cd.require(isinstance(payload, dict) and set(payload) == {'run', 'plan'}, 'invalid candidate job payload')
plan = payload['plan']
candidate.check_plan(plan)
key = cd.acceptance_digest(plan)
state = coordinator.STATE
conf = Path.home() / '.config/knowledge-governance/qa.json'
with cd.deploy_lock(state / 'runtime.lock'):
cd.require(coordinator.owner_plan(plan['task']) == plan, 'release owner plan changed')
runtime.qa_database(conf)
candidate.git('fetch', 'origin', '+refs/heads/main:refs/remotes/origin/main', cwd=repo)
verify_job(payload['run'], plan, repo)
cd.require(main_site_sha() == plan['base'], 'release baseline differs from the live main site')
directory = state / key
directory.mkdir(mode=0o700, exist_ok=True)
for existing in state.glob('*/compose.json'):
cd.require(existing.parent == directory, 'another candidate owns the acceptance slot')
candidate.build(plan, repo, directory / 'bundle')
cd.require(coordinator.owner_plan(plan['task']) == plan, 'release plan changed after candidate build')
receipt = runtime.ready(directory, directory / 'bundle', conf)
coordinator.publish_candidate(plan, receipt, payload['run'])
return receipt
def serve(repo, access):
secret = cd.immutable_file(access).read_text().strip()
cd.require(cd.matches(cd.HASH, secret), 'invalid candidate access file')
coordinator.STATE.mkdir(mode=0o700, parents=True, exist_ok=True)
class Handler(BaseHTTPRequestHandler):
def log_message(self, *_args):
pass
def respond(self, status, body):
data = json.dumps(body).encode()
self.send_response(status)
self.send_header('Content-Type', 'application/json')
self.send_header('Content-Length', str(len(data)))
self.end_headers()
self.wfile.write(data)
def do_POST(self):
if self.path != '/prepare' or not hmac.compare_digest(self.headers.get('Authorization', ''), 'Bearer ' + secret):
self.respond(403, {'error': 'candidate authorization refused'})
return
try:
size = int(self.headers.get('Content-Length', 0))
cd.require(0 < size <= 65536, 'invalid candidate payload size')
self.connection.settimeout(10)
payload = json.loads(self.rfile.read(size))
self.connection.settimeout(60)
receipt = prepare(payload, repo)
self.respond(200, receipt)
except (cd.CDError, runtime.qa_env.QAError) as exc:
self.respond(409, {'error': str(exc)})
except (OSError, KeyError, ValueError, URLError) as exc:
self.respond(502, {'error': f'candidate operation failed: {type(exc).__name__}'})
ThreadingHTTPServer(('127.0.0.1', 38984), Handler).serve_forever()
if __name__ == '__main__':
if len(sys.argv) != 3:
sys.exit('usage: candidate_worker.py <source repository> <private access file>')
serve(Path(sys.argv[1]).resolve(), Path(sys.argv[2]).resolve())
+83
View File
@@ -0,0 +1,83 @@
"""Stage an accepted bundle on the governance host before dispatch."""
import json
import re
import shlex
import subprocess
from pathlib import Path
import production_cd as cd
ROOT = '/opt/knowledge-governance/cd/bundles'
FILES = ('release.json', 'api.tar', 'web.tar', 'worker.tar')
SSH = ['ssh', '-T', '-oBatchMode=yes', '-oStrictHostKeyChecking=yes', '-oClearAllForwardings=yes', '-oConnectTimeout=10']
HOST = 'weknora-test'
# Runs on the target using its installed controller. Exit 3 means absent only.
VERIFY = '''import json, os, runpy, stat, sys
from pathlib import Path
p = Path(sys.argv[1])
try:
info = p.lstat()
except FileNotFoundError:
sys.exit(3)
if not stat.S_ISDIR(info.st_mode) or info.st_uid != os.geteuid() or info.st_mode & 0o022:
sys.exit('unsafe bundle directory')
files = {'release.json', 'api.tar', 'web.tar', 'worker.tar'}
if {f.name for f in p.iterdir()} != files or any(stat.S_IMODE(f.lstat().st_mode) != 0o600 for f in p.iterdir()):
sys.exit('unexpected bundle files or permissions')
cd = runpy.run_path('/opt/knowledge-governance/cd/bin/production_cd.py')
cd['verify_bundle'](p, dict(zip(('sha', 'task', 'bundle'), sys.argv[2:])))
print(sys.argv[4])'''
def remote(argv, *, allow_absent=False):
proc = subprocess.run([*SSH, HOST, shlex.join(argv)], capture_output=True, text=True, timeout=240)
if allow_absent and proc.returncode == 3:
return None
if proc.returncode:
raise cd.CDError('target archive handoff failed at ' + argv[0] + ': ' + proc.stderr.strip()[-300:])
return proc.stdout.strip()
def stage_bundle(request, candidates=None):
sha, task, digest = (request[k] for k in ('sha', 'task', 'bundle'))
cd.require(cd.matches(cd.SHA, sha) and cd.matches(cd.UUID, task) and cd.matches(cd.HASH, digest),
'invalid archive identity')
final = ROOT + '/' + digest
def verify(path, absent=False):
result = remote(['/usr/bin/python3', '-I', '-c', VERIFY, path, sha, task, digest], allow_absent=absent)
if absent and result is None:
return False
cd.require(result == digest, 'target archive verification returned a different digest')
return True
if verify(final, absent=True):
return digest
if candidates is None:
candidates = Path.home() / '.local/state/kg-candidate-release'
sources = []
for receipt in candidates.glob('*/ready.json'):
if not re.fullmatch('[0-9a-f]{64}', receipt.parent.name) or receipt.parent.is_symlink():
continue
ready = cd.read_json(cd.immutable_file(receipt))
if ready.get('mode') == 'acceptance' and all(ready.get(k) == request[k] for k in ('sha', 'task', 'bundle')):
sources.append(receipt.parent / 'bundle')
cd.require(len(sources) == 1, 'no unique accepted local archive matching task, commit and bundle')
source = sources[0]
cd.require(not source.is_symlink(), 'unexpected local archive directory')
cd.verify_bundle(source, request, archives=False)
paths = [str(cd.immutable_file(source / name)) for name in FILES]
temp = remote(['mktemp', '-d', ROOT + '/.handoff-XXXXXXXXXXXX'])
if not temp or not re.fullmatch(re.escape(ROOT) + r'/\.handoff-[A-Za-z0-9]{12}', temp):
raise cd.CDError('invalid target staging path')
try:
subprocess.run(['rsync', '-t', '--chmod=F600', '--perms', '-e', shlex.join(SSH), '--',
*paths, HOST + ':' + temp + '/'], check=True, timeout=1500)
verify(temp)
remote(['mv', '-Tn', '--', temp, final])
verify(final)
return digest
except (subprocess.SubprocessError, OSError) as exc:
raise cd.CDError('archive transfer incomplete before dispatch: ' + type(exc).__name__) from exc
finally:
remote(['rm', '-rf', '--', temp])
+56
View File
@@ -0,0 +1,56 @@
"""Run inside a governance container. Read the real application DB ledger only."""
import json
import os
import subprocess
from urllib.parse import parse_qsl, unquote, urlsplit
def connection_env(env):
# Keep only the connection properties actually shared by libpq and pgx.
# Unknown DSN options can change the database identity or schema search path.
u = urlsplit(env['DATABASE' + '_URL'])
if u.scheme not in ('postgres', 'postgresql') or not u.hostname or not u.username or not u.path[1:] or u.fragment:
raise ValueError('invalid database URL')
query = parse_qsl(u.query, strict_parsing=True, keep_blank_values=True)
supported = {'sslmode': 'PGSSLMODE', 'sslrootcert': 'PGSSLROOTCERT', 'sslcert': 'PGSSLCERT', 'sslkey': 'PGSSLKEY'}
if len(dict(query)) != len(query) or any(key not in supported or not val for key, val in query):
raise ValueError('unknown database connection options')
safe = {'PATH': '/usr/bin:/bin', 'HOME': env.get('HOME', '/nonexistent'), 'LC_ALL': 'C',
'PGHOST': u.hostname, 'PGPORT': str(u.port or 5432), 'PGDATABASE': unquote(u.path[1:]),
'PGUSER': unquote(u.username), 'PGCONNECT_TIMEOUT': '5',
'PGOPTIONS': '-c default_transaction_read_only=on -c statement_timeout=5000'}
for name in ('PGPASSFILE', 'PGSSLMODE', 'PGSSLROOTCERT', 'PGSSLCERT', 'PGSSLKEY'):
if env.get(name):
safe[name] = env[name]
for name in env:
if name.startswith('PG') and name not in safe:
raise ValueError('unknown inherited database connection options')
safe.update({supported[key]: value for key, value in query})
if u.password:
safe['PGPASSWORD'] = unquote(u.password)
for name in ('PGDATABASE', 'PGUSER'):
if any(char in safe[name] for char in '\r\n\x00='):
raise ValueError('unsafe database identifier')
return safe
def main():
env = connection_env(os.environ)
sql = """SELECT json_build_object('database', current_database(), 'user', current_user,
'read_only', current_setting('transaction_read_only'),
'versions', (SELECT json_agg(version ORDER BY version) FROM schema_migrations));"""
p = subprocess.run(['psql', '-XAtw', '-v', 'ON_ERROR_STOP=1', '-c', sql],
env=env, capture_output=True, timeout=12)
if p.returncode:
raise ValueError('query failed')
data = json.loads(p.stdout)
if data['read_only'] != 'on' or data['database'] != env['PGDATABASE'] or data['user'] != env['PGUSER']:
raise ValueError('database identity mismatch')
print(json.dumps(data['versions']))
if __name__ == '__main__':
try:
main()
except (OSError, ValueError, KeyError, subprocess.TimeoutExpired):
raise SystemExit('read-only migration probe failed') from None
+8
View File
@@ -442,6 +442,14 @@ def cmd_internal_contracts(go: str) -> int:
判据同时核三件事:进程退出码、必需测试集合、负例失败归因——
缺任意一件,"绿"就可能是别的测试失败/编译错误伪装出来的。
"""
qa_rc = subprocess.run(py("-m", "unittest", "discover", "-s", "scripts", "-p", "test_qa_env.py", "-v"),
cwd=ROOT).returncode
if qa_rc:
return qa_rc
for pattern in ('test_production_cd.py', 'test_candidate_release.py'):
cd_rc = subprocess.run(py('-m', 'unittest', 'discover', '-s', 'scripts', '-p', pattern, '-v'), cwd=ROOT).returncode
if cd_rc:
return cd_rc
snapshot_rc = subprocess.run(py("scripts/development_snapshot.py","--self-test"),cwd=ROOT).returncode
if snapshot_rc:
return 1
+17 -1
View File
@@ -1,6 +1,20 @@
#!/usr/bin/env bash
# 重建并上线 governance api + web(本机 docker build 需要宿主代理 + --network host)
set -u
# Share the image-only Compose switch with CD without entering the legacy build path.
compose_up() {
"${compose[@]}" up -d --no-build --no-deps "$@"
}
if [[ "${1:-}" == --verified-compose ]]; then
[[ "$#" == 7 && "$5" == api && "$6" == web && "$7" == worker && "$4" == /* ]] || exit 2
cd -- "$2" || exit 1
compose=(docker compose -p "$3" -f "$4")
compose_up --pull never "$5" "$6" "$7"
exit $?
fi
cd "$(dirname "${BASH_SOURCE[0]}")/.." || exit 1
[ -z "$(git status --porcelain --untracked-files=normal)" ] || { printf "%s\n" "REFUSED_DIRTY_SOURCE"; exit 1; }
TS=$(date +%Y%m%d-%H%M%S)
@@ -103,7 +117,9 @@ if [ "${GATES_PREV}" = "true" ] && [[ "${COMPOSE_FILES_EFFECTIVE}" != *compose.r
echo " 确实要关闸:ALLOW_GATE_OFF=1 bash scripts/deploy-api-web.sh"
exit 1
fi
docker compose ${COMPOSE_FILES_EFFECTIVE} up -d --no-build --no-deps api web || { echo "UP_FAILED"; exit 1; }
read -r -a compose_file_args <<< "$COMPOSE_FILES_EFFECTIVE"
compose=(docker compose "${compose_file_args[@]}")
compose_up api web || { echo "UP_FAILED"; exit 1; }
echo "=== 5. 状态"
docker ps --filter name=knowledge-governance-p1 --format '{{.Names}} {{.Status}} {{.Image}}'
+103
View File
@@ -0,0 +1,103 @@
#!/usr/bin/env python3
"""Submit a HiFox-approved release from the designated CD Agent host."""
import argparse
import base64
import json
import os
from pathlib import Path
import re
import sys
from urllib.error import HTTPError
from urllib.request import ProxyHandler, Request, build_opener
import production_cd as cd
DISPATCH = f'/api/v1/repos/{cd.REPO}/actions/workflows/deploy-production.yml/dispatches?return_run_details=true'
PATH = Path.home() / '.local/state/kg-hifox-release'
RUN_ID = re.compile('[1-9][0-9]{0,14}')
def forge(method, path, payload=None, *, raw=False):
request = Request(cd.FORGE + path, method=method,
data=json.dumps(payload).encode() if payload is not None else None)
env = {**os.environ, 'GIT_TERMINAL_PROMPT': '0', 'GIT_ASKPASS': '/bin/false'}
fields = dict(line.split('=', 1) for line in cd.run(
['/usr/bin/git', 'credential', 'fill'], 'read Gitea credential', cwd='/', env=env,
input_data=f'url={cd.FORGE}/{cd.REPO}.git\n\n'.encode()).decode().splitlines() if '=' in line)
cd.require(fields.get('username') and fields.get('password'), 'Gitea credential unavailable')
auth = base64.b64encode(f'{fields["username"]}:{fields["password"]}'.encode()).decode()
request.add_header('Authorization', 'Basic ' + auth)
request.add_header('Content-Type', 'application/json')
with build_opener(ProxyHandler({}), cd.NoRedirect()).open(request, timeout=20) as response:
return response.read(2**20 + 1) if raw else json.load(response)
def hifox(cli, *args):
env = {'PATH': '/usr/local/bin:/usr/bin:/bin', 'HOME': str(Path.home()), 'CI': '1'}
raw = cd.run([cli, '--organization-id', cd.ORG, *args, '--output', 'json'], 'read HiFox release record', env=env)
result = json.JSONDecoder().raw_decode(raw.decode().strip())[0]
cd.require(isinstance(result, (dict, list)) and (not isinstance(result, dict)
or (result.get('success') is not False and not result.get('error'))), 'HiFox record unavailable')
return result
def stage_bundle(inputs):
from cd_bundle_handoff import stage_bundle as stage
return stage(inputs)
def queue(task_id, cli, base=PATH):
cd.require(cd.matches(cd.UUID, task_id), 'use the triggering task UUID')
task = hifox(cli, 'task', 'view', task_id)
if not isinstance(task, dict) or task.get('id') != task_id or task.get('spaceId') != cd.SPACE:
raise cd.CDError('task is outside the release space')
acceptance = cd.metadata(task, 'cd_acceptance') or {}
cd.require(isinstance(acceptance, dict) and cd.matches(cd.SHA, acceptance.get('sha'))
and cd.matches(cd.HASH, acceptance.get('bundle')), 'skip: no registered candidate acceptance')
inputs = dict(action='deploy', confirm='deploy-production', sha=acceptance['sha'], bundle=acceptance['bundle'], task=task_id)
timeline = hifox(cli, 'api', 'get', f'/rest/v1/tasks/{task_id}/timeline')
if not isinstance(timeline, list):
raise cd.CDError('HiFox timeline unavailable')
binding, approved_at = cd.release_approval(task, timeline, inputs)
inputs.update(binding)
since = cd.immutable_file(base / 'active-since').read_text().strip()
cd.require(re.fullmatch(r'\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ', since) and approved_at > since,
'status approval predates activation; enter 待发布 again after acceptance')
claim = base / (binding['approval_event'] + '.json')
with cd.deploy_lock(base / 'dispatch.lock'):
if claim.exists():
result = cd.read_json(cd.immutable_file(claim))
cd.require(result.get('inputs') == inputs, 'HiFox approval already used for a different release')
cd.require(result.get('state') == 'queued', 'dispatch outcome unknown; reconcile Gitea before retry')
return result
cd.require(stage_bundle(inputs) == inputs['bundle'], 'target archive handoff did not verify')
fresh_task = hifox(cli, 'task', 'view', task_id)
fresh_timeline = hifox(cli, 'api', 'get', f'/rest/v1/tasks/{task_id}/timeline')
cd.require(cd.release_approval(fresh_task, fresh_timeline, inputs) == (binding, approved_at),
'release approval changed during archive handoff')
result = {'state': 'submitting', 'inputs': inputs, 'started_at': cd.stamp()}
cd.record(claim, result)
response = forge('POST', DISPATCH, {'ref': 'main', 'inputs': inputs})
run_id = str(response.get('workflow_run_id', ''))
cd.require(cd.matches(RUN_ID, run_id), 'dispatch response has no valid run ID; reconcile before retry')
result.update(state='queued', run_id=run_id, run_url=f'{cd.FORGE}/{cd.REPO}/actions/runs/{run_id}')
cd.record(claim, result)
return result
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('task', help='UUID of the task that entered 待发布')
args = parser.parse_args()
executable = Path.home() / '.local/bin/hifox'
try:
print(json.dumps(queue(args.task, str(executable)), ensure_ascii=False))
except HTTPError as exc:
sys.exit(f'CD: Gitea dispatch HTTP {exc.code}; reconcile before retry')
except cd.CDError as exc:
sys.exit(f'CD: {exc}')
except (OSError, KeyError, ValueError, TypeError) as exc:
sys.exit(f'CD: {type(exc).__name__}; inspect the dispatch record')
+6
View File
@@ -0,0 +1,6 @@
#!/bin/sh
set -eu
umask 077
[ "${SSH_ORIGINAL_COMMAND:-}" = kg-cd-v1 ] || exit 1
exec /usr/bin/env -i HOME=/opt/knowledge-governance/cd PATH=/usr/bin:/bin LANG=C.UTF-8 \
GIT_TERMINAL_PROMPT=0 /usr/bin/python3 -I /opt/knowledge-governance/cd/bin/production_cd.py serve
+893
View File
@@ -0,0 +1,893 @@
#!/usr/bin/env python3
"""Governance application CD. The installed host copy owns the release boundary."""
import argparse
from contextlib import contextmanager
import copy
from datetime import datetime, timezone
import fcntl
import hashlib
from html.parser import HTMLParser
import json
import os
from pathlib import Path
import re
import stat
import subprocess
import sys
import tarfile
import tempfile
import time
from urllib.error import URLError
from urllib.parse import urlsplit
from urllib.request import HTTPRedirectHandler, ProxyHandler, build_opener
REPO = 'Weknora/knowledge-governance'
FORGE = 'https://gitea.zheromiku.top'
TARGET = 'cloud-test-governance-main'
ORG = '169e6f7f-e508-4a1f-9a9b-63d240439a3d'
SPACE = '106e05d1-4091-40b9-8c57-f76dc94f7825'
READY = '3e15556f-ca19-417c-8bfd-666634ea5d29'
PUBLISHED = '16185166-b8e9-4761-9926-845a1f41c96d'
RELEASE_OWNER = '39ae59fb-876c-4587-ab5d-a12a841c6c09'
LOGIN_URL = 'http://100.85.111.121:8088/'
ROLES = ('api', 'web', 'worker')
REVISION = 'org.opencontainers.image.revision'
DATA = Path('/opt/knowledge-governance/cd')
APP = DATA.parent
PROJECT = 'knowledge-governance-cloud-test'
SHA = re.compile('[0-9a-f]{40}')
HASH = re.compile('[0-9a-f]{64}')
IMAGE = re.compile('sha256:[0-9a-f]{64}')
UUID = re.compile('[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}')
GUARD_PREFIX = 'KG_CD_CONFIRM_V1 '
class CDError(RuntimeError):
pass
def require(ok, message):
if not ok:
raise CDError(message)
def stamp():
return datetime.now(timezone.utc).isoformat()
def read_json(path):
return json.loads(path.read_bytes())
def sync_dir(directory):
fd = os.open(directory, os.O_RDONLY | os.O_DIRECTORY)
try:
os.fsync(fd)
finally:
os.close(fd)
def atomic_write(path, data, mode=0o600):
fd, temp = tempfile.mkstemp(dir=path.parent)
try:
with os.fdopen(fd, 'wb') as out:
os.fchmod(out.fileno(), mode)
out.write(data)
out.flush()
os.fsync(out.fileno())
os.replace(temp, path)
sync_dir(path.parent)
finally:
Path(temp).unlink(missing_ok=True)
def record(path, value):
atomic_write(path, (json.dumps(value, ensure_ascii=False, sort_keys=True) + '\n').encode())
@contextmanager
def deploy_lock(path):
fd = os.open(path, os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600)
with os.fdopen(fd, 'r+') as handle:
try:
fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError as exc:
raise CDError('deployment lock busy') from exc
yield
def matches(pattern, text):
return isinstance(text, str) and pattern.fullmatch(text) is not None
def validate_request(request):
actions = {'deploy': 'deploy-production', 'writeback': 'retry-writeback'}
action = request.get('action')
require(action in actions and request.get('confirm') == actions[action], 'explicit confirmation required')
require(matches(SHA, request.get('sha')) and matches(UUID, request.get('task'))
and matches(HASH, request.get('bundle')), 'require full SHA, bundle SHA256 and task UUID')
require(matches(re.compile('[1-9][0-9]{0,14}'), request.get('run_id')), 'invalid Gitea run ID')
event, digest = request.get('approval_event', ''), request.get('acceptance_digest', '')
require((event == '' and digest == '') or
(action == 'deploy' and matches(UUID, event) and matches(HASH, digest)),
'invalid HiFox approval binding')
def guard_proof(request, control_sha):
require(matches(SHA, control_sha), 'invalid workflow source SHA')
binding = {key: request[key] for key in ('run_id', 'action', 'confirm', 'sha', 'bundle', 'task')}
if request.get('approval_event'):
binding.update(approval_event=request['approval_event'], acceptance_digest=request['acceptance_digest'])
binding.update(repository=REPO, target=TARGET, workflow_sha=control_sha)
serialized = json.dumps(binding, sort_keys=True, separators=(',', ':')).encode()
return GUARD_PREFIX + hashlib.sha256(serialized).hexdigest()
def verify_guard_log(log, request, control_sha):
expected = guard_proof(request, control_sha)
pattern = re.compile(r'\d{4}-\d{2}-\d{2}T[0-9:.]+Z (' + GUARD_PREFIX + r'[0-9a-f]{64})')
proofs = [match.group(1) for line in log.decode().splitlines() if (match := pattern.fullmatch(line))]
require(proofs == [expected], 'Gitea guard dispatch proof missing or different')
def hash_file(path):
with path.open('rb') as src:
return hashlib.file_digest(src, 'sha256').hexdigest()
def immutable_file(path):
info = path.lstat()
require(stat.S_ISREG(info.st_mode) and info.st_uid == os.geteuid() and not info.st_mode & 0o022,
'bundle requires regular files owned by the deployment account')
return path
def verify_bundle(directory, request, archives=True):
raw = immutable_file(directory / 'release.json').read_bytes()
require(hashlib.sha256(raw).hexdigest() == request['bundle'], 'release manifest digest mismatch')
manifest = json.loads(raw)
require(manifest.get('schema') == 1 and manifest.get('target') == TARGET
and manifest.get('sha') == request['sha'] and manifest.get('task') == request['task'],
'bundle commit, task or target mismatch')
require(set(manifest.get('images', {})) == set(ROLES), 'bundle must include API, web and worker')
for role, image in manifest['images'].items():
require(matches(IMAGE, image.get('id')) and matches(HASH, image.get('sha256')), 'invalid image record')
if archives:
archive = immutable_file(directory / (role + '.tar'))
require(hash_file(archive) == image['sha256'], f'{role} archive checksum mismatch')
versions = manifest.get('migrations')
require(isinstance(versions, list) and versions and all(type(n) is int and n > 0 for n in versions)
and versions == sorted(set(versions)), 'invalid migration ledger in manifest')
return manifest
def verify_contexts(result, contexts):
latest = {}
for item in result.get('statuses') or []:
latest.setdefault(item.get('context'), item.get('status'))
require(bool(contexts) and all(latest.get(context) == 'success' for context in contexts),
'required CI status is missing or unsuccessful')
def metadata(task, key):
value = (task.get('metadata') or {}).get(key)
return json.loads(value) if isinstance(value, str) else None
def check_task(task, request, receipt=None):
require(task.get('id') == request['task'] and task.get('spaceId') == SPACE, 'HiFox task or space mismatch')
status = (task.get('status') or {}).get('id')
same_publication = receipt and metadata(task, 'cd_release') == receipt.get('hifox')
require(status == READY or (status == PUBLISHED and same_publication), 'HiFox task is not ready for release')
evidence = metadata(task, 'cd_acceptance') or {}
url = urlsplit(evidence.get('evidence', ''))
require(evidence.get('verdict') == 'passed' and evidence.get('sha') == request['sha']
and evidence.get('bundle') == request['bundle'] and url.scheme == 'https' and url.hostname
and not (url.username or url.password or url.query)
and (not url.fragment or (url.netloc == 'app.hifox.com' and url.fragment.startswith('comment-')
and matches(UUID, url.fragment.removeprefix('comment-')))),
'missing or changed business acceptance for this commit and bundle')
return evidence
def acceptance_digest(acceptance):
return hashlib.sha256(json.dumps(acceptance, sort_keys=True, separators=(',', ':')).encode()).hexdigest()
def release_approval(task, timeline, request):
evidence = check_task(task, request)
changes = [row for row in timeline if row.get('event') == 'status_changed']
require(bool(changes), 'missing HiFox status history')
approval = changes[-1]
approver = approval.get('actor') or {}
event_at = approval.get('createdAt') or ''
status_at = task.get('statusChangedAt') or ''
try:
difference = abs((datetime.fromisoformat(event_at.replace('Z', '+00:00'))
- datetime.fromisoformat(status_at.replace('Z', '+00:00'))).total_seconds())
except (ValueError, TypeError):
difference = float('inf')
# HiFox logs the status change after saving the task, sometimes across a second boundary.
require((approval.get('metadata') or {}).get('to') == '待发布'
and difference <= 2
and approver.get('id') == RELEASE_OWNER and approver.get('type') == 'human'
and matches(UUID, approval.get('id')), 'the latest transition must be an approval by the release owner')
task_url = task.get('url', '')
prefix = task_url + '#comment-'
require(task_url.startswith('https://app.hifox.com/') and evidence['evidence'].startswith(prefix),
'automated release requires the same-task acceptance report')
comment_id = evidence['evidence'].removeprefix(prefix)
require(matches(UUID, comment_id), 'invalid acceptance report ID')
reports = [row for row in timeline if row.get('event') == 'commented' and row.get('id') == comment_id]
require(len(reports) == 1, 'acceptance report missing from task history')
report = reports[0]
body = report.get('content') or ''
require(report.get('createdAt') and (report.get('updatedAt') or report['createdAt']) < min(event_at, status_at)
and request['sha'] in body and request['bundle'] in body,
'the unchanged report must identify the candidate and predate approval')
binding = {'approval_event': approval['id'], 'acceptance_digest': acceptance_digest(evidence)}
require(all(request.get(key, value) == value for key, value in binding.items()),
'HiFox approval or acceptance changed after dispatch')
return binding, min(event_at, status_at)
def accepted_task(host, request):
task = host.task(request['task'])
if request.get('approval_event'):
release_approval(task, host.timeline(request['task']), request)
return check_task(task, request)
def release(host, request):
validate_request(request)
path = host.receipt_path
existing = read_json(path) if path.exists() else None
if request['action'] == 'writeback':
require(existing and existing['state'] in ('deployed_hifox_pending', 'published'),
'writeback requires a verified deployment receipt')
require(all(existing[k] == request[k] for k in ('sha', 'task', 'bundle')), 'receipt binding mismatch')
manifest = verify_bundle(host.bundle_path(request), request)
host.approve(request)
host.verify(manifest)
return writeback(host, request, existing)
require(existing is None, 'existing release receipt: use writeback or inspect interrupted/failed deployment')
host.approve(request)
manifest = verify_bundle(host.bundle_path(request), request)
host.check_ci(request)
accepted = accepted_task(host, request)
before = host.baseline()
host.pre_switch(before, manifest)
receipt = {k: request[k] for k in ('sha', 'task', 'bundle', 'run_id')}
receipt.update(state='preparing', target=TARGET, started_at=stamp(), previous=before)
record(path, receipt)
try:
host.load(host.bundle_path(request), manifest)
host.pre_switch(before, manifest)
host.approve(request)
require(accepted_task(host, request) == accepted, 'business acceptance changed before switch')
except (CDError, OSError, ValueError, KeyError) as exc:
receipt.update(state='failed_before_cutover', failure=str(exc) if isinstance(exc, CDError) else type(exc).__name__)
record(path, receipt)
raise CDError(f'failed_before_cutover: {exc}' if isinstance(exc, CDError) else 'failed_before_cutover') from exc
receipt.update(state='cutover_started')
record(path, receipt)
try:
host.switch(before, manifest)
evidence = host.verify(manifest)
except (CDError, OSError, ValueError, KeyError) as exc:
status = 'rollback_failed'
try:
host.rollback(before)
status = 'rolled_back'
except (CDError, OSError, ValueError, KeyError):
pass
receipt.update(state=status, finished_at=stamp(), failure=str(exc) if isinstance(exc, CDError) else 'operation failed')
record(path, receipt)
raise CDError(f'{status}: deployment verification failed') from exc
receipt.update(state='deployed_hifox_pending', deployed_at=stamp(), evidence=evidence)
receipt['hifox'] = {**evidence, 'target': TARGET, 'bundle': request['bundle'], 'deployed_at': receipt['deployed_at'],
'login_url': LOGIN_URL,
'run_url': f'{FORGE}/{REPO}/actions/runs/{request["run_id"]}'}
record(path, receipt)
return writeback(host, request, receipt)
def writeback(host, request, receipt):
try:
task = host.task(request['task'])
check_task(task, request, receipt)
host.callback(request['task'], task, receipt.get('hifox'))
receipt.update(state='published')
record(host.receipt_path, receipt)
except (CDError, OSError, ValueError, KeyError) as exc:
raise CDError('DEPLOYED_HIFOX_PENDING: retry writeback for this receipt') from exc
return receipt
def with_images(config, images):
result = copy.deepcopy(config)
require(set(result['services']) == set(ROLES), 'unexpected Compose service set')
for role in ROLES:
result['services'][role]['image'] = images[role]
return result
def run(argv, purpose, *, cwd=None, input_data=None, timeout=30, allowed=(0,), env=None):
try:
result = subprocess.run(argv, cwd=cwd, input=input_data, capture_output=True, timeout=timeout, env=env)
except (OSError, subprocess.TimeoutExpired) as exc:
raise CDError(f'{purpose} unavailable or timed out') from exc
require(result.returncode in allowed, f'{purpose} failed (exit {result.returncode})')
return result.stdout
class NoRedirect(HTTPRedirectHandler):
def redirect_request(self, *_args, **_kwargs):
raise CDError('unexpected HTTP redirect')
def http(url, *, direct=False, limit=2**20):
handlers = [NoRedirect()]
if direct:
handlers.append(ProxyHandler({}))
try:
with build_opener(*handlers).open(url, timeout=10) as response:
data = response.read(limit + 1)
require(len(data) <= limit, 'HTTP response exceeds limit')
return data
except (URLError, TimeoutError) as exc:
raise CDError('HTTP read failed') from exc
class Assets(HTMLParser):
def __init__(self):
super().__init__()
self.paths = []
def handle_starttag(self, tag, attrs):
attrs = dict(attrs)
path = attrs.get('src' if tag == 'script' else 'href', '')
if path and re.fullmatch(r'/assets/[A-Za-z0-9_.-]+\.(?:js|css)', path):
self.paths.append(path)
def disk_assets(html):
parser = Assets()
parser.feed(html.decode())
require(any(p.endswith('.js') for p in parser.paths), 'web index has no compiled entry point')
return sorted(set(parser.paths))
def image_inspect(image):
return json.loads(run(['docker', 'image', 'inspect', image], 'read image identity'))[0]
def inspect(name):
obj = json.loads(run(['docker', 'container', 'inspect', name], 'read running container'))[0]
require(obj['State']['Status'] == 'running' and matches(IMAGE, obj.get('Image')), 'expected container is not running')
return obj
def image_label(image):
return image_inspect(image)['Config']['Labels'].get(REVISION, '')
def api_identity(container):
raw = run(['docker', 'exec', container, '/app/api', '--version-record-status'], 'read API build identity', allowed=(0, 1))
obj = json.loads(raw)
require(matches(SHA, obj.get('commit_sha')), 'API binary has no full build identity')
return obj['commit_sha']
def migration_files(git, sha):
paths = git('ls-tree', '-r', '--name-only', sha, 'internal/platform/postgres/migrations').decode().splitlines()
return sorted(int(Path(line).name.split('_', 1)[0]) for line in paths if line.endswith('.up.sql'))
def ledger(container):
probe = Path(__file__).with_name('cd_migration_probe.py').read_text()
data = run(['docker', 'exec', container, 'python3', '-c', probe], 'read migration ledger')
result = json.loads(data)
require(isinstance(result, list) and result, 'unexpected migration ledger result')
return result
def verify_archive(archive, expected):
# docker save by ID omits mutable RepoTags. Refuse archives that could retag another app.
with tarfile.open(archive, 'r:') as t:
entry = t.getmember('manifest.json')
require(entry.isfile() and entry.size < 65536, 'unexpected Docker archive manifest')
containers = json.load(t.extractfile(entry))
require(len(containers) == 1 and not containers[0].get('RepoTags'), 'archive must contain one untagged image')
config = t.getmember(containers[0]['Config'])
require(config.isfile() and config.size < 2**20, 'unexpected Docker image config')
require('sha256:' + hashlib.sha256(t.extractfile(config).read()).hexdigest() == expected,
'archive config does not match approved image ID')
for member in t:
require((member.isdir() or member.isfile()) and not member.name.startswith('/')
and '..' not in Path(member.name).parts, 'unexpected Docker archive path')
if 'index.json' in t.getnames():
index = t.getmember('index.json')
require(index.isfile() and index.size < 65536, 'unexpected OCI archive index')
oci = json.load(t.extractfile(index))
require(len(oci.get('manifests', [])) == 1 and all(
key not in descriptor.get('annotations', {}) for descriptor in oci['manifests']
for key in ('org.opencontainers.image.ref.name', 'io.containerd.image.name')),
'archive OCI index contains a mutable name')
descriptor = oci['manifests'][0].get('digest')
require(matches(IMAGE, descriptor), 'invalid OCI image descriptor')
entry = t.getmember('blobs/sha256/' + descriptor[7:])
require(entry.isfile() and entry.size < 2**20, 'unexpected OCI image manifest')
raw = t.extractfile(entry).read()
require('sha256:' + hashlib.sha256(raw).hexdigest() == descriptor, 'OCI manifest digest mismatch')
require(json.loads(raw).get('config', {}).get('digest') == expected, 'OCI config digest mismatch')
return descriptor
return expected
def engine_image(config, descriptor, revision):
# Classic storage uses the config ID. Containerd storage can expose the OCI manifest ID.
for ref in dict.fromkeys((descriptor, config)):
try:
info = image_inspect(ref)
except CDError:
continue
require(info['Id'] in (descriptor, config) and info['Config']['Labels'].get(REVISION) == revision,
'loaded image identity differs from approved archive')
return info['Id']
raise CDError('approved image unavailable by config and manifest digest')
class LiveHost:
def __init__(self, request):
self.receipt_path = DATA / 'receipts' / (request['bundle'] + '.json')
self.compose = APP / 'compose.json'
self.git_path = DATA / 'source.git'
self.containers = {role: 'kg-cloud-' + role for role in ROLES}
self.health_url = 'http://127.0.0.1:8088'
self.request = request
def bundle_path(self, request):
return DATA / 'bundles' / request['bundle']
def git(self, *args):
return run(['git', '-C', str(self.git_path), *args], 'release source check', timeout=90)
def approve(self, request):
repo_url = f'{FORGE}/{REPO}'
run_id = request['run_id']
run_api = f'{FORGE}/api/v1/repos/{REPO}/actions/runs/{run_id}'
dispatch = json.loads(http(run_api))
control_sha = dispatch.get('head_sha')
trigger_actor = dispatch.get('trigger_actor') or dispatch.get('actor') or {}
require(str(dispatch.get('id')) == run_id and dispatch.get('event') == 'workflow_dispatch'
and dispatch.get('path') == 'deploy-production.yml@refs/heads/main'
and dispatch.get('head_branch') == 'main' and dispatch.get('status') in ('in_progress', 'running')
and (dispatch.get('actor') or {}).get('id') == 1 and trigger_actor.get('id') == 1
and matches(SHA, control_sha), 'Gitea run is not an active deployment dispatched by the release owner')
# Repo secrets can be read by other workflows. Only a completed guard from
# the installed workflow and controller may authorize the exact inputs.
try:
self.git('merge-base', '--is-ancestor', control_sha, 'refs/remotes/origin/main')
except CDError:
self.fetch_source()
self.git('merge-base', '--is-ancestor', control_sha, 'refs/remotes/origin/main')
trusted = {'scripts/production_cd.py': Path(__file__).resolve(),
'.gitea/workflows/deploy-production.yml': DATA / 'deploy-production.yml'}
for name, local in trusted.items():
require(self.git('show', f'{control_sha}:{name}') == immutable_file(local).read_bytes(),
'Gitea approval workflow differs from installed control files')
jobs = json.loads(http(run_api + '/jobs')).get('jobs') or []
guards = [job for job in jobs if job.get('name') == 'guard' and job.get('conclusion') == 'success'
and str(job.get('run_id')) == run_id and job.get('head_sha') == control_sha
and matches(re.compile('[1-9][0-9]{0,14}'), str(job.get('id')))]
require(len(guards) == 1, 'Gitea approval guard has not succeeded')
guard_id = guards[0]['id']
verify_guard_log(http(f'{repo_url}/actions/runs/{run_id}/jobs/{guard_id}/logs'), request, control_sha)
def fetch_source(self):
self.git('fetch', '--no-tags', '--prune', f'{FORGE}/{REPO}.git', '+refs/heads/*:refs/remotes/origin/*')
def check_ci(self, request):
self.fetch_source()
refs = self.git('for-each-ref', '--format=%(refname)', '--contains', request['sha'], 'refs/remotes/origin/')
require(refs.strip(), 'candidate commit is not reachable from a repository branch')
contexts = immutable_file(DATA / 'required-contexts.txt').read_text().splitlines()
verify_contexts(json.loads(http(f'{FORGE}/api/v1/repos/{REPO}/commits/{request["sha"]}/status')),
[line.strip() for line in contexts if line.strip() and not line.lstrip().startswith('#')])
def hifox(self, *args):
cli = DATA / 'bin/hifox'
env = {'PATH': '/usr/local/bin:/usr/bin:/bin', 'HOME': str(DATA / 'hifox-home'), 'CI': '1'}
raw = run([str(cli), '--organization-id', ORG, *args, '--output', 'json'], 'HiFox operation', env=env)
result = json.JSONDecoder().raw_decode(raw.decode().strip())[0]
require(isinstance(result, (dict, list)) and (not isinstance(result, dict)
or (result.get('success') is not False and not result.get('error'))),
'HiFox did not return a successful result')
return result
def task(self, task):
return self.hifox('task', 'view', task)
def timeline(self, task):
return self.hifox('api', 'get', f'/rest/v1/tasks/{task}/timeline')
def comment_once(self, task, key, text):
marker = f'KG-CD {key}'
body = f'{text}\n\n`{marker}`'
def present():
return any(row.get('event') == 'commented' and row.get('content') == body
and (row.get('actor') or {}).get('id') == RELEASE_OWNER for row in self.timeline(task))
if not present():
self.hifox('task', 'comment', task, '--body', body)
require(present(), 'HiFox release comment readback mismatch')
def report_failure(self, request):
if not self.receipt_path.exists():
return
receipt = read_json(self.receipt_path)
if any(receipt.get(key) != request[key] for key in ('task', 'sha', 'bundle', 'run_id')):
return
messages = {
'failed_before_cutover': '发布检查失败,未切换主站。',
'rolled_back': '发布核验失败,已恢复原版本并复验。',
'rollback_failed': '发布核验失败,回滚未通过复验,请检查主站。',
'deployed_hifox_pending': '主站已部署并核验,HiFox 回写待完成。请重试回写。',
}
state = receipt['state']
if state in messages:
run_url = f'{FORGE}/{REPO}/actions/runs/{request["run_id"]}'
self.comment_once(request['task'], f'{state} #{request["run_id"]}',
f'{messages[state]}\n\n候选 `{request["sha"]}`\n\n[发布运行]({run_url})')
def callback(self, task_id, task, expected):
if metadata(task, 'cd_release') != expected:
self.hifox('task', 'metadata', 'set', task_id, 'cd_release', json.dumps(json.dumps(expected)))
fresh = self.task(task_id)
check_task(fresh, self.request, {'hifox': expected})
require(metadata(fresh, 'cd_release') == expected, 'HiFox release receipt readback mismatch')
images = '\n'.join(f'- {role} `{expected["images"][role]}`' for role in ROLES)
self.comment_once(task_id, f'published {expected["bundle"]}',
f'云治理主站发布完成,健康检查通过。\n\n'
f'运行版本 `{expected.get("version") or expected["sha"]}`\n\n'
f'提交 `{expected["sha"]}`\n\n{images}\n\n'
f'[登录主站]({LOGIN_URL}) · [发布运行]({expected["run_url"]})')
fresh = self.task(task_id)
check_task(fresh, self.request, {'hifox': expected})
require(metadata(fresh, 'cd_release') == expected, 'HiFox release changed during comment writeback')
if fresh['status']['id'] != PUBLISHED:
self.hifox('task', 'edit', task_id, '--status', PUBLISHED)
final = self.task(task_id)
final_status = (final.get('status') or {}).get('id')
require(final_status == PUBLISHED and metadata(final, 'cd_release') == expected, 'HiFox published readback mismatch')
def compose_cmd(self, *args):
return ['docker', 'compose', '-p', PROJECT, '-f', str(self.compose), *args]
def rendered_config(self):
raw = run(self.compose_cmd('config', '--format', 'json'), 'render Compose configuration', cwd=APP)
return json.loads(raw)['services']
def runtime(self):
rendered = self.rendered_config()
require(set(rendered) == set(ROLES), 'unexpected Compose service set')
result = {}
for role, name in self.containers.items():
c = inspect(name)
labels = c['Config']['Labels']
require(labels.get('com.docker.compose.project') == PROJECT
and labels.get('com.docker.compose.service') == role
and labels.get('com.docker.compose.project.working_dir') == str(APP)
and labels.get('com.docker.compose.project.config_files') == str(self.compose),
f'{role} does not belong to the approved Compose chain')
config = rendered[role]
image = image_inspect(c['Image'])
require(image_inspect(config['image'])['Id'] == c['Image'], f'{role} Compose image has drifted')
env = lambda entries: dict(item.split('=', 1) for item in entries or [])
expected_env = env(image['Config'].get('Env'))
expected_env.update({key: str(value) for key, value in (config.get('environment') or {}).items()
if value is not None})
require(env(c['Config'].get('Env')) == expected_env, f'{role} running environment has drifted')
expected_mounts = config.get('volumes') or []
require(all(mount['type'] == 'bind' for mount in expected_mounts), 'unexpected non-bind Compose volume')
mounts = {(v['Source'], v['Destination'], not v['RW']) for v in c.get('Mounts', []) if v['Type'] == 'bind'}
require(mounts == {(v['source'], v['target'], v.get('read_only', False)) for v in expected_mounts}
and len(mounts) == len(c.get('Mounts', [])), f'{role} running mounts have drifted')
require(not config.get('network_mode') or config['network_mode'] == c['HostConfig']['NetworkMode'],
f'{role} running network has drifted')
result[role] = c['Image']
return result
def baseline(self):
images = self.runtime()
self.probe_web()
return {'compose_sha256': hash_file(self.compose), 'images': images,
'revisions': {role: image_label(image) for role, image in images.items()}}
def pre_switch(self, previous, manifest):
require(hash_file(self.compose) == previous['compose_sha256'] and self.runtime() == previous['images'],
'target baseline changed during deployment')
for revision in set(previous['revisions'].values()):
require(matches(SHA, revision), 'running image has no source revision')
self.git('merge-base', '--is-ancestor', revision, manifest['sha'])
require(migration_files(self.git, manifest['sha']) == manifest['migrations'], 'source migration set differs from bundle')
for role in ('api', 'worker'):
require(ledger(self.containers[role]) == manifest['migrations'],
f'{role} migration ledger mismatch; verify schema changes outside CD')
def load(self, directory, manifest):
archives = {role: directory / (role + '.tar') for role in ROLES}
descriptors = {role: verify_archive(archive, manifest['images'][role]['id'])
for role, archive in archives.items()}
self.loaded_images = {}
for role, archive in archives.items():
image = manifest['images'][role]['id']
run(['docker', 'image', 'load', '-i', str(archive)], f'load {role} image', timeout=600)
self.loaded_images[role] = engine_image(image, descriptors[role], manifest['sha'])
@property
def backup(self):
return self.receipt_path.with_suffix('.compose.backup')
def switch(self, previous, manifest):
current = self.compose.read_bytes()
require(hashlib.sha256(current).hexdigest() == previous['compose_sha256'], 'Compose changed before switch')
images = self.loaded_images
changed = with_images(json.loads(current), images)
for role, image in previous['images'].items():
run(['docker', 'image', 'tag', image, f'knowledge-governance-cd-rollback:{self.request["bundle"]}-{role}'],
'retain rollback image')
atomic_write(self.backup, current)
atomic_write(self.compose, (json.dumps(changed, indent=2) + '\n').encode(), self.compose.stat().st_mode & 0o777)
self.recreate()
def recreate(self):
script = Path(__file__).with_name('deploy-api-web.sh')
run(['bash', str(script), '--verified-compose', str(APP), PROJECT, str(self.compose), 'api', 'web', 'worker'],
'switch governance Compose services', timeout=120)
def probe_web(self):
origin = self.health_url
require(json.loads(http(origin + '/health', direct=True)).get('status') == 'ok', 'web proxy health probe failed')
require(json.loads(http('http://127.0.0.1:18098/readyz', direct=True)).get('status') in ('ok', 'ready'),
'API readiness probe failed')
index = http(origin + '/', direct=True)
return index, {path: hashlib.sha256(http(origin + path, direct=True, limit=32 * 2**20)).hexdigest()
for path in disk_assets(index)}
def verify_web_image(self):
origin_index, assets = self.probe_web()
name = self.containers['web']
def read_asset(path):
return run(['docker', 'exec', name, 'cat', '/usr/share/nginx/html' + path], 'read running web asset')
image_index = read_asset('/index.html')
if origin_index != image_index:
# The main site's SSO proxy strips the crossorigin attribute on same-origin assets.
config = run(['docker', 'exec', name, 'cat', '/etc/nginx/conf.d/default.conf'],
'read active web configuration')
expected = re.sub(rb'(<(?:script|link)\b[^<>]*?) crossorigin(?= (?:src|href)="/assets/)',
rb'\1 ', image_index)
require(b"sub_filter 'crossorigin' '';" in config and origin_index == expected,
'served index differs from running web image')
for path, served_digest in assets.items():
require(hashlib.sha256(read_asset(path)).hexdigest() == served_digest, 'served asset differs from running web image')
return assets
def verify(self, manifest):
images = getattr(self, 'loaded_images', None)
if images is None: # A separate writeback invocation must reconstruct the same identities.
directory = self.bundle_path(self.request)
images = {}
for role, item in manifest['images'].items():
descriptor = verify_archive(directory / (role + '.tar'), item['id'])
images[role] = engine_image(item['id'], descriptor, manifest['sha'])
def check():
require(self.runtime() == images, 'running image IDs differ from approved bundle')
require(api_identity(self.containers['api']) == manifest['sha'], 'running API SHA mismatches approval')
assets = self.verify_web_image()
version = image_inspect(images['api'])['Config']['Labels'].get('org.opencontainers.image.version')
if not isinstance(version, str) or not re.fullmatch(r'[0-9A-Za-z.+_-]{1,128}', version):
version = manifest['sha']
return {'sha': manifest['sha'], 'version': version, 'images': images, 'health': 'ok', 'asset_sha256': assets}
return wait_ready(check)
def rollback(self, previous):
if not self.backup.exists():
require(hash_file(self.compose) == previous['compose_sha256'] and self.runtime() == previous['images'],
'rollback baseline cannot be established')
self.verify_web_image()
return
original = self.backup.read_bytes()
require(hashlib.sha256(original).hexdigest() == previous['compose_sha256'], 'rollback backup checksum mismatch')
source = json.loads(original)
for role, image in previous['images'].items():
reference = source['services'][role]['image']
require(image_inspect(reference)['Id'] == image, 'rollback source tag has drifted')
atomic_write(self.compose, original, self.compose.stat().st_mode & 0o777)
self.recreate()
def check():
require(self.runtime() == previous['images'], 'rollback running images mismatch')
require(api_identity(self.containers['api']) == previous['revisions']['api'], 'rollback API SHA mismatch')
self.verify_web_image()
wait_ready(check)
def wait_ready(check, seconds=90):
deadline = time.monotonic() + seconds
while True:
try:
return check()
except (CDError, OSError, KeyError, ValueError):
if time.monotonic() >= deadline:
raise
time.sleep(3)
def event_request(event, env):
require(env.get('GITHUB_EVENT_NAME') == 'workflow_dispatch' and env.get('GITHUB_REF') == 'refs/heads/main'
and env.get('GITHUB_REPOSITORY') == REPO, 'manual dispatch from main required')
inputs = event.get('inputs') or {}
request = {name: inputs.get(name) or '' for name in
('action', 'sha', 'task', 'bundle', 'confirm', 'approval_event', 'acceptance_digest')}
request['run_id'] = env.get('GITHUB_RUN_ID', '')
validate_request(request)
return request
def pack(args):
require(matches(SHA, args.sha) and matches(UUID, args.task), 'require full SHA and task UUID')
require(not args.output.exists(), 'bundle output already exists')
source = lambda *argv: run(['git', *argv], 'read candidate source')
require(source('rev-parse', args.sha + '^{commit}').decode().strip() == args.sha, 'source commit not found')
images = {}
versions = migration_files(source, args.sha)
manifest = dict(schema=1, target=TARGET, sha=args.sha, task=args.task, images=images, migrations=versions)
with tempfile.TemporaryDirectory(dir=args.output.parent) as directory:
build = Path(directory) / "sealed"
build.mkdir(mode=0o700)
for role in ROLES:
image = image_inspect(getattr(args, role).removeprefix('sha256:'))
image_id = image['Id']
require(matches(IMAGE, image_id) and image_label(image_id) == args.sha, f'{role} source label mismatch')
archive = build / (role + '.tar')
run(['docker', 'image', 'save', '-o', str(archive), image_id], f'archive {role} image', timeout=900)
verify_archive(archive, image_id)
archive.chmod(0o600)
images[role] = {'id': image_id, 'sha256': hash_file(archive)}
record(build / 'release.json', manifest)
for item in build.iterdir():
with item.open("rb") as artifact:
os.fsync(artifact.fileno())
sync_dir(build)
build.rename(args.output)
sync_dir(args.output.parent)
print(hash_file(args.output / 'release.json'))
def attest(args):
request = {'sha': args.sha, 'task': args.task, 'bundle': hash_file(args.directory / 'release.json')}
require(matches(SHA, args.sha) and matches(UUID, args.task), 'require full SHA and task UUID')
manifest = verify_bundle(args.directory, request)
before = {role: inspect(getattr(args, role)) for role in ROLES}
for role, obj in before.items():
require(obj['Image'] == manifest['images'][role]['id'] and obj['Name'] != '/kg-cloud-' + role,
'isolated test runtime image differs from bundle')
require(api_identity(args.api) == args.sha and ledger(args.api) == manifest['migrations']
and ledger(args.worker) == manifest['migrations'], 'test runtime SHA or schema differs')
base = urlsplit(args.test_url)
require(base.scheme in ('http', 'https') and base.hostname and not (base.username or base.password or base.query or base.fragment)
and base.path in ('', '/') and base.port != 8088, 'provide isolated test endpoint')
origin = args.test_url.rstrip('/')
require(json.loads(http(origin + '/health', direct=True)).get('status') == 'ok', 'isolated test health probe failed')
index = http(origin + '/', direct=True)
require(index == run(['docker', 'exec', args.web, 'cat', '/usr/share/nginx/html/index.html'], 'read test web index'),
'test endpoint is serving another web image')
for role, obj in before.items():
require(inspect(getattr(args, role))['Id'] == obj['Id'], 'test instance changed during readback')
print(json.dumps({'sha': args.sha, 'bundle': request['bundle'], 'test_url': args.test_url,
'images': {role: obj['Image'] for role, obj in before.items()}}, sort_keys=True))
def cli():
parser = argparse.ArgumentParser(description=__doc__)
commands = parser.add_subparsers(dest='command', required=True)
for command in ('guard', 'send', 'serve', 'pack', 'attest'):
sub = commands.add_parser(command)
if command in ('guard', 'send'):
sub.add_argument('--event', type=Path, required=True)
if command in ('pack', 'attest'):
sub.add_argument('--sha', required=True)
sub.add_argument('--task', required=True)
if command in ('pack', 'attest'):
for role in ROLES:
sub.add_argument('--' + role, required=True)
if command == 'pack':
sub.add_argument('--output', type=Path, required=True)
if command == 'attest':
sub.add_argument('--directory', type=Path, required=True)
sub.add_argument('--test-url', required=True)
args = parser.parse_args()
if args.command in ('guard', 'send'):
request = event_request(read_json(args.event), os.environ)
if args.command == 'guard':
print(guard_proof(request, os.environ.get('GITHUB_SHA')))
else:
send(request)
elif args.command == 'pack':
pack(args)
elif args.command == 'attest':
attest(args)
else:
raw = sys.stdin.buffer.read(8193)
require(len(raw) <= 8192, 'request exceeds size limit')
request = json.loads(raw)
validate_request(request)
with deploy_lock(DATA / 'release.lock'):
host = LiveHost(request)
for item in (DATA / 'receipts').glob('*.json'):
if read_json(item)['state'] in ('cutover_started', 'rollback_failed'):
raise CDError('previous deployment outcome requires operator reconciliation')
try:
result = release(host, request)
except (CDError, OSError, ValueError, KeyError):
try:
host.report_failure(request)
except (CDError, OSError, ValueError, KeyError):
print('CD: HiFox failure comment pending', file=sys.stderr)
raise
print(json.dumps({k: result[k] for k in ('state', 'sha', 'task', 'bundle', 'hifox')}, ensure_ascii=False))
def send(request):
key = os.environ.get('KG_CD_SSH_KEY', '')
known_hosts = os.environ.get('KG_CD_KNOWN_HOSTS', '')
host = os.environ.get('KG_CD_SSH_HOST', '')
port = os.environ.get('KG_CD_SSH_PORT', '22') or '22'
require(key.strip() and known_hosts.strip(), 'missing KG_CD_SSH_KEY or KG_CD_KNOWN_HOSTS')
require(host in ('100.85.111.121', '::1') and port.isdecimal() and 1 <= int(port) <= 65535,
'configure the direct or approved tunnel address for the target release endpoint')
with tempfile.TemporaryDirectory() as directory:
temp = Path(directory)
for filename, value in (('key', key), ('known_hosts', known_hosts)):
atomic_write(temp / filename, (value.strip() + '\n').encode())
argv = ['ssh', '-F', '/dev/null', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=10', '-o', 'IdentitiesOnly=yes',
'-o', 'ClearAllForwardings=yes', '-o', 'StrictHostKeyChecking=yes', '-o', 'HostKeyAlias=kg-governance-cd',
'-o', 'GlobalKnownHostsFile=/dev/null', '-o', f'UserKnownHostsFile={temp / "known_hosts"}',
'-i', str(temp / 'key'), '-p', port, '-T', 'root@' + host, 'kg-cd-v1']
try:
result = subprocess.run(argv, input=json.dumps(request).encode(), capture_output=True, timeout=2100)
except (OSError, subprocess.TimeoutExpired) as exc:
raise CDError('target outcome unknown; inspect durable receipt before retry') from exc
if result.returncode:
error = result.stderr.decode(errors='replace')
for marker in ('DEPLOYED_HIFOX_PENDING', 'rollback_failed:', 'rolled_back:', 'failed_before_cutover:',
'target preflight rejected', 'deployment lock busy', 'writeback requires a verified deployment receipt',
'Gitea approval guard has not succeeded', 'Gitea guard dispatch proof missing or different'):
if marker in error:
raise CDError(error.strip().splitlines()[-1])
raise CDError('target rejected request or outcome unknown; inspect durable receipt')
response = json.loads(result.stdout)
require(response.get('state') == 'published' and all(response.get(k) == request[k] for k in ('sha', 'task', 'bundle')),
'invalid or unverified deployment receipt')
print(json.dumps(response, ensure_ascii=False))
if __name__ == '__main__':
try:
cli()
except CDError as error:
print(f'CD: {error}', file=sys.stderr)
sys.exit(1)
except (OSError, KeyError, ValueError, TypeError, tarfile.TarError) as error:
print(f'CD: operation could not be verified ({type(error).__name__})', file=sys.stderr)
sys.exit(1)
+374
View File
@@ -0,0 +1,374 @@
#!/usr/bin/env python3
"""Prepare and exercise an isolated Knowledge Governance QA run."""
import argparse
from contextlib import ExitStack
import fcntl
import http.client
import json
import os
from pathlib import Path
import re
import shutil
import signal
import socket
import stat
import subprocess
import sys
import tempfile
import time
ROOT = Path(__file__).resolve().parents[1]
CONFIG = Path.home() / '.config/knowledge-governance/qa.json'
API_PORT = 8088
WEB_PORT = 5173
RUNTIME_RESPONSE = 'KG_QA_RUNTIME_OK'
class QAError(RuntimeError):
pass
def report(stage, detail):
print(f'[qa:{stage}] {detail}', flush=True)
def capture(argv, stage, timeout=10, env=None):
try:
return subprocess.run(argv, cwd=ROOT, env=env, text=True, capture_output=True,
timeout=timeout, stdin=subprocess.DEVNULL)
except FileNotFoundError as exc:
raise QAError(f'{stage} 缺少命令 {argv[0]}') from exc
except subprocess.TimeoutExpired as exc:
raise QAError(f'{stage} 超过 {timeout} 秒') from exc
def private_file(path):
try:
info = path.lstat()
except FileNotFoundError as exc:
raise QAError(f'缺少测试配置文件 {path}') from exc
if not stat.S_ISREG(info.st_mode) or info.st_uid != os.getuid() or stat.S_IMODE(info.st_mode) != 0o600:
raise QAError(f'{path} 必须是当前用户所有的 0600 普通文件')
def database_config(path):
private_file(path)
try:
config = json.loads(path.read_text())
except (UnicodeError, json.JSONDecodeError) as exc:
raise QAError(f'{path} 不是有效 JSON') from exc
if not isinstance(config, dict) or config.keys() != {'host', 'port', 'database', 'user'}:
raise QAError('qa.json 只接受 host、port、database、user 四个字段')
for field in ('database', 'user'):
if not re.fullmatch(r'kg_qa_[a-z0-9_]{1,56}', str(config[field])):
raise QAError(f'RDS {field} 必须以 kg_qa_ 开头并使用小写字母、数字或下划线')
host = config['host']
if not isinstance(host, str) or not re.fullmatch(r'[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+', host):
raise QAError('RDS host 必须填写证书对应的 DNS 主机名')
if type(config['port']) is not int or not 1 <= config['port'] <= 65535:
raise QAError('RDS port 必须是 1–65535 的整数')
return config
def tool_env():
allowed = ('HOME', 'PATH', 'LANG', 'TMPDIR', 'GOPROXY', 'GOSUMDB', 'GOPRIVATE', 'GONOSUMDB',
'GOMODCACHE', 'GOCACHE', 'npm_config_cache', 'npm_config_registry',
'HTTP_PROXY', 'HTTPS_PROXY', 'ALL_PROXY', 'NO_PROXY',
'http_proxy', 'https_proxy', 'all_proxy', 'no_proxy')
env = {key: os.environ[key] for key in allowed if key in os.environ}
env['GOFLAGS'] = '-mod=readonly'
return env
def database_env(config, directory):
# Keep inherited PG variables and integration switches out of application children.
env = tool_env()
env.update(PGHOST=config['host'], PGPORT=str(config['port']), PGDATABASE=config['database'],
PGUSER=config['user'], PGSSLMODE='verify-full', PGCONNECT_TIMEOUT='5',
PGPASSFILE=str(directory / 'qa.pgpass'), PGSSLROOTCERT=str(directory / 'rds-ca.pem'),
PGOPTIONS='-c search_path=public', LC_ALL='C',
TEST_WEKNORA_ENABLED='false', PP_SCAN_ENABLED='false',
RELEASE_WORKER_ENABLED='false', PRODUCTION_RELEASE_REQUESTS_ENABLED='false',
DOBOTAI_OPS_READ_ENABLED='false', DOBOTAI_OPS_DIRECTORY_SYNC_ENABLED='false')
env['APP_ADDR'] = f'127.0.0.1:{API_PORT}'
env['DATA' + 'BASE_URL'] = (
f"postgresql://{config['user']}@{config['host']}:{config['port']}/{config['database']}"
'?sslmode=verify-full&connect_timeout=5&search_path=public'
)
return env
def psql(env, sql):
result = capture(['psql', '-XAtw', '-v', 'ON_ERROR_STOP=1', '-c', sql], 'RDS 探针', env=env)
if result.returncode == 0:
return result.stdout.strip()
detail = result.stderr.lower()
hints = (
('password', '口令认证失败,检查 qa.pgpass 和登录角色'),
('certificate', 'TLS 校验失败,检查 RDS 主机名和 CA'),
('does not exist', '数据库或角色不存在,联系管理员确认专用 QA 库'),
('permission denied', 'RDS 权限不足,检查专用 QA 角色的 CONNECT、schema USAGE/CREATE 权限'),
('could not translate host name', 'RDS 主机名无法解析,检查私网 DNS'),
('timeout', '连接 RDS 超时,检查 QA 虚拟机到 RDS 的私网和安全组'),
('connection refused', 'RDS 拒绝 TCP 连接,检查主机名、端口和私网接入'),
)
hint = next((message for marker, message in hints if marker in detail), '连接或 SQL 探针失败,检查 RDS 接入和权限')
raise QAError(f'RDS {hint}(psql 退出 {result.returncode})')
def database_state(env):
identity = psql(env, """
SELECT concat_ws('|', current_database(), current_user,
COALESCE((SELECT ssl FROM pg_stat_ssl WHERE pid = pg_backend_pid()), false),
(SELECT NOT (rolsuper OR rolcreaterole OR rolcreatedb OR rolreplication OR rolbypassrls)
FROM pg_roles WHERE rolname = current_user),
(has_schema_privilege(current_user, 'public', 'USAGE') AND
has_schema_privilege(current_user, 'public', 'CREATE')),
to_regclass('public.schema_migrations') IS NOT NULL,
EXISTS (SELECT FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace
WHERE n.nspname = 'public' AND c.relname <> 'schema_migrations')
OR EXISTS (SELECT FROM pg_namespace
WHERE nspname NOT IN ('public', 'information_schema') AND nspname !~ '^pg_')
OR EXISTS (SELECT FROM pg_proc p JOIN pg_namespace n ON n.oid=p.pronamespace
WHERE n.nspname = 'public'));
""")
fields = identity.split('|')
if len(fields) != 7 or fields[:4] != [env['PGDATABASE'], env['PGUSER'], 't', 't']:
raise QAError('RDS 实际库名、角色、TLS 或角色权限与 QA 配置不符')
if fields[4] != 't':
raise QAError('RDS 角色需要 public schema 的 USAGE 和 CREATE 权限')
rows = psql(env, 'SELECT version FROM public.schema_migrations ORDER BY version;') if fields[5] == 't' else ''
if any(not re.fullmatch(r'[0-9]+', row) for row in rows.splitlines()):
raise QAError('RDS 迁移记录包含无效版本')
return [int(row) for row in rows.splitlines()], fields[6] == 't'
def expected_migrations():
paths = (ROOT / 'internal/platform/postgres/migrations').glob('*.up.sql')
try:
versions = sorted(int(path.name.split('_', 1)[0]) for path in paths)
except ValueError as exc:
raise QAError('仓库存在无效的迁移文件名') from exc
if not versions or len(versions) != len(set(versions)):
raise QAError('仓库迁移文件缺失或版本重复')
return versions
def check_migrations(expected, applied, nonempty, *, complete):
if not applied and nonempty:
raise QAError('RDS 非空且缺少有效迁移记录,停止初始化')
if expected[:len(applied)] != applied:
raise QAError('RDS 迁移序列与当前提交不兼容,使用专用空库或匹配的测试库')
if complete and applied != expected:
raise QAError(f'RDS 迁移未完成,缺少版本 {expected[len(applied)]} 至 {expected[-1]}')
def check_hifox(output):
try:
state = json.loads(output)
online = state['connected'] is True and state['remoteLiveness']['status'] == 'online'
except (ValueError, KeyError, TypeError) as exc:
raise QAError('HiFox 未返回有效的在线状态,检查本机注册和接收服务') from exc
if not online:
raise QAError('HiFox 未确认测试机在线,检查本机接收服务和网络')
def check_checkout(expected):
if not re.fullmatch(r'[0-9a-f]{40}', expected):
raise QAError('设置 KG_QA_SHA 为提测的完整 40 位 Git SHA')
actual = capture(['git', 'rev-parse', 'HEAD'], 'Git 检出')
if actual.returncode or actual.stdout.strip() != expected:
raise QAError('Git 检出与提测提交不一致')
state = capture(['git', 'status', '--porcelain'], 'Git 状态')
if state.returncode or state.stdout.strip():
raise QAError('QA 需要干净的独立检出,请检查 Git 状态')
def preflight(env):
for cmd in ('git', 'make', 'go', 'node', 'npm', 'psql', 'hifox', 'omp'):
if not shutil.which(cmd, path=env.get('PATH')):
raise QAError(f'工具链缺少 {cmd},检查 QA 机器的 PATH')
go = capture(['go', 'env', 'GOROOT', 'GOVERSION'], 'Go 工具链', env=env)
fields = go.stdout.splitlines()
if go.returncode or len(fields) != 2 or not fields[1].startswith('go1.26.'):
raise QAError('QA 需要 Go 1.26 工具链')
root = Path(fields[0]) / 'bin'
if not os.access(root / 'gofmt', os.X_OK):
raise QAError('Go 工具链缺少 gofmt,请安装完整的 Go 1.26')
env['PATH'] = f"{root}:{env['PATH']}"
node = capture(['node', '--version'], 'Node.js 工具链', env=env)
if node.returncode or not node.stdout.startswith('v22.'):
raise QAError('QA 需要 Node.js 22 工具链')
report('toolchain', f'{fields[1]} / Node.js {node.stdout.strip()}')
hifox = capture(['hifox', 'computer', 'status', '--output', 'json'], 'HiFox 在线检查', timeout=15)
if hifox.returncode:
raise QAError(f'HiFox 状态命令失败(退出 {hifox.returncode})')
check_hifox(hifox.stdout)
report('machine', f'{socket.gethostname()} / HiFox online')
prompt = f'Reply with exactly {RUNTIME_RESPONSE}. Do not use tools.'
omp = capture(['omp', '--no-session', '-p', prompt], 'OMP Runtime 探针', timeout=35)
if omp.returncode or RUNTIME_RESPONSE not in {line.strip() for line in omp.stdout.splitlines()}:
raise QAError('OMP Runtime 没有返回探针结果,检查 OMP 模型配置和 Magpie 网关')
report('runtime', 'OMP 模型请求通过')
def check_ports():
for port in (API_PORT, WEB_PORT):
with socket.socket() as listener:
listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
listener.bind(('127.0.0.1', port))
except OSError as exc:
raise QAError(f'QA 端口 {port} 无法绑定,检查已有监听进程') from exc
def run_step(argv, stage, env, timeout):
report(stage, ' '.join(argv[:2]))
process = subprocess.Popen(argv, cwd=ROOT, env=env, stdin=subprocess.DEVNULL, start_new_session=True)
try:
code = process.wait(timeout=timeout)
except subprocess.TimeoutExpired as exc:
raise QAError(f'{stage} 超过 {timeout} 秒') from exc
finally:
stop_process(process)
if code:
raise QAError(f'{stage} 失败(退出 {code}),查看上方命令输出')
def stop_process(process):
try:
os.killpg(process.pid, signal.SIGTERM)
except ProcessLookupError:
pass
try:
process.wait(timeout=5)
except subprocess.TimeoutExpired:
try:
os.killpg(process.pid, signal.SIGKILL)
except ProcessLookupError:
pass
process.wait(timeout=5)
def start_service(stack, argv, env, log):
output = stack.enter_context(log.open('w', encoding='utf-8'))
process = subprocess.Popen(argv, cwd=ROOT, env=env, stdin=subprocess.DEVNULL,
stdout=output, stderr=subprocess.STDOUT, start_new_session=True)
stack.callback(stop_process, process)
return process
def request(port, path):
connection = http.client.HTTPConnection('127.0.0.1', port, timeout=2)
try:
connection.request('GET', path)
response = connection.getresponse()
return response.status, response.getheader('Content-Type', ''), response.read(32768)
finally:
connection.close()
def probe(port, path, expected):
try:
code, content_type, body = request(port, path)
if code != 200:
return False
if expected == 'html':
return 'text/html' in content_type and b'id="root"' in body
return 'application/json' in content_type and json.loads(body)['status'] == expected
except (OSError, http.client.HTTPException, ValueError, KeyError, TypeError):
return False
def wait_service(process, port, path, expected, log):
deadline = time.monotonic() + 45
while time.monotonic() < deadline:
if process.poll() is not None:
raise QAError(f'服务端口 {port} 启动进程提前退出(退出 {process.returncode}),日志 {log}')
if probe(port, path, expected):
return
time.sleep(0.25)
raise QAError(f'服务探针超时 127.0.0.1:{port}{path},日志 {log}')
def qa_run(commit, env, db_env, versions, state):
with tempfile.TemporaryDirectory(prefix='run-', dir=state) as directory, ExitStack() as services:
binary = Path(directory) / 'api'
run_step(['make', 'deps-install'], 'deps', env, 300)
ldflags = f'-X knowledge-governance/internal/version.CommitSHA={commit}'
run_step(['go', 'build', '-ldflags', ldflags, '-o', str(binary), './cmd/api'], 'build-api', env, 300)
check_ports()
log_dir = Path(tempfile.mkdtemp(prefix=f'{commit[:12]}-', dir=state))
report('logs', str(log_dir))
app_env = db_env | {'PATH': env['PATH'], 'GOVERNANCE_SPOOL_ROOT': str(Path(directory) / 'spool')}
api_log = log_dir / 'api.log'
api = start_service(services, [str(binary)], app_env, api_log)
wait_service(api, API_PORT, '/readyz', 'ready', api_log)
check_migrations(versions, *database_state(db_env), complete=True)
report('migration', f'已核对全部 {len(versions)} 条迁移,最新版本 {versions[-1]}')
web_log = log_dir / 'web.log'
web = start_service(services, ['npm', '--prefix', 'web', 'run', 'dev', '--', '--host', '127.0.0.1',
'--port', str(WEB_PORT), '--strictPort'], env, web_log)
wait_service(web, WEB_PORT, '/', 'html', web_log)
wait_service(web, WEB_PORT, '/health', 'ok', web_log)
report('services', 'API /readyz、Web 首页与 Vite /health 代理通过')
run_step(['make', 'tests-go', 'tests-web'], 'tests', env, 300)
check_checkout(commit)
if api.poll() is not None or web.poll() is not None or not probe(WEB_PORT, '/health', 'ok'):
raise QAError(f'服务在测试期间失去健康状态,日志目录 {log_dir}')
report('result', f'PASS {commit},已停止本次 API 和 Web 进程')
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('action', choices=('doctor', 'run'))
args = parser.parse_args()
env = tool_env()
try:
commit = os.environ.get('KG_QA_SHA', '')
if args.action == 'run':
check_checkout(commit)
check_ports()
preflight(env)
config_path = Path(os.environ.get('KG_QA_CONFIG', CONFIG)).expanduser().absolute()
config = database_config(config_path)
private_file(config_path.parent / 'qa.pgpass')
if not (config_path.parent / 'rds-ca.pem').is_file():
raise QAError(f'缺少 RDS CA 文件 {config_path.parent / "rds-ca.pem"}')
db_env = database_env(config, config_path.parent)
versions = expected_migrations()
if args.action == 'doctor':
applied, nonempty = database_state(db_env)
check_migrations(versions, applied, nonempty, complete=False)
report('database', f'连接与身份正常,已应用 {len(applied)}/{len(versions)} 条迁移')
return 0
state = Path.home() / '.local/state/knowledge-governance/qa'
state.mkdir(mode=0o700, parents=True, exist_ok=True)
with (state / 'run.lock').open('a') as lock:
try:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError as exc:
raise QAError('本机已有 QA 任务,等待当前任务退出') from exc
check_ports()
check_migrations(versions, *database_state(db_env), complete=False)
qa_run(commit, env, db_env, versions, state)
return 0
except (QAError, OSError, ValueError) as exc:
print(f'[qa:FAIL] {exc}', file=sys.stderr)
return 1
except KeyboardInterrupt:
print('[qa:FAIL] QA 任务中断', file=sys.stderr)
return 130
if __name__ == '__main__':
def interrupt(_signal, _frame):
raise KeyboardInterrupt
signal.signal(signal.SIGTERM, interrupt)
sys.exit(main())
+119
View File
@@ -0,0 +1,119 @@
from pathlib import Path
import subprocess
import tempfile
import unittest
from types import SimpleNamespace
from unittest.mock import patch
import candidate_release as candidate
import candidate_runtime as runtime
import production_cd as cd
BASE, A, B, OTHER = [c * 40 for c in 'abcd']
TASK, QA1, QA2, OWNER = [f'{n:08d}-1111-2222-3333-444444444444' for n in range(1, 5)]
RUN = {'sha': B, 'bundle': 'e' * 64, 'ready_at': '2026-11-01T10:00:00Z', 'url': 'http://127.0.0.1:39191'}
class CandidateReleaseTest(unittest.TestCase):
def setUp(self):
self.plan = {'task': TASK, 'sha': B, 'base': BASE,
'items': [{'task': QA1, 'pr': 20}, {'task': QA2, 'pr': 21}],
'extra': []}
self.prs = {n: {'merged': True, 'base': {'ref': 'main'}, 'merge_commit_sha': sha}
for n, sha in ((20, A), (21, B))}
self.report = {'actor': {'id': OWNER}, 'createdAt': '2026-11-01T11:00:00Z', 'id': OWNER}
def test_scope_accounts_for_entire_main_range(self):
candidate.check_scope(self.plan, self.prs.__getitem__, [A, B])
with self.assertRaisesRegex(cd.CDError, 'outside the release scope'):
candidate.check_scope(self.plan, self.prs.__getitem__, [A, OTHER, B])
def test_pr_must_be_merged_on_main_and_match_range(self):
self.prs[20]['base']['ref'] = 'test'
with self.assertRaisesRegex(cd.CDError, 'merged into main'):
candidate.check_scope(self.plan, self.prs.__getitem__, [A, B])
def test_merged_runtime_baseline_requires_full_main_scope(self):
with tempfile.TemporaryDirectory() as tmp:
repo = Path(tmp)
def git(*args):
return subprocess.check_output(['git', *args], cwd=repo, text=True).strip()
git('init', '-q')
git('config', 'user.name', 'Test')
git('config', 'user.email', 'test@example.invalid')
tree = git('hash-object', '-w', '-t', 'tree', '/dev/null')
def commit(message, *parents):
return git('commit-tree', tree, '-m', message, *(part for p in parents for part in ('-p', p)))
root = commit('root')
live = commit('running baseline', root)
control = commit('control plane', root)
integration = commit('bring the running version into main', control, live)
landed = commit('land business PR', integration)
git('update-ref', 'refs/remotes/origin/main', landed)
plan = dict(self.plan, base=live, sha=landed, items=[{'task': QA1, 'pr': 20}],
extra=[control, integration])
pr = dict(self.prs[20], merge_commit_sha=landed)
with patch.object(candidate, 'read_forge', return_value=pr), patch.object(cd, 'verify_contexts'):
candidate.verify_source(plan, repo)
with self.assertRaisesRegex(cd.CDError, 'outside the release scope'):
candidate.verify_source(dict(plan, extra=[integration]), repo)
unrelated = commit('unmerged branch', root)
with self.assertRaisesRegex(cd.CDError, 'baseline must be an ancestor'):
candidate.verify_source(dict(plan, base=unrelated), repo)
with self.assertRaisesRegex(cd.CDError, 'candidate must be on main'):
candidate.verify_source(dict(plan, base=root, sha=live), repo)
def test_candidate_selects_only_the_configured_qa_password(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
config = root / 'qa.json'
pgpass = root / 'qa.pgpass'
cert = root / 'rds-ca.pem'
for path in (config, pgpass, cert):
path.touch(mode=0o600)
config.write_text('{"host":"kg-qa-rds.test","port":15483,"database":"kg_qa_app","user":"kg_qa_app"}')
application = 'kg-qa-rds.test:15483:kg_qa_app:kg_qa_app:app\\:example'
integration = 'kg-qa-rds.test:15483:kg_qa_it:kg_qa_it:it-example'
pgpass.write_text(f'{integration}\n{application}\n')
url, ca = runtime.qa_database(config)
self.assertEqual(ca, cert)
self.assertIn('app%3Aexample@kg-qa-rds.test:15483/kg_qa_app', url)
for rows in ((integration,), (application, application), (application, '*:15483:*:*:example'),
(application, 'kg-qa-rds.test:15483:governance:governance:example')):
pgpass.write_text('\n'.join(rows))
with self.subTest(rows=rows), self.assertRaises(cd.CDError):
runtime.qa_database(config)
def test_require_all_qa_reports_and_shared_regression(self):
sources = {QA1: (self.report, self.result()), QA2: (self.report, self.result())}
with self.assertRaisesRegex(cd.CDError, 'every requirement and the release task'):
candidate.check_qa(self.plan, RUN, sources, {OWNER})
sources[TASK] = (self.report, self.result())
candidate.check_qa(self.plan, RUN, sources, {OWNER})
def test_same_candidate_and_author_required(self):
for result, author, reason in ((self.result(sha=OTHER), OWNER, 'different candidate'),
(self.result(bundle='0' * 64), OWNER, 'different candidate'),
(self.result(), QA1, 'authorized QA'),
(self.result(failed=1), OWNER, 'not passed')):
sources = {QA1: (dict(self.report, actor={'id': author}), result),
QA2: (self.report, self.result()), TASK: (self.report, self.result())}
with self.subTest(reason=reason), self.assertRaisesRegex(cd.CDError, reason):
candidate.check_qa(self.plan, RUN, sources, {OWNER})
def test_preparation_rejected_from_review_branch(self):
import json
event = {'inputs': {'mode': 'prepare', 'plan': json.dumps(self.plan)}}
env = {'GITHUB_EVENT_NAME': 'workflow_dispatch', 'GITHUB_REPOSITORY': cd.REPO,
'GITHUB_REF': 'refs/heads/feat/candidate-release-batch'}
with self.assertRaisesRegex(cd.CDError, 'workflow from main'):
candidate.event_plan(event, env)
event['inputs']['mode'] = 'verify'
self.assertEqual(candidate.event_plan(event, env), (self.plan, 'verify'))
def result(self, **extra):
return {**RUN, 'verdict': 'passed', 'required': 2, 'passed': 2, 'failed': 0, 'blocked': 0, **extra}
+264
View File
@@ -0,0 +1,264 @@
import hashlib
import json
import tempfile
import unittest
from pathlib import Path
from unittest.mock import Mock, patch
import production_cd as cd
import hifox_release_trigger as trigger
SHA = 'a' * 40
TASK = 'd5abdf29-d0b5-4992-8073-0cb8fffd84ed'
IMAGES = {role: 'sha256:' + str(i) * 64 for i, role in enumerate(('api', 'web', 'worker'), 1)}
CTX = 'build / build (push)'
class ProductionCD(unittest.TestCase):
def setUp(self):
temp = tempfile.TemporaryDirectory()
self.addCleanup(temp.cleanup)
self.root = Path(temp.name)
self.request = dict(sha=SHA, task=TASK, bundle='b' * 64, confirm='deploy-production',
action='deploy', run_id='42')
self.manifest = dict(schema=1, target=cd.TARGET, sha=SHA, task=TASK, migrations=[1, 2], images={})
for role, image in IMAGES.items():
archive = self.root / (role + '.tar')
archive.write_text(role)
self.manifest['images'][role] = dict(id=image, sha256=hashlib.sha256(role.encode()).hexdigest())
data = json.dumps(self.manifest).encode()
(self.root / 'release.json').write_bytes(data)
for path in self.root.iterdir():
path.chmod(0o600)
self.request['bundle'] = hashlib.sha256(data).hexdigest()
self.acceptance = {'verdict': 'passed', 'sha': SHA, 'bundle': self.request['bundle'],
'evidence': 'https://example.test/result/42'}
self.host = Mock()
self.host.task.return_value = {'id': TASK, 'spaceId': cd.SPACE, 'status': {'id': cd.READY},
'metadata': {'cd_acceptance': json.dumps(self.acceptance)}}
self.host.baseline.return_value = {'before': 'baseline'}
self.host.pre_switch.return_value = None
self.host.verify.return_value = {'sha': SHA, 'images': IMAGES, 'health': 'ok'}
self.host.receipt_path = self.root / 'receipt.json'
self.host.bundle_path.return_value = self.root
def execute(self):
return cd.release(self.host, self.request)
def assert_no_deploy(self):
self.host.load.assert_not_called()
self.host.switch.assert_not_called()
self.host.callback.assert_not_called()
def test_archive_binds_engine_descriptor_to_approved_config(self):
import io
import tarfile
config = b'{"architecture":"amd64"}'
digest = lambda raw: 'sha256:' + hashlib.sha256(raw).hexdigest()
expected = digest(config)
for target in (expected, 'sha256:' + '0' * 64):
blob = json.dumps({'schemaVersion': 2, 'config': {'digest': target}}).encode()
manifest_id = digest(blob)
archive = self.root / 'identity.tar'
files = {'manifest.json': json.dumps([{'Config': 'config.json'}]).encode(), 'config.json': config,
'index.json': json.dumps({'manifests': [{'digest': manifest_id}]}).encode(),
'blobs/sha256/' + manifest_id[7:]: blob}
with tarfile.open(archive, 'w') as tar:
for name, raw in files.items():
entry = tarfile.TarInfo(name)
entry.size = len(raw)
tar.addfile(entry, io.BytesIO(raw))
if target == expected:
self.assertEqual(cd.verify_archive(archive, expected), manifest_id)
else:
with self.assertRaisesRegex(cd.CDError, 'config digest'):
cd.verify_archive(archive, expected)
def test_no_confirmation_has_zero_side_effects(self):
self.request['confirm'] = ''
with self.assertRaisesRegex(cd.CDError, 'confirmation'):
self.execute()
self.host.assert_not_called()
self.assert_no_deploy()
def test_preconditions_prevent_loading_and_switching(self):
for mode in ('approval', 'ci', 'test', 'changed_bundle', 'tampered_archive', 'migration'):
with self.subTest(mode=mode):
self.setUp()
if mode in ('approval', 'ci', 'migration'):
step = {'approval': self.host.approve, 'ci': self.host.check_ci,
'migration': self.host.pre_switch}[mode]
step.side_effect = cd.CDError(mode)
elif mode == 'test':
self.host.task.return_value['metadata'].clear()
elif mode == 'changed_bundle':
self.request['bundle'] = 'f' * 64
else:
(self.root / 'web.tar').write_bytes(b'other image')
with self.assertRaises(cd.CDError):
self.execute()
self.assert_no_deploy()
def test_bare_ci_success_cannot_replace_required_context(self):
for statuses in ([], [{'context': 'different', 'status': 'success'}],
[{'context': CTX, 'status': 'failure'}, {'context': CTX, 'status': 'success'}]):
with self.assertRaises(cd.CDError):
cd.verify_contexts({'state': 'success', 'statuses': statuses}, [CTX])
cd.verify_contexts({'state': 'success', 'statuses': [{'context': CTX, 'status': 'success'}]}, [CTX])
def test_approval_and_acceptance_rechecked_before_switch(self):
self.host.approve.side_effect = [None, cd.CDError('revoked')]
with self.assertRaisesRegex(cd.CDError, 'revoked'):
self.execute()
self.host.switch.assert_not_called()
self.host.callback.assert_not_called()
def test_success_and_writeback_retry_do_not_switch_twice(self):
self.host.callback.side_effect = [cd.CDError('HiFox timeout'), None]
with self.assertRaisesRegex(cd.CDError, 'DEPLOYED_HIFOX_PENDING'):
self.execute()
self.assertEqual(cd.read_json(self.host.receipt_path)['state'], 'deployed_hifox_pending')
self.request.update(action='writeback', confirm='retry-writeback')
self.assertEqual(self.execute()['state'], 'published')
self.host.switch.assert_called_once()
self.host.load.assert_called_once()
self.assertEqual(self.host.verify.call_count, 2)
def test_writeback_without_receipt_refuses(self):
self.request.update(action='writeback', confirm='retry-writeback')
with self.assertRaisesRegex(cd.CDError, 'receipt'):
self.execute()
self.assert_no_deploy()
def test_failed_cutover_rolls_back_and_never_marks_published(self):
for result in ('rolled_back', 'rollback_failed'):
with self.subTest(result=result):
self.setUp()
self.host.verify.side_effect = cd.CDError('new unhealthy')
if result == 'rollback_failed':
self.host.rollback.side_effect = cd.CDError('old unhealthy')
with self.assertRaisesRegex(cd.CDError, result):
self.execute()
self.assertEqual(cd.read_json(self.host.receipt_path)['state'], result)
self.host.rollback.assert_called_once()
self.host.callback.assert_not_called()
with self.assertRaisesRegex(cd.CDError, 'receipt'):
self.execute()
self.host.switch.assert_called_once()
def test_gitea_guard_log_binds_the_exact_dispatch(self):
trusted = 'f' * 40
proof = cd.guard_proof(self.request, trusted)
log = f'2026-11-22T17:31:54.013Z {proof}\n'.encode()
cd.verify_guard_log(log, self.request, trusted)
for name, altered in (('sha', 'b' * 40), ('bundle', 'c' * 64), ('run_id', '43'),
('task', 'd5abdf29-d0b5-4992-8073-0cb8fffd84ee2'), ('confirm', 'retry-writeback')):
with self.subTest(name=name), self.assertRaisesRegex(cd.CDError, 'dispatch proof'):
cd.verify_guard_log(log, {**self.request, name: altered}, trusted)
with self.assertRaisesRegex(cd.CDError, 'dispatch proof'):
cd.verify_guard_log(log + log, self.request, trusted)
def hifox_fixture(self):
task = self.host.task.return_value
report = 'ba3ced78-e648-47de-9c17-bccb8f31f36f'
event = 'a3aa1dbe-4082-4972-8e29-ed3e39e26b30'
task.update(url='https://app.hifox.com/example/task/TEST-42', statusChangedAt='2026-11-22T18:00:00Z')
self.acceptance['evidence'] = task['url'] + '#comment-' + report
task['metadata']['cd_acceptance'] = json.dumps(self.acceptance)
timeline = [dict(id=report, event='commented', createdAt='2026-11-22T17:59:00Z',
content=f'验收通过 {SHA} {self.request["bundle"]}'),
dict(id=event, event='status_changed', createdAt=task['statusChangedAt'],
actor={'type': 'human', 'id': cd.RELEASE_OWNER}, metadata={'to': '待发布'})]
return task, timeline
def test_hifox_dispatch_claims_one_transition(self):
task, timeline = self.hifox_fixture()
timeline[-1]['createdAt'] = '2026-11-22T18:00:01Z'
cd.atomic_write(self.root / 'active-since', b'2026-11-22T17:55:00Z\n')
with patch.object(trigger, 'hifox', side_effect=[task, timeline] * 3), \
patch.object(trigger, 'stage_bundle', side_effect=lambda inputs: inputs['bundle']), \
patch.object(trigger, 'forge', return_value={'workflow_run_id': 42}) as dispatch:
first = trigger.queue(TASK, 'unused', self.root)
replay = trigger.queue(TASK, 'unused', self.root)
self.assertEqual(first, replay)
self.assertEqual(first['run_id'], '42')
dispatch.assert_called_once_with('POST', trigger.DISPATCH, {'ref': 'main', 'inputs': first['inputs']})
self.assertEqual(first['inputs']['approval_event'], timeline[-1]['id'])
def test_missing_target_bundle_holds_dispatch_without_claim(self):
task, timeline = self.hifox_fixture()
cd.atomic_write(self.root / 'active-since', b'2026-11-22T17:55:00Z\n')
with patch.object(trigger, 'hifox', side_effect=[task, timeline]), \
patch.object(trigger, 'stage_bundle', create=True, side_effect=cd.CDError('archive unavailable')), \
patch.object(trigger, 'forge', return_value={'workflow_run_id': 42}) as dispatch:
with self.assertRaisesRegex(cd.CDError, 'archive unavailable'):
trigger.queue(TASK, 'unused', self.root)
dispatch.assert_not_called()
self.assertFalse((self.root / (timeline[-1]['id'] + '.json')).exists())
def test_unknown_dispatch_outcome_is_held(self):
task, timeline = self.hifox_fixture()
cd.atomic_write(self.root / 'active-since', b'2026-11-22T17:55:00Z\n')
with patch.object(trigger, 'hifox', side_effect=[task, timeline] * 3), \
patch.object(trigger, 'stage_bundle', side_effect=lambda inputs: inputs['bundle']), \
patch.object(trigger, 'forge', side_effect=TimeoutError()) as dispatch:
with self.assertRaises(TimeoutError):
trigger.queue(TASK, 'unused', self.root)
with self.assertRaisesRegex(cd.CDError, 'outcome unknown'):
trigger.queue(TASK, 'unused', self.root)
dispatch.assert_called_once()
def test_hifox_gate_requires_owner_and_existing_candidate_report(self):
for failure in ('agent', 'other human', 'mismatched report', 'updated report', 'stale transition', 'no evidence'):
with self.subTest(failure=failure):
task, timeline = self.hifox_fixture()
if failure == 'agent':
timeline[-1]['actor']['type'] = 'agent'
if failure == 'other human':
timeline[-1]['actor']['id'] = TASK
if failure == 'mismatched report':
timeline[0]['content'] = SHA
if failure == 'updated report':
timeline[0]['updatedAt'] = '2026-11-22T19:00:00Z'
if failure == 'stale transition':
task['statusChangedAt'] = '2026-11-22T19:00:00Z'
if failure == 'no evidence':
task['metadata'] = {}
with patch.object(trigger, 'hifox', side_effect=[task, timeline]), patch.object(trigger, 'forge') as forge:
with self.assertRaises(cd.CDError):
trigger.queue(TASK, 'unused', self.root)
forge.assert_not_called()
def test_auto_approval_is_checked_again_before_switch(self):
task, timeline = self.hifox_fixture()
approval, _ = cd.release_approval(task, timeline, self.request)
self.request.update(approval)
self.host.timeline.side_effect = [timeline, timeline[:-1]]
proof = cd.guard_proof(self.request, 'f' * 40)
self.assertNotEqual(proof, cd.guard_proof({**self.request, 'acceptance_digest': 'e' * 64}, 'f' * 40))
with self.assertRaisesRegex(cd.CDError, 'status history'):
self.execute()
self.host.switch.assert_not_called()
def test_target_lock_is_exclusive(self):
path = self.root / 'lock'
with cd.deploy_lock(path):
with self.assertRaisesRegex(cd.CDError, 'deployment lock'):
with cd.deploy_lock(path):
self.fail('lock was acquired twice')
def test_persisted_compose_changes_only_images(self):
original = {'services': {role: {'image': role + ':old', 'env_file': [{'path': '/kept', 'format': 'raw'}],
'volumes': ['/kept:/run/key:ro'], 'environment': {'GATE': 'true'}}
for role in IMAGES}, 'name': 'governance'}
changed = cd.with_images(original, IMAGES)
for role, new in changed['services'].items():
self.assertEqual(new.pop('image'), IMAGES[role])
old = original['services'][role].copy()
old.pop('image')
self.assertEqual(new, old)
if __name__ == '__main__':
unittest.main()
+99
View File
@@ -0,0 +1,99 @@
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import json
import os
from threading import Thread
from pathlib import Path
import subprocess
import tempfile
import unittest
from unittest.mock import patch
import qa_env
class QAEnvironmentTests(unittest.TestCase):
def test_missing_approval_config_names_file(self):
with tempfile.TemporaryDirectory() as directory:
config = Path(directory) / 'qa.json'
with self.assertRaisesRegex(qa_env.QAError, 'qa.json'):
qa_env.database_config(config)
def test_rejects_non_qa_database_before_connection(self):
with tempfile.TemporaryDirectory() as directory:
config = Path(directory) / 'qa.json'
config.write_text(json.dumps(dict(host='rds.example.test', port=5432,
database='governance', user='kg_qa_app')))
config.chmod(0o600)
with self.assertRaisesRegex(qa_env.QAError, 'kg_qa_'):
qa_env.database_config(config)
def test_database_environment_uses_only_approved_identity(self):
settings = dict(host='rds.example.test', port=5432, database='kg_qa_app', user='kg_qa_app')
with patch.dict(os.environ, {'PGHOSTADDR': '127.0.0.1', 'PGPASSWORD': 'fixture',
'PGSERVICE': 'other', 'PRODUCTION_RELEASE_REQUESTS_ENABLED': 'true'}):
env = qa_env.database_env(settings, Path('/approved'))
self.assertEqual(env['PGHOST'], 'rds.example.test')
self.assertEqual(env['PGSSLMODE'], 'verify-full')
self.assertEqual(env['PRODUCTION_RELEASE_REQUESTS_ENABLED'], 'false')
self.assertFalse({'PGHOSTADDR', 'PGPASSWORD', 'PGSERVICE'} & env.keys())
def test_empty_database_or_known_migration_prefix_can_bootstrap(self):
for applied in ([], [1], [1, 2]):
with self.subTest(applied=applied):
qa_env.check_migrations([1, 2], applied, False, complete=False)
def test_pending_migrations_block_testing(self):
with self.assertRaisesRegex(qa_env.QAError, '迁移未完成'):
qa_env.check_migrations([1, 2], [1], False, complete=True)
def test_schema_without_ledger_is_rejected(self):
with self.assertRaisesRegex(qa_env.QAError, '非空'):
qa_env.check_migrations([1, 2], [], True, complete=False)
def test_unknown_or_missing_middle_migrations_are_rejected(self):
for applied in ([1, 3], [1, 2, 3], [2]):
with self.subTest(applied=applied), self.assertRaisesRegex(qa_env.QAError, '迁移序列'):
qa_env.check_migrations([1, 2], applied, False, complete=False)
def test_hifox_exit_zero_does_not_override_offline_state(self):
with self.assertRaisesRegex(qa_env.QAError, '在线'):
qa_env.check_hifox('{"connected":true,"remoteLiveness":{"status":"offline"}}')
qa_env.check_hifox('{"connected":true,"remoteLiveness":{"status":"online"}}')
def test_health_probe_rejects_spa_fallback(self):
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header('Content-Type', 'text/html')
self.end_headers()
self.wfile.write(b'<html><div id="root"></div></html>')
def log_message(self, format, *args):
pass
with ThreadingHTTPServer(('127.0.0.1', 0), Handler) as server:
thread = Thread(target=server.serve_forever)
thread.start()
try:
self.assertTrue(qa_env.probe(server.server_port, '/', 'html'))
self.assertFalse(qa_env.probe(server.server_port, '/health', 'ok'))
finally:
server.shutdown()
thread.join()
def test_database_identity_mismatch_stops_before_reading_migrations(self):
env = {'PGDATABASE': 'kg_qa_app', 'PGUSER': 'kg_qa_app'}
with patch.object(qa_env, 'psql', return_value='other|kg_qa_app|t|t|t|t|t') as probe:
with self.assertRaisesRegex(qa_env.QAError, '实际库名'):
qa_env.database_state(env)
self.assertEqual(probe.call_count, 1)
def test_full_sha_mismatch_rejects_current_checkout(self):
full_sha = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=qa_env.ROOT, text=True).strip()
wrong = ('0' if full_sha[0] != '0' else '1') + full_sha[1:]
with self.assertRaisesRegex(qa_env.QAError, '提交不一致'):
qa_env.check_checkout(wrong)
if __name__ == '__main__':
unittest.main()
-717
View File
@@ -1,717 +0,0 @@
import { renderToStaticMarkup } from 'react-dom/server'
import { describe, expect, it, vi } from 'vitest'
import {
BackupScheduleView,
backupDaysValid,
backupMonthsValid,
backupTimeValid,
copyBackupPath,
formatBackupBytes,
inventoryAlerts,
inventorySnapshotState,
inventoryUsage,
runMoment,
storageAlerts,
storageAlertSummary,
storageUsage,
} from './BackupScheduleSection'
import type { StorageDiskObservation } from './BackupScheduleSection'
import type { BackupInventory } from './backupInventory'
import type { BackupSchedule } from './backupSchedule'
const base: BackupSchedule = {
enabled: true,
schedule_time: '03:30',
retention_days: 7,
retention_months: 3,
updated_by: 'yaozhanghao',
updated_at: '2026-10-09T12:00:00Z',
last_applied_at: '2026-10-09T12:00:00Z',
last_applied_summary: '每天 03:30 · 保留 7 天 · 每月归档 3 份',
host_configured: true,
host_target: 'weknora-test',
host_endpoint: '100.85.111.121:22',
host_reachable: true,
host_error: '',
host_schedule_enabled: true,
host_schedule_time: '03:30',
host_keep_days: 7,
host_keep_months: 3,
host_cron_lines: [
'30 03 * * * root /bin/bash /opt/weknora-test/logical-backup.sh >> /srv/kb-backups/logs/logical-backup.log 2>&1',
],
host_cron_service: 'active',
host_script_present: true,
last_run_stamp: '20261009T052909Z',
last_run_created_at: '2026-10-09T05:29:09Z',
last_run_duration_seconds: 33,
last_run_total_bytes: 778_502_144,
last_run_databases: ['weknora_test', 'dobotai_prod'],
last_run_failed_databases: [],
last_run_error: '',
in_sync: true,
applied: true,
apply_error: '',
running: false,
running_started_at: '',
run_last_error: '',
}
const GiB = 1024 * 1024 * 1024
const diskFixture = (overrides: Partial<StorageDiskObservation> = {}): StorageDiskObservation => ({
total_bytes: 240 * GiB,
free_bytes: 48 * GiB,
backup_bytes: 62 * GiB,
other_volume_backup_bytes: 0,
quota_bytes: 100 * GiB,
reserve_bytes: 10 * GiB,
estimate_bytes: 12 * GiB,
sampled_at: '2026-11-19T02:00:00Z',
...overrides,
})
const inventoryFixture = (overrides: Partial<BackupInventory> = {}): BackupInventory => {
const baseInventory: BackupInventory = {
wired: true,
metadata: {
configured: true,
present: true,
valid: true,
fresh: true,
complete: true,
path: '/var/lib/knowledge-governance/backup-host/metadata.json',
collected_at: '2026-11-19T03:30:00Z',
age_seconds: 10,
max_age_seconds: 900,
schema_version: 1,
generation: '20261119T033000Z-abc123',
host: 'weknora-test',
collector_version: 'backup-metadata/1',
error: '',
},
root: '/srv/kb-backups/rds-logical',
host_root: '/srv/kb-backups/rds-logical',
source: 'weknora-test:/srv/kb-backups/rds-logical',
observed_at: '2026-11-19T03:30:10Z',
error: '',
measurement: 'host_collector',
mount: {
container_root: '',
mount_verified: true,
lives_on_container_root: false,
read_only: true,
evidence: '宿主采集器:/dev/sdb1 挂在 /srv/kb-backups(ext4),API 不遍历备份目录',
mount_point: '/srv/kb-backups',
device: '/dev/sdb1',
fs_type: 'ext4',
},
capacity: {
measured: true,
total_bytes: 240 * GiB,
free_bytes: 48 * GiB,
available_bytes: 45 * GiB,
used_bytes: 192 * GiB,
},
batches: [
{
stamp: '20261118T193001Z',
path: '/var/lib/knowledge-governance/backup-host/rds-logical/20261118T193001Z',
host_path: '/srv/kb-backups/rds-logical/20261118T193001Z',
manifest_state: 'ok',
manifest_path: '/var/lib/knowledge-governance/backup-host/rds-logical/20261118T193001Z/MANIFEST.json',
kind: 'rds-logical-backup',
created_at: '20261118T193001Z',
started_at: '20261118T192908Z',
duration_seconds: 53,
manifest_total_bytes: 1_393_646_469,
apparent_bytes: 1_393_646_469,
actual_bytes: 1_500_000_000,
file_count: 214,
sizes_complete: true,
databases: [
{
name: 'weknora_v090prod',
dir_name: 'weknora_v090prod.dir',
path: '/var/lib/knowledge-governance/backup-host/rds-logical/20261118T193001Z/weknora_v090prod.dir',
host_path: '/srv/kb-backups/rds-logical/20261118T193001Z/weknora_v090prod.dir',
present: true,
failed: false,
in_manifest: true,
apparent_bytes: 700_000,
actual_bytes: 720_896,
file_count: 12,
},
{
name: 'weknora_test',
dir_name: 'weknora_test.dir',
path: '/var/lib/knowledge-governance/backup-host/rds-logical/20261118T193001Z/weknora_test.dir',
host_path: '/srv/kb-backups/rds-logical/20261118T193001Z/weknora_test.dir',
present: true,
failed: true,
in_manifest: true,
apparent_bytes: 10,
actual_bytes: 4096,
file_count: 1,
},
],
},
{
stamp: '20261117T193001Z',
path: '/var/lib/knowledge-governance/backup-host/rds-logical/20261117T193001Z',
host_path: '/srv/kb-backups/rds-logical/20261117T193001Z',
manifest_state: 'invalid',
manifest_path: '/var/lib/knowledge-governance/backup-host/rds-logical/20261117T193001Z/MANIFEST.json',
manifest_error: '清单无法解析:unexpected end of JSON input',
kind: '',
created_at: '',
started_at: '',
duration_seconds: 0,
manifest_total_bytes: 0,
apparent_bytes: 2048,
actual_bytes: 4096,
file_count: 1,
sizes_complete: true,
databases: [
{
name: 'weknora_archive',
dir_name: 'weknora_archive.dir',
path: '/var/lib/knowledge-governance/backup-host/rds-logical/20261117T193001Z/weknora_archive.dir',
host_path: '/srv/kb-backups/rds-logical/20261117T193001Z/weknora_archive.dir',
present: false,
failed: false,
in_manifest: false,
apparent_bytes: 0,
actual_bytes: 0,
file_count: 0,
},
],
},
],
totals: {
batch_count: 2,
database_count: 3,
apparent_bytes: 1_393_648_517,
actual_bytes: 1_500_004_096,
latest_stamp: '20261118T193001Z',
latest_actual_bytes: 1_500_000_000,
complete: true,
},
incomplete_count: 1,
skipped: [{ name: 'junk', reason: '不是批次目录' }],
truncated: false,
}
return { ...baseInventory, ...overrides }
}
const view = (
overrides: Partial<BackupSchedule> = {},
extra: Record<string, unknown> = {},
disk: StorageDiskObservation | null = null
) => {
const schedule = { ...base, ...overrides }
return renderToStaticMarkup(
<BackupScheduleView
schedule={schedule}
isAdmin={(extra.isAdmin as boolean) ?? true}
loading={false}
probing={false}
busy={(extra.busy as 'save' | 'apply' | 'run' | null) ?? null}
error={(extra.error as string | null) ?? null}
message={(extra.message as string) ?? ''}
enabledDraft={(extra.enabledDraft as boolean) ?? schedule.enabled}
timeDraft={(extra.timeDraft as string) ?? schedule.schedule_time}
daysDraft={(extra.daysDraft as string) ?? String(schedule.retention_days)}
monthsDraft={(extra.monthsDraft as string) ?? String(schedule.retention_months)}
onEnabledChange={vi.fn()}
onTimeChange={vi.fn()}
onDaysChange={vi.fn()}
onMonthsChange={vi.fn()}
onSave={vi.fn()}
onApply={vi.fn()}
onRunNow={vi.fn()}
onReload={vi.fn()}
disk={disk}
inventory={(extra.inventory as BackupInventory) ?? null}
inventoryLoading={(extra.inventoryLoading as boolean) ?? false}
inventoryError={(extra.inventoryError as string | null) ?? null}
onReloadInventory={vi.fn()}
/>
)
}
describe('BackupScheduleView', () => {
it('按真实契约给出范围与读写方向,并把立即备份限定为整批', () => {
const html = view()
for (const text of [
'存储与备份',
'数据库整库逻辑备份',
'范围与读写方向',
'备份执行主机 weknora-test 本机直连 RDS',
'最近批次含 2 个数据库',
'元数据快照未读取',
'元数据快照未读取:目录不可验证,不按设置推定',
'整批 · 2 个数据库(weknora_test、dobotai_prod)',
'100.85.111.121:22',
'立即备份一次(整批 2 个数据库)',
'不开放单库动作',
'仅备份该库(不可用)',
])
expect(html).toContain(text)
// 不存在把整批接口包装成单库操作的按钮文案。
expect(html).not.toContain('>立即备份</button>')
expect(html).not.toContain('生产 090')
expect(html).not.toContain('weknora_v090prod')
})
it('策略区分主机生效状态与编辑草稿,保留期与时间仍是真实可保存字段', () => {
const html = view({}, { timeDraft: '05:10', daysDraft: '14' })
expect(html).toContain('主机生效:每天 03:30 · 保留 7 天 · 每月 3 份 · 与设置已一致')
expect(html).toContain('最后下发(历史)')
expect(html).toContain('只记录当时下发结果,不能代表当前主机计划或执行状态')
expect(html).toContain('编辑草稿:每天 05:10 · 保留 14 天')
expect(html).toContain('有未保存修改,主机仍按生效计划执行')
expect(html).toContain('type="time"')
expect(html).toContain('value="05:10"')
expect(html).toContain('储存天数')
expect(html).toContain('每月归档保留')
expect(html).toContain('保存并下发到主机')
expect(html).toContain('重新下发当前设置')
})
it('目录/配额/预留没有后端字段:控件禁用并写明原因,不会假装可保存', () => {
const html = view()
expect(html).toContain('备份主机上的目录')
expect(html).toContain('元数据快照未读取')
expect(html).toContain('检查目录(不可用)')
expect(html).toContain('备份总配额(GiB)')
expect(html).toContain('磁盘预留(GiB)')
expect(html).toContain('不会被保存')
expect(html).toContain('保存只提交后端契约里的四项')
expect(html).toContain('disabled')
})
it('宿主快照:展示全部批次、MANIFEST 状态、子库完整路径与实际占盘', () => {
const html = view({}, { inventory: inventoryFixture() })
for (const text of [
'备份记录',
'2 批 · 元数据快照',
'最近批次 20261118T193001Z',
'清单完整',
'清单损坏',
'批次戳 20261118T193001Z',
'实际占盘',
'weknora_v090prod',
'weknora_test',
'已写入',
'失败',
'目录缺失',
'/srv/kb-backups/rds-logical/20261118T193001Z',
'/srv/kb-backups/rds-logical/20261118T193001Z/weknora_v090prod.dir',
'/srv/kb-backups/rds-logical/20261117T193001Z/weknora_archive.dir',
'复制子库目录',
'清单无法解析',
'有 1 个',
'junk(不是批次目录)',
'恢复验证:未接线',
])
expect(html).toContain(text)
expect(html).not.toContain('子库路径待接口返回')
expect(html).not.toContain('复制目录(不可用)')
})
it('没有快照:不展示任何历史批次或伪造路径', () => {
const html = view()
expect(html).toContain('尚未读取宿主元数据快照')
expect(html).not.toContain('批次戳')
expect(html).not.toContain('/srv/kb-backups/rds-logical')
})
it('快照未接线:说明与 SSH 计划读回独立,未读到不等于没有备份', () => {
const base = inventoryFixture()
const html = view(
{},
{
inventory: inventoryFixture({
wired: false,
metadata: {
...base.metadata,
configured: false,
present: false,
valid: false,
fresh: false,
complete: false,
error: '元数据快照未接线(BACKUP_HOST_METADATA_PATH 未设置)',
},
error: '元数据快照未接线(BACKUP_HOST_METADATA_PATH 未设置)',
batches: [],
capacity: { measured: false, total_bytes: 0, free_bytes: 0, available_bytes: 0, used_bytes: 0 },
}),
}
)
expect(html).toContain('元数据快照未接线')
expect(html).toContain('未读到批次不等于没有备份')
expect(html).not.toContain('/srv/kb-backups/rds-logical/20261118T193001Z')
})
it('快照可读但没有批次时说明不能据此判断成功/失败', () => {
const html = view(
{
last_run_stamp: '',
last_run_created_at: '',
last_run_databases: [],
last_run_total_bytes: 0,
host_reachable: false,
},
{
inventory: inventoryFixture({
batches: [],
totals: {
batch_count: 0,
database_count: 0,
apparent_bytes: 0,
actual_bytes: 0,
latest_stamp: '',
latest_actual_bytes: 0,
complete: true,
},
}),
}
)
expect(html).toContain('宿主快照可读,但没有批次目录')
expect(html).toContain('不能证明备份成功或失败')
})
it('非管理员只读:没有保存/下发/立即备份按钮,只给当前设置', () => {
const html = view({}, { isAdmin: false })
expect(html).toContain('定时备份设置仅管理员可修改')
expect(html).toContain('立即备份仅管理员可触发')
expect(html).not.toContain('保存并下发到主机')
expect(html).not.toContain('立即备份一次(整批')
})
it('无主机凭据:不能宣称远端计划停止,历史下发只作历史记录', () => {
const html = view({
host_configured: false,
host_reachable: false,
host_error: '目标主机凭据未挂载(BACKUP_HOST_SSH_CONFIG / BACKUP_HOST_TARGET)',
in_sync: false,
})
expect(html).toContain('平台未挂载主机凭据(远端状态未知)')
expect(html).toContain('无法确认当前主机计划')
expect(html).toContain('远端 cron 可能仍在执行')
expect(html).toContain('历史下发不能代替实时状态')
expect(html).toContain('最后下发(历史)')
expect(html).toContain('只记录当时下发结果,不能代表当前主机计划或执行状态')
expect(html).toContain('无法比对(未读取主机计划)')
expect(html).toContain('未探测(平台未挂载主机凭据)')
expect(html).toContain('目标主机凭据未挂载')
// 没读到主机就断言"不会执行"是同类误报。
expect(html).not.toContain('不会执行')
expect(html).not.toContain('未接通备份执行主机')
expect(html).toContain('disabled')
})
it('主机已接线但尚未探测:区分"连不上"与"还没读",不按设置推定', () => {
const html = view({ host_reachable: false, host_error: '', host_checked_at: '', in_sync: false })
expect(html).toContain('weknora-test · 尚未探测')
expect(html).not.toContain('weknora-test · 连接失败')
expect(html).toContain('尚未探测当前主机计划:不能按设置或历史下发推定')
expect(html).toContain('尚未比对')
expect(html).toContain('尚未探测主机,无法确认下一次执行')
})
it('连不上主机:报连接失败与拨号地址,脚本状态写未知而不是"缺失"', () => {
const html = view({
host_reachable: false,
host_endpoint: '120.76.217.51:22',
host_error:
'目标主机 weknora-test 不可达(ssh: connect to host 120.76.217.51 port 22: Operation timed out);未执行任何主机侧脚本,脚本与计划状态未知(拨号地址 120.76.217.51:22)',
in_sync: false,
host_script_present: false,
})
expect(html).toContain('weknora-test · 连接失败')
expect(html).toContain('120.76.217.51:22')
expect(html).toContain('未知(未连上主机,未执行主机侧脚本)')
expect(html).not.toContain('<dt>备份脚本</dt><dd>缺失</dd>')
expect(html).toContain('主机连不上:以下&quot;主机生效&quot;状态未知')
expect(html).toContain('无法比对(主机不可达)')
})
it('已连上且脚本真的不在:这时才显示"缺失"', () => {
const html = view({ host_reachable: true, host_script_present: false, in_sync: false })
expect(html).toContain('weknora-test · 已连接')
expect(html).toContain('缺失')
expect(html).not.toContain('未知(未连上主机')
})
it('待下发(主机上的计划与设置不一致)时提示', () => {
const html = view({ host_schedule_time: '05:00', in_sync: false })
expect(html).toContain('待下发')
expect(html).toContain('每天 05:00')
})
it('在途备份:只报在途与开始时间,不造百分比', () => {
const html = view({ running: true, running_started_at: '2026-10-09T12:30:00Z' })
expect(html).toContain('备份进行中…')
expect(html).toContain('正在备份')
expect(html).toContain('没有真实百分比接口')
})
it('非法输入就地拦截,且保存按钮在未改动时不可点', () => {
const html = view({}, { timeDraft: '25:99', daysDraft: '0' })
expect(html).toContain('定时时间需为 HH:MM(00:00~23:59),储存天数 1~365,每月归档 0~24。')
expect(html).toContain('disabled')
expect(backupTimeValid('03:30')).toBe(true)
expect(backupTimeValid('24:00')).toBe(false)
expect(backupDaysValid(0)).toBe(false)
expect(backupDaysValid(365)).toBe(true)
expect(backupMonthsValid(0)).toBe(true)
expect(backupMonthsValid(25)).toBe(false)
})
it('展示失败的库与最近一次读取错误', () => {
const html = view({ last_run_failed_databases: ['rdsadmin'], last_run_error: '清单无法解析' })
expect(html).toContain('rdsadmin')
expect(html).toContain('清单无法解析')
})
it('最近一次备份不重复显示同一个时间戳', () => {
expect(runMoment({ last_run_stamp: '20261009T060736Z', last_run_created_at: '20261009T060736Z' })).toBe('')
expect(runMoment({ last_run_stamp: '20261009T060736Z', last_run_created_at: '' })).toBe('')
expect(runMoment({ last_run_stamp: '20261009T060736Z', last_run_created_at: '2026-10-09T06:07:36Z' })).not.toBe('')
})
it('体积格式化:未知与零分开', () => {
expect(formatBackupBytes(0)).toBe('0 B')
expect(formatBackupBytes(null)).toBe('—')
expect(formatBackupBytes(undefined)).toBe('—')
expect(formatBackupBytes(1024 * 1024)).toBe('1.0 MiB')
expect(formatBackupBytes(4096)).toBe('4.0 KiB')
expect(formatBackupBytes(720896)).toBe('0.7 MiB')
expect(formatBackupBytes(2 * 1024 * 1024 * 1024)).toBe('2.00 GiB')
})
})
describe('整盘占用与告警', () => {
it('没有快照时:不显示示例容量,四条告警只报未知原因', () => {
const html = view()
expect(html).toContain('占盘未知 · 不使用部分字节')
expect(html).toContain('宿主单项元数据采集器')
expect(html).toContain('无法判定')
expect(html).toContain('整盘总量 / 空闲 / 备份实际占盘:未接线')
// 原型里的示例容量不能被当成产品事实带进来。
expect(html).not.toContain('总容量 240 GiB')
expect(html).not.toContain('总容量 500 GiB')
expect(html).not.toContain('可再写')
})
it('四段色带按真实读数计算:系统其他、备份已用、配额内空闲、配额外空闲', () => {
const usage = storageUsage(diskFixture())
expect(usage.system_other).toBe(130 * GiB) // 240 - 48 - 62
expect(usage.backup).toBe(62 * GiB)
expect(usage.quota_free).toBe(38 * GiB)
expect(usage.beyond_quota_free).toBe(10 * GiB) // 48 - 38
expect(usage.allowance).toBe(38 * GiB)
const html = view({}, {}, diskFixture())
expect(html).toContain('系统其他占用 130 GiB')
expect(html).toContain('备份已用 62 GiB')
expect(html).toContain('配额内空闲 38 GiB')
expect(html).toContain('配额外空闲 10 GiB')
expect(html).toContain('四项均正常')
})
it('磁盘不足:只剩磁盘告警,差值与预计新增都来自读数', () => {
const alerts = storageAlerts(diskFixture({ free_bytes: 20 * GiB, quota_bytes: 80 * GiB }))
expect(alerts.find((item) => item.code === 'disk_low')?.active).toBe(true)
expect(alerts.find((item) => item.code === 'quota_low')?.active).toBe(false)
expect(alerts.find((item) => item.code === 'both_low')?.active).toBe(false)
expect(storageAlertSummary(alerts)).toBe('磁盘不足')
const html = view({}, {}, diskFixture({ free_bytes: 20 * GiB, quota_bytes: 80 * GiB }))
expect(html).toContain('差 2 GiB')
})
it('配额不足:磁盘够、配额差 7 GiB', () => {
const alerts = storageAlerts(diskFixture({ backup_bytes: 95 * GiB }))
expect(alerts.find((item) => item.code === 'quota_low')?.active).toBe(true)
expect(alerts.find((item) => item.code === 'disk_low')?.active).toBe(false)
expect(alerts.find((item) => item.code === 'quota_low')?.detail).toContain('差 7 GiB')
expect(storageAlertSummary(alerts)).toBe('配额不足')
})
it('两者同时不足:第三条告警成立', () => {
const alerts = storageAlerts(diskFixture({ free_bytes: 20 * GiB, backup_bytes: 95 * GiB }))
expect(alerts.find((item) => item.code === 'both_low')?.active).toBe(true)
expect(storageAlertSummary(alerts)).toContain('磁盘与配额同时不足')
})
it('配额超出物理空闲:配额余量大于盘上空闲时单独告警', () => {
const alerts = storageAlerts(diskFixture({ quota_bytes: 200 * GiB }))
expect(alerts.find((item) => item.code === 'quota_over_physical')?.active).toBe(true)
expect(alerts.find((item) => item.code === 'quota_over_physical')?.detail).toContain('超出部分画不进磁盘')
})
it('缺下次新增体积时,磁盘/配额判定保持未知而不是默认正常', () => {
const alerts = storageAlerts(diskFixture({ estimate_bytes: null }))
expect(alerts.filter((item) => !item.known).map((item) => item.code)).toEqual(['disk_low', 'quota_low', 'both_low'])
})
it('真实快照:整盘色带取采集器容量与 st_blocks 实际占盘', () => {
const inventory = inventoryFixture()
const usage = inventoryUsage(inventory)
expect(usage).not.toBeNull()
expect(usage!.total).toBe(240 * GiB)
expect(usage!.free).toBe(45 * GiB)
expect(usage!.backup).toBe(1_500_004_096)
expect(usage!.system_other).toBe(192 * GiB - 1_500_004_096)
const alerts = inventoryAlerts(inventory)
expect(alerts.find((item) => item.code === 'disk_low')?.known).toBe(true)
expect(alerts.find((item) => item.code === 'disk_low')?.active).toBe(false)
expect(alerts.find((item) => item.code === 'quota_low')?.known).toBe(false)
expect(storageAlertSummary(alerts)).toBe('磁盘项正常 · 配额字段未接线')
const html = view({}, { inventory })
for (const text of [
'宿主采集器实测',
'系统其他占用',
'备份实际占盘',
'可用',
'配额内/外 —(无配额字段)',
'文件系统已用',
'采集时间',
'读回时间',
'(API 读回)',
'备份文件系统必须由备份主机可写',
'空间预测仅以上次整批实际占盘 1.40 GiB',
'宿主采集器:/dev/sdb1 挂在 /srv/kb-backups',
'磁盘项正常 · 配额字段未接线',
'0.7 MiB',
'重新盘点(仅重读快照)',
])
expect(html).toContain(text)
expect(html).not.toContain('挂载可写')
expect(html).not.toContain('不是只读')
expect(html).not.toContain('缺主机磁盘读数')
expect(html).not.toContain('0.0 MiB')
})
it('过期快照:目录与历史标已过期,不显示未接线,也不沿用旧批次/旧容量', () => {
const base = inventoryFixture()
const stale = inventoryFixture({
metadata: {
...base.metadata,
valid: false,
fresh: false,
complete: false,
age_seconds: 1200,
error: '元数据已陈旧:采集于 2026-11-19T03:30:00Z,超过 15m0s',
},
capacity: { measured: false, total_bytes: 0, free_bytes: 0, available_bytes: 0, used_bytes: 0 },
totals: { ...base.totals, apparent_bytes: null, actual_bytes: null, latest_actual_bytes: null, complete: false },
// 即使 API 意外保留旧批次,页面也不得用过期快照的路径/容量。
batches: base.batches,
})
expect(inventorySnapshotState(stale)).toBe('stale')
expect(inventoryUsage(stale)).toBeNull()
const alerts = inventoryAlerts(stale)
expect(alerts.find((item) => item.code === 'disk_low')?.known).toBe(false)
expect(alerts.find((item) => item.code === 'disk_low')?.detail).toContain('陈旧')
const html = view({}, { inventory: stale })
for (const text of [
'元数据快照已过期',
'采集时间',
'年龄 1200 秒 / 上限 900 秒',
'已过期',
'读回时间',
'(API 读回)',
'不展示旧批次',
'元数据快照已过期:目录不可验证,不沿用旧路径',
'等待宿主重新采集',
'旧批次、旧目录与旧容量都不再展示',
])
expect(html).toContain(text)
expect(html).not.toContain('元数据快照未接线')
expect(html).not.toContain('/20261118T193001Z')
expect(html).not.toContain('实际占盘 1.40 GiB')
expect(html).not.toContain('文件系统已用')
})
it('未配置快照:明确未接线,不能冒充过期或展示目录/历史', () => {
const base = inventoryFixture()
const unconfigured = inventoryFixture({
wired: false,
metadata: {
...base.metadata,
configured: false,
present: false,
valid: false,
fresh: false,
complete: false,
error: '元数据快照未接线(BACKUP_HOST_METADATA_PATH 未设置)',
},
source: '',
root: '',
host_root: '',
capacity: { measured: false, total_bytes: 0, free_bytes: 0, available_bytes: 0, used_bytes: 0 },
totals: { ...base.totals, apparent_bytes: null, actual_bytes: null, latest_actual_bytes: null, complete: false },
batches: [],
})
expect(inventorySnapshotState(unconfigured)).toBe('unconfigured')
const html = view({}, { inventory: unconfigured })
expect(html).toContain('元数据快照未接线')
expect(html).toContain('目录不可证明')
expect(html).not.toContain('元数据快照已过期')
expect(html).not.toContain('不展示旧目录路径')
})
it('快照请求失败:与未配置/过期分开,不展示目录或旧批次', () => {
const html = view({}, { inventoryError: 'HTTP 503' })
expect(html).toContain('元数据快照读取失败')
expect(html).toContain('快照请求失败:HTTP 503')
expect(html).toContain('目录不可验证')
expect(html).not.toContain('元数据快照未接线')
expect(html).not.toContain('元数据快照已过期')
})
it('不完整快照:容量图与占盘不使用部分字节', () => {
const base = inventoryFixture()
const inventory = inventoryFixture({
metadata: {
...base.metadata,
complete: false,
error: '采集不完整:遍历失败:PermissionError: Permission denied',
},
capacity: { measured: false, total_bytes: 0, free_bytes: 0, available_bytes: 0, used_bytes: 0 },
totals: { ...base.totals, apparent_bytes: null, actual_bytes: null, latest_actual_bytes: null, complete: false },
batches: base.batches.map((batch) => ({
...batch,
apparent_bytes: null,
actual_bytes: null,
file_count: null,
sizes_complete: false,
sizes_error: '宿主采集器该项不完整,占盘未知',
databases: batch.databases.map((database) => ({
...database,
apparent_bytes: null,
actual_bytes: null,
file_count: null,
})),
})),
})
expect(inventoryUsage(inventory)).toBeNull()
const alerts = inventoryAlerts(inventory)
expect(alerts.find((item) => item.code === 'disk_low')?.known).toBe(false)
expect(alerts.find((item) => item.code === 'disk_low')?.detail).toContain('不完整')
expect(storageAlertSummary(alerts)).toBe('无法判定(缺读数与配额字段)')
const html = view({}, { inventory })
expect(html).toContain('占盘未知 · 不使用部分字节')
expect(html).toContain('采集快照不完整:所有批次占盘与容量未知')
expect(html).toContain('占盘未知(采集不完整)')
expect(html).not.toContain('备份实际占盘 1.40 GiB')
expect(html).not.toContain('缺主机磁盘读数')
})
it('复制路径:空值与不可用按钮不谎报成功', async () => {
expect(await copyBackupPath('')).toBe(false)
})
})
File diff suppressed because it is too large Load Diff
-175
View File
@@ -1,175 +0,0 @@
import { useEffect, useState } from 'react'
import { fetchLibraryStorage, formatBytes, type LibraryStorage } from './librarySnapshots'
import './libraryStorage.css'
// 系统设置 → 存储管理:只读展示整库归档的真实口径。
// 保留策略、依赖保护、清理预览都只是"如果清理会怎样",没有任何删除动作;
// 自动清理恒为关闭,策略未设置时不生成候选。
export function LibraryStorageSection() {
const [data, setData] = useState<LibraryStorage | null>(null)
const [error, setError] = useState<string | null>(null)
const [loading, setLoading] = useState(true)
useEffect(() => {
const controller = new AbortController()
fetchLibraryStorage(controller.signal)
.then((value) => {
setData(value)
setError(null)
})
.catch((loadError) => {
if ((loadError as Error).name === 'AbortError') return
setError(loadError instanceof Error ? loadError.message : '读取存储用量失败')
})
.finally(() => setLoading(false))
return () => controller.abort()
}, [])
const plan = data?.plan
const policyConfigured = Boolean(plan?.policy_configured)
return (
<section className="library-storage" aria-label="存储管理">
<header>
<h3>归档占用(版本快照,不是数据库备份)</h3>
<p>
只读口径:被版本引用的去重内容、blob 文件表观/实际分配字节、未被引用对象、清单文件。
这些归档文件与上面的整库数据库备份分开计量,不能相加。
</p>
</header>
{loading ? <p className="library-storage-hint">读取中…</p> : null}
{error ? (
<div className="library-storage-blocked">
<strong>读取失败</strong>
<p>{error}</p>
</div>
) : null}
{data && !data.available ? <p className="library-storage-hint">{data.reason || '归档未接线'}</p> : null}
{data?.available ? (
<>
<dl className="library-storage-grid">
<div>
<dt>版本数</dt>
<dd>{data.versions.length}</dd>
</div>
<div>
<dt>被版本引用的去重内容</dt>
<dd>{formatBytes(data.content_bytes)}</dd>
</div>
<div>
<dt>blob 文件(表观)</dt>
<dd>{formatBytes(data.blob_file_bytes)}</dd>
</div>
<div>
<dt>blob 实际分配</dt>
<dd>{formatBytes(data.blob_allocated_bytes)}</dd>
</div>
<div>
<dt>未被任何版本引用</dt>
<dd>
{data.unreferenced_blobs} 个 / {formatBytes(data.unreferenced_bytes)}
</dd>
</div>
<div>
<dt>清单文件</dt>
<dd>{formatBytes(data.manifest_file_bytes)}</dd>
</div>
</dl>
<div className="library-storage-panel">
<h4>容量门禁</h4>
{data.capacity.configured ? (
<p>
预算 {formatBytes(data.capacity.budget_bytes)} · 当前 {formatBytes(data.capacity.current_bytes)} ·
目标版本约 {formatBytes(data.capacity.required_bytes)} →{' '}
{data.capacity.ok ? '可写入' : `阻断:${data.capacity.reason}`}
</p>
) : (
<p className="library-storage-warn">
容量预算未设置(LIBRARY_CAPACITY_BUDGET_BYTES):无法证明装得下,生产写入按阻断处理。
</p>
)}
</div>
<details className="settings-details" open={!policyConfigured}>
<summary>保留策略与清理预览(未设置时按“全部保留”处理)</summary>
<div className="library-storage-panel">
<h4>保留与依赖保护</h4>
<p>
{policyConfigured
? `策略:${[
plan && plan.policy.keep_versions > 0 ? `保留最近 ${plan.policy.keep_versions} 个版本` : '',
plan && plan.policy.keep_days > 0 ? `保留 ${plan.policy.keep_days} 天` : '',
]
.filter(Boolean)
.join(' + ')}`
: '策略:未设置(不生成清理候选)'}
</p>
<p>
受保护版本 {plan?.protected.length ?? 0} 个:生产生效、每库最近封存、每次生产预备份、运行中作业引用,
不论多久都不会进入候选。
</p>
{data.versions.filter((item) => item.protected).length > 0 ? (
<ul className="library-storage-versions">
{data.versions
.filter((item) => item.protected)
.map((item) => (
<li key={item.id}>
<code>{item.id.slice(0, 12)}</code> {item.kind} · {(item.protected_by ?? []).join('、')}
</li>
))}
</ul>
) : null}
</div>
<div className="library-storage-panel">
<h4>清理预览</h4>
{policyConfigured ? (
plan && plan.candidates.length > 0 ? (
<>
<p>
按策略可考虑清理 {plan.candidates.length} 个版本,独占字节上限{' '}
{formatBytes(plan.reclaim_preview_bytes)}(共享归档文件不会因此释放,这不是可回收空间)。
</p>
<ul className="library-storage-versions">
{plan.candidates.map((item) => (
<li key={item.id}>
<code>{item.id.slice(0, 12)}</code> {item.kind} · {item.reason.join(';')} ·{' '}
{formatBytes(item.exclusive_bytes)}
</li>
))}
</ul>
</>
) : (
<p>按当前策略没有可清理的候选版本。</p>
)
) : (
<p className="library-storage-warn">
保留数量与天数都未设置,按「全部保留」处理:不生成候选,也不提供默认值。
</p>
)}
{plan?.blocked.length ? (
<ul className="library-storage-blocked-list">
{plan.blocked.map((item) => (
<li key={item}>{item}</li>
))}
</ul>
) : null}
</div>
<ul className="library-storage-limits">
<li>自动清理:{data.automatic_cleanup ? '开启' : '保持关闭'}(页面不提供删除动作)</li>
<li>实际删除需要单独授权,本页只给预览</li>
<li>以上数字都不是「可回收空间」,不能用来估算清理收益</li>
{data.notes.map((note) => (
// 服务端注记里的 blob 指归档文件:页面统一术语,不把实现细节甩给操作者。
<li key={note}>{note.replace(/blob/gi, '归档文件')}</li>
))}
</ul>
</details>
</>
) : null}
</section>
)
}
+280
View File
@@ -0,0 +1,280 @@
// @vitest-environment jsdom
import { act } from 'react'
import { createRoot, type Root } from 'react-dom/client'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { StorageBackupSummary } from './StorageBackupSummary'
import type { BackupInventory, BackupInventoryBatch } from './backupInventory'
import type { LibraryStorage } from './librarySnapshots'
const GIB = 1024 ** 3
const TB = 1024 * GIB
const batch = (index: number, overrides: Partial<BackupInventoryBatch> = {}): BackupInventoryBatch => {
const stamp = `202611${String(24 - Math.floor(index / 24)).padStart(2, '0')}T${String(index % 24).padStart(2, '0')}0000Z`
const created = `2026-11-${String(24 - Math.floor(index / 24)).padStart(2, '0')}T${String(index % 24).padStart(2, '0')}:00:00Z`
return {
stamp,
path: `/srv/kb-backups/rds-logical/${stamp}`,
host_path: `/srv/kb-backups/rds-logical/${stamp}`,
manifest_state: 'ok',
manifest_path: `/srv/kb-backups/rds-logical/${stamp}/MANIFEST.json`,
kind: 'rds',
created_at: created,
started_at: created,
duration_seconds: 240,
manifest_total_bytes: 10 * GIB,
apparent_bytes: 10 * GIB,
actual_bytes: 9 * GIB,
file_count: 120,
sizes_complete: true,
databases: [
{
name: 'weknora',
dir_name: 'weknora.dir',
path: `/srv/kb-backups/rds-logical/${stamp}/weknora.dir`,
host_path: `/srv/kb-backups/rds-logical/${stamp}/weknora.dir`,
present: true,
failed: false,
in_manifest: true,
apparent_bytes: 10 * GIB,
actual_bytes: 9 * GIB,
file_count: 120,
},
],
...overrides,
}
}
const inventory = (overrides: Partial<BackupInventory> = {}): BackupInventory => ({
wired: true,
metadata: {
configured: true,
present: true,
valid: true,
fresh: true,
complete: true,
path: '/var/lib/kb-backups/metadata.json',
collected_at: '2026-11-24T10:17:00Z',
age_seconds: 60,
max_age_seconds: 900,
schema_version: 1,
generation: 'g-1',
host: 'backup-host',
collector_version: '1',
error: '',
},
root: '/srv/kb-backups/rds-logical',
host_root: '/srv/kb-backups/rds-logical',
source: 'host',
observed_at: '2026-11-24T10:18:00Z',
measurement: 'host-reported',
mount: {
container_root: '',
mount_verified: true,
lives_on_container_root: false,
read_only: true,
evidence: '',
mount_point: '/srv/kb-backups',
device: '/dev/sdb1',
fs_type: 'ext4',
},
capacity: {
measured: true,
total_bytes: 2 * TB,
free_bytes: 1.2 * TB,
available_bytes: 1.2 * TB,
used_bytes: 0.8 * TB,
},
batches: [batch(0), batch(1, { manifest_state: 'invalid' })],
totals: {
batch_count: 2,
database_count: 2,
apparent_bytes: 20 * GIB,
actual_bytes: 18 * GIB,
latest_stamp: '20261124T000000Z',
latest_actual_bytes: 9 * GIB,
complete: true,
},
incomplete_count: 0,
skipped: [],
truncated: false,
...overrides,
})
const archive: LibraryStorage = {
available: true,
archive_root: '/var/lib/knowledge-governance/library',
versions: [],
content_bytes: 41_231_686_042,
blob_file_bytes: 0,
blob_allocated_bytes: 0,
unreferenced_blobs: 0,
unreferenced_bytes: 0,
manifest_file_bytes: 0,
policy: { keep_versions: 0, keep_days: 0 },
capacity: {
budget_bytes: 100 * GIB,
current_bytes: 41_231_686_042,
required_bytes: 0,
projected_bytes: 41_231_686_042,
configured: true,
ok: true,
},
automatic_cleanup: false,
notes: [],
}
let root: Root
let container: HTMLDivElement
let fetcher: ReturnType<typeof vi.fn<(path: string, init?: RequestInit) => Promise<Response>>>
const paths = (): string[] => fetcher.mock.calls.map((call) => String(call[0]))
const flush = async () => {
await act(async () => {
await Promise.resolve()
await Promise.resolve()
})
}
beforeEach(() => {
container = document.createElement('div')
document.body.append(container)
root = createRoot(container)
fetcher = vi.fn(async (path: string) => {
if (path.endsWith('/inventory')) {
return new Response(JSON.stringify({ data: inventory() }), { status: 200 })
}
return new Response(JSON.stringify(archive), { status: 200 })
})
vi.stubGlobal('fetch', fetcher)
})
afterEach(() => {
act(() => root.unmount())
container.remove()
vi.unstubAllGlobals()
vi.useRealTimers()
})
describe('StorageBackupSummary', () => {
it('renders directory, recent outcomes, archive usage, disk and the alert table', async () => {
act(() => root.render(<StorageBackupSummary />))
await flush()
const text = container.textContent || ''
expect(text).toContain('备份目录')
expect(text).toContain('/srv/kb-backups/rds-logical')
expect(text).toContain('最近成功')
expect(text).toContain('最近失败')
expect(text).toContain('归档占用')
expect(text).toContain('38.4 GB')
expect(text).toContain('配额 100 GB')
expect(text).toContain('磁盘剩余')
expect(text).toContain('1.2 TB')
expect(text).toContain('上次上报')
expect(text).toContain('清单损坏')
expect(container.querySelectorAll('tbody tr')).toHaveLength(2)
expect(container.querySelectorAll('.storage-alerts li')).toHaveLength(4)
expect(text).not.toContain('无法判定')
expect(text).not.toContain('未接线')
expect(text).not.toContain('示例')
})
it('asks for both read-only endpoints and refreshes once per 60 seconds while visible', async () => {
vi.useFakeTimers()
act(() => root.render(<StorageBackupSummary />))
await flush()
expect(paths().filter((path) => path.endsWith('/inventory'))).toHaveLength(1)
expect(paths().filter((path) => path.endsWith('/library/storage'))).toHaveLength(1)
await act(async () => {
await vi.advanceTimersByTimeAsync(60_000)
})
await flush()
expect(paths().filter((path) => path.endsWith('/inventory'))).toHaveLength(2)
Object.defineProperty(document, 'visibilityState', { value: 'hidden', configurable: true })
await act(async () => {
await vi.advanceTimersByTimeAsync(60_000)
})
await flush()
expect(paths().filter((path) => path.endsWith('/inventory'))).toHaveLength(2)
Object.defineProperty(document, 'visibilityState', { value: 'visible', configurable: true })
})
it('shows 主机未上报 with the last report time and no zero placeholders when the host is unwired', async () => {
fetcher.mockImplementation(async (path: string) => {
if (path.endsWith('/inventory')) {
const wired = inventory()
return new Response(
JSON.stringify({
data: {
...wired,
wired: false,
root: '',
host_root: '',
batches: [],
capacity: { measured: false, total_bytes: 0, free_bytes: 0, available_bytes: 0, used_bytes: 0 },
metadata: { ...wired.metadata, present: false, valid: false, fresh: false, collected_at: '' },
},
}),
{ status: 200 }
)
}
return new Response(
JSON.stringify({ ...archive, available: false, capacity: { ...archive.capacity, configured: false } }),
{
status: 200,
}
)
})
act(() => root.render(<StorageBackupSummary />))
await flush()
const text = container.textContent || ''
expect(text).toContain('主机未上报')
expect(text).toContain('上次上报 —')
expect(text).toContain('未接入宿主上报')
expect(text).not.toContain('0 B')
expect(text).not.toContain('0 GB')
expect(container.querySelectorAll('tbody tr')).toHaveLength(0)
expect(text).toContain('主机未上报(上次上报 —)')
})
it('copies a path once the browser grants clipboard access', async () => {
const writeText = vi.fn().mockResolvedValue(undefined)
Object.defineProperty(navigator, 'clipboard', { value: { writeText }, configurable: true })
act(() => root.render(<StorageBackupSummary />))
await flush()
const button = container.querySelector<HTMLButtonElement>('button[aria-label="复制备份目录"]')
expect(button).not.toBeNull()
await act(async () => {
button!.click()
await Promise.resolve()
})
expect(writeText).toHaveBeenCalledWith('/srv/kb-backups/rds-logical')
expect(button!.textContent).toBe('已复制')
})
it('pages long batch lists 20 at a time', async () => {
fetcher.mockImplementation(async (path: string) => {
if (path.endsWith('/inventory')) {
const batches = Array.from({ length: 25 }, (_, index) => batch(index))
return new Response(
JSON.stringify({ data: { ...inventory(), batches, totals: { ...inventory().totals, batch_count: 25 } } }),
{ status: 200 }
)
}
return new Response(JSON.stringify(archive), { status: 200 })
})
act(() => root.render(<StorageBackupSummary />))
await flush()
expect(container.querySelectorAll('tbody tr')).toHaveLength(20)
const more = container.querySelector<HTMLButtonElement>('.storage-more')
expect(more?.textContent).toContain('剩余 5 个')
await act(async () => {
more!.click()
})
expect(container.querySelectorAll('tbody tr')).toHaveLength(25)
expect(container.querySelector('.storage-more')).toBeNull()
})
})
+271
View File
@@ -0,0 +1,271 @@
// 「系统设置 → 存储与备份」只读摘要页:目录、最近成功/失败、归档占用、磁盘剩余、
// 四条容量告警和批次列表。数据只来自宿主每 5 分钟上报的快照与归档库接口,
// 本页没有任何写操作;读不到的量显示"主机未上报"或"—",不用 0 占位。
import { useCallback, useEffect, useRef, useState } from 'react'
import { fetchBackupInventory } from './backupInventory'
import type { BackupInventory } from './backupInventory'
import { fetchLibraryStorage } from './librarySnapshots'
import type { LibraryStorage } from './librarySnapshots'
import {
UNKNOWN,
batchOutcome,
batchWhen,
formatSize,
formatWhen,
hostState,
hostValueLabel,
pendingAlertCount,
storageAlerts,
summaryCards,
} from './storageSummary'
import type { HostState } from './storageSummary'
import './storageBackup.css'
export const REFRESH_INTERVAL_MS = 60_000
const BATCH_PAGE = 20
export async function copyText(value: string): Promise<boolean> {
if (!value) return false
try {
await navigator.clipboard.writeText(value)
return true
} catch {
// 内网 http 页面没有 clipboard 权限时退回选中,不谎报"已复制"。
const area = document.createElement('textarea')
area.value = value
area.setAttribute('readonly', '')
area.style.position = 'fixed'
area.style.opacity = '0'
document.body.append(area)
area.focus()
area.select()
const copied = document.execCommand('copy')
area.remove()
return copied
}
}
const hostStateLabel = (state: HostState): string => {
switch (state) {
case 'unwired':
return '未接入宿主上报'
case 'missing':
return '尚无上报表'
case 'stale':
return '上次上报已过期'
case 'invalid':
return '上次上报不可用'
case 'incomplete':
return '本次上报不完整'
default:
return ''
}
}
export function StorageBackupSummary() {
const [inventory, setInventory] = useState<BackupInventory | null>(null)
const [archive, setArchive] = useState<LibraryStorage | null>(null)
const [archiveFailed, setArchiveFailed] = useState(false)
const [errors, setErrors] = useState<string[]>([])
const [loading, setLoading] = useState(true)
const [visible, setVisible] = useState(BATCH_PAGE)
const [copied, setCopied] = useState('')
const inFlight = useRef(false)
const copiedTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined)
const load = useCallback(async () => {
if (inFlight.current) return
inFlight.current = true
const [inventoryResult, archiveResult] = await Promise.allSettled([fetchBackupInventory(), fetchLibraryStorage()])
const nextErrors: string[] = []
if (inventoryResult.status === 'fulfilled') {
setInventory(inventoryResult.value)
} else {
nextErrors.push(inventoryResult.reason instanceof Error ? inventoryResult.reason.message : '读取备份元数据失败')
}
if (archiveResult.status === 'fulfilled') {
setArchive(archiveResult.value)
setArchiveFailed(archiveResult.value === null)
if (archiveResult.value === null) nextErrors.push('读取归档占用失败')
} else {
setArchiveFailed(true)
nextErrors.push(archiveResult.reason instanceof Error ? archiveResult.reason.message : '读取归档占用失败')
}
setErrors(nextErrors)
setLoading(false)
inFlight.current = false
}, [])
useEffect(() => {
void load()
const timer = setInterval(() => {
if (document.visibilityState === 'hidden') return
void load()
}, REFRESH_INTERVAL_MS)
return () => {
clearInterval(timer)
clearTimeout(copiedTimer.current)
}
}, [load])
const state = hostState(inventory)
const alerts = storageAlerts(inventory, archive, archiveFailed)
const cards = summaryCards(inventory, archive, archiveFailed)
const batches = inventory?.batches ?? []
const shown = batches.slice(0, visible)
const handleCopy = (key: string, value: string) => {
void copyText(value).then((ok) => {
if (!ok) return
setCopied(key)
clearTimeout(copiedTimer.current)
copiedTimer.current = setTimeout(() => setCopied(''), 2000)
})
}
const lastReport = formatWhen(inventory?.metadata.collected_at)
const stateNote = hostStateLabel(state)
return (
<section className="settings-panel storage-summary" aria-label="存储与备份">
<header className="storage-summary-head">
<div>
<h2>存储与备份</h2>
{stateNote ? <p className="storage-summary-state">{stateNote}</p> : null}
</div>
<div className="storage-summary-meta">
<span>上次上报 {lastReport || UNKNOWN}</span>
<button type="button" className="storage-refresh" onClick={() => void load()} disabled={loading}>
刷新
</button>
</div>
</header>
{errors.length > 0 ? (
<p className="storage-summary-error" role="alert">
{errors.join(';')}
</p>
) : null}
{loading ? (
<p className="storage-summary-loading">正在读取存储与备份…</p>
) : (
<>
<div className="storage-cards">
{cards.map((card) => (
<div className={card.key === 'root' ? 'storage-card storage-card-root' : 'storage-card'} key={card.key}>
<span className="storage-card-label">{card.label}</span>
<span className={card.unknown ? 'storage-card-value is-unknown' : 'storage-card-value'}>
{card.value}
</span>
<span className="storage-card-note">
{card.note}
{card.copy ? (
<button
type="button"
className="storage-copy"
onClick={() => handleCopy(card.key, card.copy!)}
aria-label={`复制${card.label}`}
>
{copied === card.key ? '已复制' : '复制'}
</button>
) : null}
</span>
</div>
))}
</div>
<section className="storage-alerts" aria-label="容量告警">
<header>
<h3>容量告警</h3>
<span
className={pendingAlertCount(alerts) > 0 ? 'storage-alert-count is-pending' : 'storage-alert-count'}
>
{pendingAlertCount(alerts)} 项需处理
</span>
</header>
<ul>
{alerts.map((alert) => (
<li key={alert.key} data-tone={alert.tone}>
<span className="storage-alert-label">{alert.label}</span>
<span className="storage-alert-value">{alert.value}</span>
<span className="storage-alert-conclusion" data-tone={alert.tone}>
{alert.conclusion}
</span>
</li>
))}
</ul>
</section>
<section className="storage-batches" aria-label="备份批次">
<header>
<h3>备份批次</h3>
<span>{batches.length > 0 ? `共 ${batches.length} 个` : ''}</span>
</header>
{batches.length === 0 ? (
<p className="storage-batches-empty">
{state === 'ready' || state === 'incomplete'
? '暂无批次'
: `${hostValueLabel(state)}(上次上报 ${lastReport || UNKNOWN})`}
</p>
) : (
<table>
<thead>
<tr>
<th>时间</th>
<th>结果</th>
<th>大小</th>
<th>批次</th>
<th>路径</th>
<th aria-label="复制" />
</tr>
</thead>
<tbody>
{shown.map((batch) => {
const outcome = batchOutcome(batch)
return (
<tr key={batch.stamp}>
<td className="storage-batch-time">{batchWhen(batch)}</td>
<td>
<span
className={outcome.failed ? 'storage-batch-result is-failed' : 'storage-batch-result is-ok'}
>
{outcome.failed ? '失败' : '成功'}
</span>
{outcome.reasons.length > 0 ? (
<p className="storage-batch-reason">{outcome.reasons.join(';')}</p>
) : null}
</td>
<td className="storage-batch-size">{formatSize(batch.actual_bytes)}</td>
<td className="storage-batch-stamp">{batch.stamp}</td>
<td className="storage-batch-path" title={batch.path}>
<span>{batch.path}</span>
</td>
<td>
<button
type="button"
className="storage-copy"
onClick={() => handleCopy(batch.stamp, batch.path)}
aria-label={`复制路径 ${batch.stamp}`}
>
{copied === batch.stamp ? '已复制' : '复制'}
</button>
</td>
</tr>
)
})}
</tbody>
</table>
)}
{visible < batches.length ? (
<button type="button" className="storage-more" onClick={() => setVisible((value) => value + BATCH_PAGE)}>
加载更多(剩余 {batches.length - visible} 个)
</button>
) : null}
</section>
</>
)}
</section>
)
}
+2 -2
View File
@@ -256,9 +256,9 @@ describe('SystemSettingsView', () => {
initialSection="storage"
/>
)
// 存储与备份分区已换成真实功能(整库逻辑备份的定时计划),静态占位文案不再存在。
// 存储与备份分区是只读摘要页:SSR 先给加载态,静态占位文案不再存在。
expect(storageHtml).toContain('存储与备份')
expect(storageHtml).toContain('正在读取备份计划…')
expect(storageHtml).toContain('正在读取存储与备份…')
expect(storageHtml).not.toContain('仅保存凭据引用,不可回读')
const refreshHtml = renderToStaticMarkup(
<SystemSettingsView
+2 -8
View File
@@ -1,7 +1,6 @@
import { useCallback, useEffect, useState } from 'react'
import { BackupScheduleSection } from './BackupScheduleSection'
import { LibraryStorageSection } from './LibraryStorageSection'
import { StorageBackupSummary } from './StorageBackupSummary'
import { QAModelSettings } from './QAModelSettings'
import { MembersSection } from './MembersSection'
import { DingtalkAccountStatus, SourceManagementDetails, SourceSettingsCard } from './SourceManagement'
@@ -242,12 +241,7 @@ export function SystemSettingsView({
</details>
</>
) : null}
{section === 'storage' ? (
<>
<BackupScheduleSection />
<LibraryStorageSection />
</>
) : null}
{section === 'storage' ? <StorageBackupSummary /> : null}
{section === 'members' && identity?.role === 'admin' ? <MembersSection /> : null}
{section === 'refresh' && settings ? (
<section className="settings-panel wide" id="settings-refresh">
-87
View File
@@ -1,87 +0,0 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { fetchBackupSchedule, fetchBackupScheduleHost, runBackupNow, saveBackupSchedule } from './backupSchedule'
const payload = {
enabled: true,
schedule_time: '03:30',
retention_days: 7,
retention_months: 3,
updated_by: 'yaozhanghao',
updated_at: '2026-10-09T12:00:00Z',
last_applied_at: '',
last_applied_summary: '',
host_configured: true,
host_target: 'weknora-test',
host_reachable: true,
host_error: '',
host_schedule_enabled: true,
host_schedule_time: '03:30',
host_keep_days: 7,
host_keep_months: 3,
host_cron_lines: ['30 03 * * * root …'],
host_cron_service: 'active',
host_script_present: true,
last_run_stamp: '20261009T052909Z',
last_run_created_at: '2026-10-09T05:29:09Z',
last_run_duration_seconds: 33,
last_run_total_bytes: 778502144,
last_run_databases: ['weknora_test'],
last_run_failed_databases: [],
last_run_error: '',
in_sync: true,
applied: true,
apply_error: '',
running: false,
running_started_at: '',
run_last_error: '',
}
const jsonResponse = (body: unknown, status = 200) =>
new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } })
afterEach(() => {
vi.unstubAllGlobals()
})
describe('backupSchedule 客户端', () => {
it('解析计划三要素与主机回执', async () => {
vi.stubGlobal(
'fetch',
vi.fn(async () => jsonResponse({ data: payload }))
)
const schedule = await fetchBackupSchedule()
expect(schedule.schedule_time).toBe('03:30')
expect(schedule.retention_days).toBe(7)
expect(schedule.host_cron_lines).toHaveLength(1)
expect(schedule.last_run_failed_databases).toEqual([])
})
it('缺计划字段就报错,绝不把默认值伪装成真实设置', async () => {
const broken = { ...payload } as Record<string, unknown>
delete broken.retention_days
vi.stubGlobal(
'fetch',
vi.fn(async () => jsonResponse({ data: broken }))
)
await expect(fetchBackupScheduleHost()).rejects.toThrow('存储与备份响应缺少计划字段')
})
it('保存失败时把后端的中文原因透出来', async () => {
vi.stubGlobal(
'fetch',
vi.fn(async () => jsonResponse({ error: '储存天数需在 1~365 之间,收到 0' }, 400))
)
await expect(
saveBackupSchedule({ enabled: true, schedule_time: '03:30', retention_days: 0, retention_months: 3 })
).rejects.toThrow('储存天数需在 1~365 之间,收到 0')
})
it('立即备份返回 202 时识别为已启动', async () => {
vi.stubGlobal(
'fetch',
vi.fn(async () => jsonResponse({ data: { started: true, running: true } }, 202))
)
await expect(runBackupNow()).resolves.toEqual({ started: true, running: true })
})
})
-187
View File
@@ -1,187 +0,0 @@
import { newOperationID } from './operationKey'
// 「系统设置 → 存储与备份」:整库逻辑备份的定时计划(时间 + 储存天数)与主机回执。
export interface BackupSchedule {
enabled: boolean
schedule_time: string
retention_days: number
retention_months: number
updated_by: string
updated_at: string
last_applied_at: string
last_applied_summary: string
host_configured: boolean
host_target: string
// host_endpoint 是这条别名真实拨号的 host:port(来自挂载的 ssh 配置)。
host_endpoint: string
host_reachable: boolean
host_error: string
host_schedule_enabled: boolean
host_schedule_time: string
// 主机若没有返回真实 next-run,保持空串;页面不得用历史下发时间推算。
host_next_run?: string
host_checked_at?: string
host_keep_days: number
host_keep_months: number
host_cron_lines: string[]
host_cron_service: string
host_script_present: boolean
last_run_stamp: string
last_run_created_at: string
last_run_duration_seconds: number
last_run_total_bytes: number
last_run_databases: string[]
last_run_failed_databases: string[]
last_run_error: string
in_sync: boolean
applied: boolean
apply_error: string
running: boolean
running_started_at: string
run_last_error: string
}
export interface BackupRunStart {
started: boolean
running: boolean
}
const record = (value: unknown): value is Record<string, unknown> =>
Boolean(value) && typeof value === 'object' && !Array.isArray(value)
const asString = (value: unknown): string => (typeof value === 'string' ? value : '')
const asNumber = (value: unknown): number => (typeof value === 'number' && Number.isFinite(value) ? value : 0)
const asStringList = (value: unknown): string[] =>
Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string') : []
// 严格解析:计划三要素(时间/天数/月数)必须是正确类型,缺一个就整块报错,
// 而不是让界面显示成"默认 03:30 / 7 天"这种假状态。
function scheduleProjection(item: Record<string, unknown>): BackupSchedule {
if (
typeof item.schedule_time !== 'string' ||
typeof item.retention_days !== 'number' ||
typeof item.retention_months !== 'number'
) {
throw new Error('存储与备份响应缺少计划字段(schedule_time / retention_days / retention_months)')
}
return {
enabled: item.enabled === true,
schedule_time: item.schedule_time,
retention_days: item.retention_days,
retention_months: item.retention_months,
updated_by: asString(item.updated_by),
updated_at: asString(item.updated_at),
last_applied_at: asString(item.last_applied_at),
last_applied_summary: asString(item.last_applied_summary),
host_configured: item.host_configured === true,
host_target: asString(item.host_target),
host_endpoint: asString(item.host_endpoint),
host_reachable: item.host_reachable === true,
host_error: asString(item.host_error),
host_schedule_enabled: item.host_schedule_enabled === true,
host_schedule_time: asString(item.host_schedule_time),
host_next_run: asString(item.host_next_run),
host_checked_at: asString(item.host_checked_at),
host_keep_days: asNumber(item.host_keep_days),
host_keep_months: asNumber(item.host_keep_months),
host_cron_lines: asStringList(item.host_cron_lines),
host_cron_service: asString(item.host_cron_service),
host_script_present: item.host_script_present === true,
last_run_stamp: asString(item.last_run_stamp),
last_run_created_at: asString(item.last_run_created_at),
last_run_duration_seconds: asNumber(item.last_run_duration_seconds),
last_run_total_bytes: asNumber(item.last_run_total_bytes),
last_run_databases: asStringList(item.last_run_databases),
last_run_failed_databases: asStringList(item.last_run_failed_databases),
last_run_error: asString(item.last_run_error),
in_sync: item.in_sync === true,
applied: item.applied === true,
apply_error: asString(item.apply_error),
running: item.running === true,
running_started_at: asString(item.running_started_at),
run_last_error: asString(item.run_last_error),
}
}
async function readSchedule(path: string, failure: string, signal?: AbortSignal): Promise<BackupSchedule> {
const response = await fetch(path, { signal, headers: { Accept: 'application/json' } })
if (!response.ok) throw new Error(`${failure}(HTTP ${response.status})`)
const value = (await response.json()) as unknown
if (!record(value) || !record(value.data)) throw new Error('存储与备份响应无效')
return scheduleProjection(value.data)
}
export function fetchBackupSchedule(signal?: AbortSignal): Promise<BackupSchedule> {
return readSchedule('/api/v1/backup-schedule', '读取备份计划失败', signal)
}
// host 端点会 SSH 探测目标主机(计划 + 最近一次结果),单独调用以免拖慢首屏。
export function fetchBackupScheduleHost(signal?: AbortSignal): Promise<BackupSchedule> {
return readSchedule('/api/v1/backup-schedule/host', '读取目标主机上的备份状态失败', signal)
}
async function writeSchedule(
path: string,
method: string,
body: unknown,
failure: string,
signal?: AbortSignal
): Promise<BackupSchedule> {
const response = await fetch(path, {
method,
signal,
headers: { 'Content-Type': 'application/json', Accept: 'application/json', 'Idempotency-Key': newOperationID() },
body: body === undefined ? undefined : JSON.stringify(body),
})
if (!response.ok) {
let reason = `${failure}(HTTP ${response.status})`
try {
const payload = (await response.json()) as unknown
if (record(payload) && typeof payload.error === 'string') reason = payload.error
} catch {
/* keep the status text */
}
throw new Error(reason)
}
const value = (await response.json()) as unknown
if (!record(value) || !record(value.data)) throw new Error('存储与备份响应无效')
return scheduleProjection(value.data)
}
export interface BackupScheduleInput {
enabled: boolean
schedule_time: string
retention_days: number
retention_months: number
// 默认 true:保存后立刻下发到目标主机(页面按钮"保存并下发")。
apply?: boolean
}
export function saveBackupSchedule(input: BackupScheduleInput, signal?: AbortSignal): Promise<BackupSchedule> {
return writeSchedule('/api/v1/backup-schedule', 'PUT', input, '保存备份计划失败', signal)
}
export function applyBackupSchedule(signal?: AbortSignal): Promise<BackupSchedule> {
return writeSchedule('/api/v1/backup-schedule/apply', 'POST', undefined, '下发备份计划失败', signal)
}
export async function runBackupNow(signal?: AbortSignal): Promise<BackupRunStart> {
const response = await fetch('/api/v1/backup-schedule/run', {
method: 'POST',
signal,
headers: { Accept: 'application/json', 'Idempotency-Key': newOperationID() },
})
if (!response.ok) {
let reason = `触发备份失败(HTTP ${response.status})`
try {
const payload = (await response.json()) as unknown
if (record(payload) && typeof payload.error === 'string') reason = payload.error
} catch {
/* keep the status text */
}
throw new Error(reason)
}
const value = (await response.json()) as unknown
if (!record(value) || !record(value.data)) throw new Error('触发备份响应无效')
return { started: value.data.started === true, running: value.data.running === true }
}
-99
View File
@@ -1,99 +0,0 @@
.library-storage {
border: 1px solid var(--border-base, #e2e8f0);
border-radius: 10px;
padding: 16px 18px;
margin-bottom: 18px;
background: #fff;
}
.library-storage header h3 {
margin: 0 0 4px;
font-size: 16px;
}
.library-storage header p {
margin: 0 0 12px;
font-size: 12px;
color: var(--ink-mute, #64748b);
line-height: 1.6;
}
.library-storage-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
gap: 10px;
margin: 0 0 12px;
}
.library-storage-grid div {
border: 1px solid #e6edf2;
border-radius: 8px;
padding: 9px 11px;
}
.library-storage-grid dt {
font-size: 11px;
color: var(--ink-mute, #64748b);
}
.library-storage-grid dd {
margin: 3px 0 0;
font-size: 16px;
font-variant-numeric: tabular-nums;
}
.library-storage-limits {
margin: 0;
padding-left: 18px;
font-size: 12px;
color: #986b24;
line-height: 1.8;
}
.library-storage-hint {
margin: 0;
font-size: 12px;
color: var(--ink-mute, #64748b);
}
.library-storage-blocked {
border: 1px solid #f3c2b8;
background: #fff6f3;
border-radius: 8px;
padding: 10px 12px;
margin-bottom: 10px;
}
.library-storage-blocked strong {
display: block;
font-size: 12px;
color: #a03a1e;
}
.library-storage-blocked p {
margin: 2px 0 0;
font-size: 12px;
color: #7c2d12;
}
.library-storage-panel {
border: 1px solid #e6edf2;
border-radius: 8px;
padding: 10px 12px;
margin-bottom: 10px;
}
.library-storage-panel h4 {
margin: 0 0 6px;
font-size: 13px;
}
.library-storage-panel p {
margin: 0 0 6px;
font-size: 12px;
line-height: 1.7;
color: #3f5566;
}
.library-storage-warn {
color: #986b24 !important;
}
.library-storage-versions {
margin: 4px 0 0;
padding-left: 18px;
font-size: 12px;
line-height: 1.8;
color: #3f5566;
}
.library-storage-blocked-list {
margin: 4px 0 0;
padding-left: 18px;
font-size: 12px;
color: #a03a1e;
}
+320 -372
View File
@@ -1,424 +1,372 @@
/* 「系统设置 → 存储与备份」:数据库整库逻辑备份。
原型里的单条整盘图与告警在这里保留位置;真实读数未接线时用虚底而不是假容量。 */
.storage-settings-panel {
/* 存储与备份:只读摘要页。全部颜色走 tokens,状态色沿用全局 fail/warn/done。 */
.storage-summary {
display: flex;
flex-direction: column;
gap: 14px;
gap: 18px;
}
.storage-settings-panel .settings-section-heading p {
.storage-summary-head {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 16px;
flex-wrap: wrap;
}
.storage-summary-head h2 {
margin: 0;
max-width: 78ch;
color: var(--ink-mute, #64748b);
font-size: 11px;
line-height: 1.7;
font-size: 16px;
color: var(--ink-strong);
}
/* 主机读回用两栏事实表;窄列时自动落成一栏,避免 dd 把 dt 挤成竖排。 */
.settings-panel .storage-settings-grid {
grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
.storage-summary-state {
margin: 4px 0 0;
font-size: 12px;
color: var(--c-warn);
}
.settings-panel .storage-settings-grid > dl {
grid-template-columns: minmax(104px, max-content) minmax(0, 1fr);
.storage-summary-meta {
display: flex;
align-items: center;
gap: 12px;
font-size: 12px;
color: var(--ink-mute);
}
.storage-settings-panel code {
.storage-refresh,
.storage-more {
border: 1px solid var(--border-strong);
background: var(--bg-panel);
border-radius: 6px;
padding: 5px 12px;
font-size: 12px;
color: var(--ink-base);
cursor: pointer;
}
.storage-refresh:hover,
.storage-more:hover {
background: var(--bg-hover);
}
.storage-refresh:disabled {
color: var(--ink-faint);
cursor: default;
}
.storage-summary-error {
margin: 0;
padding: 8px 12px;
border-radius: 6px;
border: 1px solid var(--c-fail-border);
background: var(--c-fail-bg);
color: var(--c-fail);
font-size: 12px;
}
.storage-summary-loading {
margin: 0;
font-size: 13px;
color: var(--ink-mute);
}
.storage-cards {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(190px, 1fr));
gap: 12px;
}
.storage-card {
border: 1px solid var(--border-base);
border-radius: 10px;
background: var(--bg-panel);
padding: 14px 16px;
display: flex;
flex-direction: column;
gap: 6px;
min-width: 0;
}
.storage-card-label {
font-size: 12px;
color: var(--ink-mute);
}
.storage-card-value {
font-size: 24px;
font-weight: 600;
line-height: 1.15;
color: var(--ink-strong);
overflow-wrap: anywhere;
}
.storage-block {
border-top: 1px solid var(--border-base, #e2e8f0);
padding-top: 12px;
.storage-card-value.is-unknown {
font-size: 15px;
font-weight: 500;
color: var(--ink-mute);
}
.storage-block-heading {
/* 备份目录是配置事实而不是指标:独占一行、字号收小,避免长路径撑爆卡片。 */
.storage-card-root {
grid-column: 1 / -1;
}
.storage-card-root .storage-card-value {
font-size: 16px;
line-height: 1.35;
overflow-wrap: anywhere;
}
.storage-card-note {
display: flex;
align-items: center;
gap: 8px;
font-size: 12px;
color: var(--ink-mute);
min-height: 18px;
}
.storage-copy {
border: 1px solid var(--border-base);
background: var(--bg-soft);
border-radius: 5px;
padding: 1px 7px;
font-size: 11px;
color: var(--ink-mute);
cursor: pointer;
flex: none;
}
.storage-copy:hover {
background: var(--bg-hover);
color: var(--ink-base);
}
.storage-alerts,
.storage-batches {
border: 1px solid var(--border-base);
border-radius: 10px;
background: var(--bg-panel);
overflow: hidden;
}
.storage-alerts > header,
.storage-batches > header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px 14px;
flex-wrap: wrap;
margin-bottom: 6px;
gap: 12px;
padding: 12px 16px;
border-bottom: 1px solid var(--border-soft);
}
.storage-block-heading h3 {
.storage-alerts h3,
.storage-batches h3 {
margin: 0;
font-size: 13px;
color: var(--ink-base);
color: var(--ink-strong);
}
.storage-block-heading button {
font: inherit;
font-size: 10px;
padding: 3px 9px;
border-radius: 5px;
border: 1px solid var(--border-base, #cbd5e1);
background: var(--bg-panel, #fff);
color: inherit;
cursor: pointer;
.storage-batches > header span,
.storage-alert-count {
font-size: 12px;
color: var(--ink-mute);
}
.storage-block-heading button:disabled {
opacity: 0.55;
cursor: default;
}
.storage-chip {
border-radius: 999px;
padding: 2px 9px;
font-size: 10px;
border: 1px solid var(--border-base, #e2e8f0);
color: var(--ink-mute, #64748b);
}
.storage-chip.ok {
color: #17695a;
border-color: #a9d5c8;
background: #effaf5;
}
.storage-chip.warn {
color: #985d10;
border-color: #f0d3a4;
background: #fff8ec;
}
.storage-chip.off {
color: var(--ink-mute, #64748b);
background: var(--bg-soft, #f6f8fa);
}
.settings-panel .storage-facts {
display: grid;
grid-template-columns: minmax(96px, max-content) minmax(0, 1fr);
gap: 5px 14px;
margin: 6px 0;
font-size: 11px;
color: var(--ink-mute, #64748b);
}
.settings-panel .storage-facts dd {
margin: 0;
color: var(--ink-base);
overflow-wrap: anywhere;
}
.storage-inline-note {
display: block;
color: var(--ink-mute, #64748b);
font-size: 10px;
}
.storage-block-actions {
display: flex;
align-items: center;
gap: 8px 12px;
flex-wrap: wrap;
margin: 7px 0;
}
.storage-block-actions .hint {
max-width: 72ch;
}
.storage-block-actions button {
font: inherit;
font-size: 11px;
padding: 5px 11px;
border-radius: 6px;
border: 1px solid var(--border-base, #cbd5e1);
background: var(--bg-panel, #fff);
color: inherit;
cursor: pointer;
}
.storage-block-actions button:disabled {
opacity: 0.55;
cursor: default;
}
.storage-block-actions button.primary {
background: #185f78;
border-color: #185f78;
color: #fff;
}
.storage-progress {
margin: 6px 0;
}
.storage-running {
margin: 0 0 5px;
font-size: 11px;
color: var(--ink-base);
}
.storage-progress-bar {
width: 100%;
height: 10px;
}
.storage-disk-track {
display: flex;
height: 22px;
margin: 8px 0;
border-radius: 5px;
overflow: hidden;
background: #e4e9ef;
outline: 1px solid #aab9c1;
}
.storage-disk-other {
background: #77889a;
}
.storage-disk-zone {
display: flex;
background: #c0dfed;
box-shadow: inset 0 0 0 1px #6191a8;
}
.storage-disk-used {
background: #19698c;
}
.storage-disk-blank {
background: #e4e9ef;
}
.storage-disk-track-unknown {
display: flex;
align-items: center;
justify-content: center;
background: repeating-linear-gradient(45deg, #eef2f5 0 6px, #e1e7eb 6px 12px);
border: 1px dashed #aab9c1;
outline: none;
color: #576674;
font-size: 10px;
}
.storage-disk-low .storage-disk-other {
background: #9d625d;
}
.storage-disk-low .storage-disk-used {
background: #be6c10;
}
.storage-disk-low .storage-disk-zone {
background: #ffe0a8;
}
.storage-disk-legend {
display: flex;
gap: 6px 16px;
flex-wrap: wrap;
font-size: 10px;
color: #3f5566;
}
.storage-dot {
display: inline-block;
width: 10px;
height: 10px;
margin-right: 4px;
border-radius: 2px;
vertical-align: -1px;
}
.storage-dot.other {
background: #77889a;
}
.storage-dot.used {
background: #19698c;
}
.storage-dot.zone {
background: #c0dfed;
}
.storage-dot.blank {
background: #e4e9ef;
outline: 1px solid #c4ced6;
}
.storage-metric {
margin: 6px 0 2px;
font-size: 11px;
.storage-alert-count.is-pending {
color: var(--c-fail);
font-weight: 600;
}
.storage-manifest {
font-size: 10px;
padding: 1px 7px;
border-radius: 999px;
border: 1px solid var(--border-base, #e2e8f0);
}
.storage-manifest.ok {
color: #17695a;
border-color: #a9d5c8;
background: #effaf5;
}
.storage-manifest.missing,
.storage-manifest.invalid {
color: #a03a1e;
border-color: #f3c2b8;
background: #fff6f3;
}
.storage-path-row {
display: grid;
grid-template-columns: max-content minmax(0, 1fr) max-content;
gap: 4px 8px;
align-items: center;
margin: 5px 0;
}
.storage-path-row small {
color: var(--ink-mute, #64748b);
}
.storage-path-row code {
font-size: 10px;
padding: 3px 6px;
border-radius: 4px;
background: var(--bg-soft, #f6f8fa);
overflow-wrap: anywhere;
}
.storage-path-row button,
.storage-sublibraries button {
font: inherit;
font-size: 10px;
padding: 3px 8px;
border-radius: 5px;
border: 1px solid var(--border-base, #cbd5e1);
background: var(--bg-panel, #fff);
color: inherit;
cursor: pointer;
}
.storage-path-row button:disabled,
.storage-sublibraries button:disabled {
opacity: 0.55;
cursor: default;
}
.storage-sublibrary-path {
margin: 2px 0 0;
grid-template-columns: minmax(0, 1fr) max-content;
}
.storage-alert-summary {
margin: 8px 0 0;
font-size: 11px;
font-weight: 600;
color: #3f5566;
}
.storage-alerts {
.storage-alerts ul {
list-style: none;
margin: 8px 0 0;
margin: 0;
padding: 0;
display: grid;
gap: 5px;
}
.storage-alerts li {
display: grid;
grid-template-columns: max-content max-content minmax(0, 1fr);
gap: 4px 10px;
align-items: baseline;
font-size: 10px;
padding: 4px 8px;
border-radius: 6px;
background: var(--bg-soft, #f6f8fa);
grid-template-columns: 180px minmax(0, 1fr) 84px;
gap: 12px;
align-items: center;
padding: 10px 16px;
border-bottom: 1px solid var(--border-soft);
font-size: 13px;
}
.storage-alerts li strong {
font-size: 11px;
.storage-alerts li:last-child {
border-bottom: none;
}
.storage-alerts li small {
color: var(--ink-mute, #64748b);
.storage-alert-label {
color: var(--ink-base);
}
.storage-alert-value {
color: var(--ink-mute);
overflow-wrap: anywhere;
}
.storage-alerts .alert-on {
background: #fff1ec;
color: #a03a1e;
.storage-alert-conclusion {
justify-self: end;
border-radius: 999px;
padding: 2px 10px;
font-size: 12px;
border: 1px solid var(--border-base);
color: var(--ink-mute);
background: var(--bg-soft);
}
.storage-alerts .alert-ok {
background: #f0faf6;
color: #17695a;
.storage-alert-conclusion[data-tone='ok'] {
color: var(--c-done);
border-color: var(--c-done-border);
background: var(--c-done-bg);
}
.storage-alerts .alert-unknown {
background: #f8f5ee;
color: #715c2c;
.storage-alert-conclusion[data-tone='warn'] {
color: var(--c-warn);
border-color: var(--c-warn-border);
background: var(--c-warn-bg);
}
.storage-plan {
margin: 4px 0;
font-size: 11px;
color: #3f5566;
.storage-alert-conclusion[data-tone='bad'] {
color: var(--c-fail);
border-color: var(--c-fail-border);
background: var(--c-fail-bg);
}
.storage-policy-editor {
display: flex;
flex-direction: column;
gap: 8px;
margin-top: 6px;
}
.storage-policy-editor > label {
display: grid;
gap: 3px;
font-size: 10px;
color: var(--ink-mute, #64748b);
}
.storage-policy-editor input[type='text'],
.storage-policy-editor input[type='time'],
.storage-policy-editor input[type='number'] {
.storage-batches table {
width: 100%;
max-width: 320px;
font: inherit;
font-size: 11px;
padding: 5px 8px;
border-radius: 5px;
border: 1px solid var(--border-base, #cbd5e1);
background: var(--bg-panel, #fff);
color: inherit;
border-collapse: collapse;
font-size: 12px;
table-layout: fixed;
}
.storage-policy-editor input:disabled {
background: var(--bg-soft, #f1f4f6);
color: var(--ink-mute, #64748b);
.storage-batches th {
text-align: left;
font-weight: 500;
color: var(--ink-mute);
padding: 8px 16px;
border-bottom: 1px solid var(--border-soft);
}
.storage-checkbox {
display: flex !important;
align-items: center;
gap: 6px;
font-size: 11px !important;
color: var(--ink-base) !important;
.storage-batches td {
padding: 10px 16px;
border-bottom: 1px solid var(--border-soft);
vertical-align: top;
color: var(--ink-base);
}
.storage-policy-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
gap: 8px 12px;
.storage-batches th:nth-child(1),
.storage-batches td:nth-child(1) {
width: 96px;
}
.storage-policy-grid label {
display: grid;
gap: 3px;
font-size: 10px;
color: var(--ink-mute, #64748b);
.storage-batches th:nth-child(2),
.storage-batches td:nth-child(2) {
width: 200px;
}
.storage-policy-grid input {
width: 100%;
.storage-batches th:nth-child(3),
.storage-batches td:nth-child(3) {
width: 88px;
}
.storage-batch {
border: 1px solid var(--border-base, #e2e8f0);
border-radius: 8px;
padding: 8px 10px;
.storage-batches th:nth-child(4),
.storage-batches td:nth-child(4) {
width: 170px;
}
.storage-batches th:nth-child(6),
.storage-batches td:nth-child(6) {
width: 64px;
}
.storage-batch-time,
.storage-batch-stamp {
font-variant-numeric: tabular-nums;
white-space: nowrap;
}
.storage-batch-size {
white-space: nowrap;
}
.storage-batch-result {
display: inline-block;
border-radius: 999px;
padding: 1px 9px;
border: 1px solid var(--border-base);
font-size: 11px;
}
.storage-batch summary {
display: flex;
gap: 6px 14px;
flex-wrap: wrap;
align-items: baseline;
cursor: pointer;
.storage-batch-result.is-ok {
color: var(--c-done);
border-color: var(--c-done-border);
background: var(--c-done-bg);
}
.storage-batch summary strong.ok {
color: #17695a;
.storage-batch-result.is-failed {
color: var(--c-fail);
border-color: var(--c-fail-border);
background: var(--c-fail-bg);
}
.storage-batch summary strong.off {
color: #a03a1e;
.storage-batch-reason {
margin: 4px 0 0;
font-size: 11px;
color: var(--c-fail);
white-space: normal;
overflow-wrap: anywhere;
}
.storage-batch p {
margin: 6px 0;
color: #3f5566;
/* 长路径中间截断:保留结尾(批次目录名),从开头省略。 */
.storage-batch-path {
min-width: 0;
}
.storage-sublibraries {
list-style: none;
margin: 6px 0;
padding: 0;
display: grid;
gap: 4px;
.storage-batch-path > span {
display: block;
direction: rtl;
unicode-bidi: plaintext;
text-align: left;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
color: var(--ink-mute);
}
.storage-sublibraries li {
display: grid;
grid-template-columns: minmax(120px, max-content) max-content minmax(0, 1fr);
gap: 4px 10px;
align-items: baseline;
padding: 3px 6px;
border-radius: 5px;
background: var(--bg-soft, #f6f8fa);
.storage-batches-empty {
margin: 0;
padding: 24px 16px;
font-size: 13px;
color: var(--ink-mute);
text-align: center;
}
.storage-sublibrary-path {
grid-column: 1 / -1;
.storage-more {
display: block;
margin: 12px auto;
}
.storage-sublibraries .ok {
color: #17695a;
}
.storage-sublibraries .off {
color: #a03a1e;
}
.storage-sublibraries small {
color: var(--ink-mute, #64748b);
}
.storage-verify {
margin: 6px 0 0;
color: #715c2c;
font-size: 10px;
}
@media (max-width: 700px) {
.storage-facts,
.storage-sublibraries li,
@media (max-width: 720px) {
.storage-alerts li {
grid-template-columns: minmax(0, 1fr);
grid-template-columns: minmax(0, 1fr) 84px;
}
.storage-alerts .storage-alert-value {
grid-column: 1 / -1;
grid-row: 2;
}
.storage-batches table {
table-layout: auto;
}
.storage-batches th:nth-child(4),
.storage-batches td:nth-child(4),
.storage-batches th:nth-child(5),
.storage-batches td:nth-child(5) {
display: none;
}
}
+308
View File
@@ -0,0 +1,308 @@
import { describe, expect, it } from 'vitest'
import type { BackupInventory, BackupInventoryBatch } from './backupInventory'
import type { LibraryStorage } from './librarySnapshots'
import {
DISK_CRITICAL_AVAILABLE_PERCENT,
batchOutcome,
formatSize,
formatWhen,
hostState,
orderedBatches,
pendingAlertCount,
recentOutcome,
storageAlerts,
summaryCards,
} from './storageSummary'
const GIB = 1024 ** 3
const TB = 1024 * GIB
export const batch = (overrides: Partial<BackupInventoryBatch> = {}): BackupInventoryBatch => ({
stamp: '20261124T020000Z',
path: '/srv/kb-backups/rds-logical/20261124T020000Z',
host_path: '/srv/kb-backups/rds-logical/20261124T020000Z',
manifest_state: 'ok',
manifest_path: '/srv/kb-backups/rds-logical/20261124T020000Z/MANIFEST.json',
kind: 'rds',
created_at: '2026-11-24T02:00:00Z',
started_at: '2026-11-24T02:00:00Z',
duration_seconds: 240,
manifest_total_bytes: 10 * GIB,
apparent_bytes: 10 * GIB,
actual_bytes: 9 * GIB,
file_count: 120,
sizes_complete: true,
databases: [
{
name: 'weknora',
dir_name: 'weknora.dir',
path: '/srv/kb-backups/rds-logical/20261124T020000Z/weknora.dir',
host_path: '/srv/kb-backups/rds-logical/20261124T020000Z/weknora.dir',
present: true,
failed: false,
in_manifest: true,
apparent_bytes: 10 * GIB,
actual_bytes: 9 * GIB,
file_count: 120,
},
],
...overrides,
})
export const inventory = (overrides: Partial<BackupInventory> = {}): BackupInventory => ({
wired: true,
metadata: {
configured: true,
present: true,
valid: true,
fresh: true,
complete: true,
path: '/var/lib/kb-backups/metadata.json',
collected_at: '2026-11-24T10:17:00Z',
age_seconds: 60,
max_age_seconds: 900,
schema_version: 1,
generation: 'g-1',
host: 'backup-host',
collector_version: '1',
error: '',
},
root: '/srv/kb-backups/rds-logical',
host_root: '/srv/kb-backups/rds-logical',
source: 'host',
observed_at: '2026-11-24T10:18:00Z',
measurement: 'host-reported',
mount: {
container_root: '',
mount_verified: true,
lives_on_container_root: false,
read_only: true,
evidence: '',
mount_point: '/srv/kb-backups',
device: '/dev/sdb1',
fs_type: 'ext4',
},
capacity: {
measured: true,
total_bytes: 2 * TB,
free_bytes: 1.2 * TB,
available_bytes: 1.2 * TB,
used_bytes: 0.8 * TB,
},
batches: [batch()],
totals: {
batch_count: 1,
database_count: 1,
apparent_bytes: 10 * GIB,
actual_bytes: 9 * GIB,
latest_stamp: '20261124T020000Z',
latest_actual_bytes: 9 * GIB,
complete: true,
},
incomplete_count: 0,
skipped: [],
truncated: false,
...overrides,
})
export const archive = (overrides: Partial<LibraryStorage> = {}): LibraryStorage => ({
available: true,
archive_root: '/var/lib/knowledge-governance/library',
versions: [],
content_bytes: 41_231_686_042,
blob_file_bytes: 0,
blob_allocated_bytes: 0,
unreferenced_blobs: 0,
unreferenced_bytes: 0,
manifest_file_bytes: 0,
policy: { keep_versions: 0, keep_days: 0 },
capacity: {
budget_bytes: 100 * GIB,
current_bytes: 41_231_686_042,
required_bytes: 0,
projected_bytes: 41_231_686_042,
configured: true,
ok: true,
},
automatic_cleanup: false,
notes: [],
...overrides,
})
const unreported = (): BackupInventory =>
inventory({
wired: false,
metadata: {
configured: false,
present: false,
valid: false,
fresh: false,
complete: false,
path: '',
collected_at: '',
age_seconds: 0,
max_age_seconds: 900,
schema_version: 0,
generation: '',
host: '',
collector_version: '',
error: '元数据快照未接线(BACKUP_HOST_METADATA_PATH 未设置)',
},
root: '',
host_root: '',
capacity: { measured: false, total_bytes: 0, free_bytes: 0, available_bytes: 0, used_bytes: 0 },
batches: [],
totals: {
batch_count: 0,
database_count: 0,
apparent_bytes: null,
actual_bytes: null,
latest_stamp: '',
latest_actual_bytes: null,
complete: false,
},
})
describe('formatSize', () => {
it('keeps one decimal below 100 units and never calls an unknown value zero', () => {
expect(formatSize(41_231_686_042)).toBe('38.4 GB')
expect(formatSize(100 * GIB)).toBe('100 GB')
expect(formatSize(1.2 * TB)).toBe('1.2 TB')
expect(formatSize(2 * TB)).toBe('2 TB')
expect(formatSize(0)).toBe('0 B')
expect(formatSize(null)).toBe('—')
expect(formatSize(undefined)).toBe('—')
})
})
describe('hostState', () => {
it('separates unreported, stale, incomplete and ready snapshots', () => {
expect(hostState(null)).toBe('loading')
expect(hostState(unreported())).toBe('unwired')
expect(hostState(inventory({ metadata: { ...inventory().metadata, present: false } }))).toBe('missing')
expect(hostState(inventory({ metadata: { ...inventory().metadata, fresh: false } }))).toBe('stale')
expect(hostState(inventory({ metadata: { ...inventory().metadata, complete: false } }))).toBe('incomplete')
expect(hostState(inventory())).toBe('ready')
})
})
describe('batchOutcome', () => {
it('reports manifest damage and failed databases as failure reasons', () => {
expect(batchOutcome(batch())).toEqual({ failed: false, reasons: [] })
expect(batchOutcome(batch({ manifest_state: 'missing' })).reasons).toEqual(['清单缺失'])
expect(
batchOutcome(
batch({
manifest_state: 'invalid',
manifest_error: 'MANIFEST.json 无法解析',
databases: [{ ...batch().databases[0], failed: true }],
})
)
).toEqual({ failed: true, reasons: ['清单损坏', 'MANIFEST.json 无法解析', '子库失败:weknora'] })
})
})
describe('recentOutcome', () => {
it('uses the newest batch per outcome and counts only the 7 day window', () => {
const now = Date.parse('2026-11-24T12:00:00Z')
const outcome = recentOutcome(
[
batch({ stamp: '20261124T020000Z', created_at: '2026-11-24T02:00:00Z' }),
batch({ stamp: '20261123T020000Z', created_at: '2026-11-23T02:00:00Z', manifest_state: 'invalid' }),
batch({ stamp: '20261101T020000Z', created_at: '2026-11-01T02:00:00Z', manifest_state: 'missing' }),
],
now
)
expect(outcome.latestSuccessAt).toBe(formatWhen('2026-11-24T02:00:00Z'))
expect(outcome.latestFailureAt).toBe(formatWhen('2026-11-23T02:00:00Z'))
expect(outcome.successCount).toBe(1)
expect(outcome.failureCount).toBe(1)
})
it('orders batches by time even when the host sends them unsorted', () => {
const ordered = orderedBatches([
batch({ stamp: '20261122T020000Z', created_at: '2026-11-22T02:00:00Z' }),
batch({ stamp: '20261124T020000Z', created_at: '2026-11-24T02:00:00Z' }),
])
expect(ordered.map((item) => item.stamp)).toEqual(['20261124T020000Z', '20261122T020000Z'])
})
})
describe('summaryCards', () => {
it('shows real values when the host reported and the archive is available', () => {
const cards = summaryCards(inventory(), archive(), false)
const byKey = Object.fromEntries(cards.map((card) => [card.key, card.value]))
expect(byKey.root).toBe('/srv/kb-backups/rds-logical')
expect(byKey.success).toBe(formatWhen('2026-11-24T02:00:00Z'))
expect(byKey.failure).toBe('无')
expect(byKey.archive).toBe('38.4 GB')
expect(byKey.disk).toBe('1.2 TB')
expect(cards.find((card) => card.key === 'archive')?.note).toBe('配额 100 GB')
})
it('shows 主机未上报 with the last report time instead of 0 when the host never reported', () => {
const cards = summaryCards(unreported(), archive({ available: false }), false)
for (const key of ['root', 'success', 'failure', 'disk']) {
const card = cards.find((item) => item.key === key)!
expect(card.value).toBe('主机未上报')
expect(card.note).toBe('上次上报 —')
}
expect(cards.find((card) => card.key === 'archive')?.value).toBe('—')
expect(cards.some((card) => card.value === '0 B')).toBe(false)
})
it('keeps paths readable but leaves sizes empty for an incomplete report', () => {
const cards = summaryCards(inventory({ metadata: { ...inventory().metadata, complete: false } }), archive(), false)
expect(cards.find((card) => card.key === 'root')?.value).toBe('/srv/kb-backups/rds-logical')
expect(cards.find((card) => card.key === 'disk')?.value).toBe('—')
expect(cards.find((card) => card.key === 'disk')?.note).toBe('本次上报不完整')
})
})
describe('storageAlerts', () => {
it('judges disk and quota independently and counts pending rows', () => {
const healthy = storageAlerts(inventory(), archive(), false)
expect(healthy.map((row) => row.conclusion)).toEqual(['正常', '正常', '正常', '正常'])
expect(pendingAlertCount(healthy)).toBe(0)
const nearQuota = storageAlerts(
inventory(),
archive({
capacity: { ...archive().capacity, current_bytes: 95 * GIB, budget_bytes: 100 * GIB },
}),
false
)
expect(nearQuota.find((row) => row.key === 'quota_low')?.tone).toBe('warn')
expect(nearQuota.find((row) => row.key === 'both_low')?.conclusion).toBe('正常')
expect(pendingAlertCount(nearQuota)).toBe(1)
})
it('flags both-insufficient and quota larger than physical free space', () => {
const tight = storageAlerts(
inventory({
capacity: {
measured: true,
total_bytes: 2 * TB,
free_bytes: 0.01 * TB,
available_bytes: 0.01 * TB,
used_bytes: 1.99 * TB,
},
}),
archive({ capacity: { ...archive().capacity, current_bytes: 100 * GIB, budget_bytes: 100 * GIB } }),
false
)
expect(tight.find((row) => row.key === 'disk_low')?.tone).toBe('bad')
expect(tight.find((row) => row.key === 'both_low')?.conclusion).toBe('需处理')
expect(tight.find((row) => row.key === 'quota_over_physical')?.conclusion).toBe('需处理')
expect(pendingAlertCount(tight)).toBe(4)
expect(DISK_CRITICAL_AVAILABLE_PERCENT).toBe(5)
})
it('never claims a conclusion without numbers', () => {
const alerts = storageAlerts(unreported(), null, true)
expect(alerts.every((row) => row.conclusion === '未知')).toBe(true)
expect(alerts.find((row) => row.key === 'disk_low')?.value).toBe('主机未上报')
expect(alerts.some((row) => row.value.includes('无法判定'))).toBe(false)
})
})
+348
View File
@@ -0,0 +1,348 @@
// 「存储与备份」只读摘要的纯逻辑:数据源只有两个只读接口——
// /api/v1/backup-schedule/inventory (宿主每 5 分钟上报的元数据快照)
// /api/v1/library/storage (归档库自身的占用与配额)
// 页面不提供任何写操作。读不到的量一律留空("主机未上报" / "—"),不用 0 冒充。
import type { BackupInventory, BackupInventoryBatch } from './backupInventory'
import type { LibraryStorage } from './librarySnapshots'
// 阈值(与 docs/STORAGE_BACKUP_READONLY_API.md 的「页面口径」一致):
// 磁盘:可用空间 < 5% 红,< 10% 黄
// 配额:已用 >= 100% 红,>= 90% 黄
export const DISK_CRITICAL_AVAILABLE_PERCENT = 5
export const DISK_WARN_AVAILABLE_PERCENT = 10
export const QUOTA_CRITICAL_USED_PERCENT = 100
export const QUOTA_WARN_USED_PERCENT = 90
export const RECENT_WINDOW_DAYS = 7
export type Tone = 'ok' | 'warn' | 'bad' | 'none'
export type HostState = 'loading' | 'unwired' | 'missing' | 'stale' | 'invalid' | 'incomplete' | 'ready'
// 陈旧在先:stale 的快照会被后端判为 invalid,但"上次上报时间"仍然可读。
export const hostState = (inventory: BackupInventory | null): HostState => {
if (!inventory) return 'loading'
if (!inventory.wired) return 'unwired'
if (!inventory.metadata.present) return 'missing'
if (!inventory.metadata.fresh) return 'stale'
if (!inventory.metadata.valid) return 'invalid'
if (!inventory.metadata.complete) return 'incomplete'
return 'ready'
}
export const UNREPORTED = '主机未上报'
// 没有可用的上报表时的说法要和真实原因一致:未接入/从未上报、过期、不可用是三件事。
export const hostValueLabel = (state: HostState): string => {
switch (state) {
case 'unwired':
case 'missing':
return UNREPORTED
case 'stale':
return '上报已过期'
case 'invalid':
return '上报不可用'
default:
return UNKNOWN
}
}
export const UNKNOWN = '—'
// 结论未知与数值缺失是两件事:数值缺用“—”,无法判断结论用“未知”。
export const UNKNOWN_STATE = '未知'
const UNITS = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'] as const
export function formatSize(bytes: number | null | undefined): string {
if (bytes === null || bytes === undefined || !Number.isFinite(bytes) || bytes < 0) return UNKNOWN
if (bytes === 0) return '0 B'
let value = bytes
let index = 0
while (value >= 1024 && index < UNITS.length - 1) {
value /= 1024
index += 1
}
const digits = index === 0 || value >= 100 ? 0 : 1
const text = value.toFixed(digits).replace(/\.0$/, '')
return `${text} ${UNITS[index]}`
}
// 本地时间 MM/DD HH:mm;无法解析时返回空串,由调用方显示 "—"。
export function formatWhen(value: string | null | undefined): string {
if (!value) return ''
const date = new Date(value)
if (Number.isNaN(date.getTime())) return ''
return `${String(date.getMonth() + 1).padStart(2, '0')}/${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}
const STAMP = /^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z?$/
const stampTime = (stamp: string): number => {
const match = STAMP.exec(stamp)
if (!match) return 0
return Date.UTC(+match[1], +match[2] - 1, +match[3], +match[4], +match[5], +match[6])
}
export function batchWhen(batch: BackupInventoryBatch): string {
const iso = formatWhen(batch.created_at) || formatWhen(batch.started_at)
if (iso) return iso
const parsed = stampTime(batch.stamp)
return parsed ? formatWhen(new Date(parsed).toISOString()) || UNKNOWN : UNKNOWN
}
const batchTime = (batch: BackupInventoryBatch): number => {
const created = Date.parse(batch.created_at)
if (!Number.isNaN(created)) return created
const started = Date.parse(batch.started_at)
if (!Number.isNaN(started)) return started
return stampTime(batch.stamp)
}
export function orderedBatches(batches: BackupInventoryBatch[]): BackupInventoryBatch[] {
return [...batches].sort((left, right) => batchTime(right) - batchTime(left))
}
export interface BatchOutcome {
failed: boolean
reasons: string[]
}
// 失败判定:任一子库失败、清单缺失或损坏都算失败。宿主上报里没有自由文本原因,
// 页面只写能证明的事实(清单状态、失败子库名),不编造原因。
export function batchOutcome(batch: BackupInventoryBatch): BatchOutcome {
const reasons: string[] = []
if (batch.manifest_state === 'missing') reasons.push('清单缺失')
if (batch.manifest_state === 'invalid') reasons.push('清单损坏')
const manifestError = batch.manifest_error?.trim()
if (manifestError) reasons.push(manifestError)
const failedDatabases = batch.databases.filter((database) => database.failed).map((database) => database.name)
if (failedDatabases.length > 0) reasons.push(`子库失败:${failedDatabases.join('、')}`)
return { failed: reasons.length > 0, reasons }
}
export interface RecentOutcome {
latestSuccessAt: string
latestFailureAt: string
successCount: number
failureCount: number
}
export function recentOutcome(batches: BackupInventoryBatch[], now: number = Date.now()): RecentOutcome {
const windowStart = now - RECENT_WINDOW_DAYS * 24 * 60 * 60 * 1000
let latestSuccessAt = ''
let latestFailureAt = ''
let successCount = 0
let failureCount = 0
for (const batch of orderedBatches(batches)) {
const failed = batchOutcome(batch).failed
const when = batchWhen(batch)
const at = batchTime(batch)
if (failed) {
if (!latestFailureAt) latestFailureAt = when
} else if (!latestSuccessAt) {
latestSuccessAt = when
}
if (at >= windowStart) {
if (failed) failureCount += 1
else successCount += 1
}
}
return { latestSuccessAt, latestFailureAt, successCount, failureCount }
}
export interface SummaryCard {
key: string
label: string
value: string
note: string
copy?: string
unknown: boolean
}
const lastReportNote = (inventory: BackupInventory): string =>
`上次上报 ${formatWhen(inventory.metadata.collected_at) || UNKNOWN}`
export function summaryCards(
inventory: BackupInventory | null,
archive: LibraryStorage | null,
archiveFailed: boolean
): SummaryCard[] {
const state = hostState(inventory)
const facts = state === 'ready' || state === 'incomplete'
const sizes = state === 'ready'
const pending = Boolean(inventory) && state !== 'loading'
const recent = inventory && facts ? recentOutcome(inventory.batches) : null
const hostValue = pending && !facts ? hostValueLabel(state) : UNKNOWN
const hostNote = pending ? lastReportNote(inventory!) : UNKNOWN
const partialNote = facts && !sizes ? '本次上报不完整' : hostNote
const root = inventory ? inventory.host_root || inventory.root : ''
const rootKnown = facts && Boolean(root)
const capacity = inventory?.capacity
const diskKnown = sizes && Boolean(capacity?.measured) && (capacity?.total_bytes ?? 0) > 0
const availablePercent = diskKnown ? Math.round((capacity!.available_bytes / capacity!.total_bytes) * 100) : 0
const archiveKnown = Boolean(archive?.available) && !archiveFailed
return [
{
key: 'root',
label: '备份目录',
value: rootKnown ? root : hostValue,
note: rootKnown ? inventory!.metadata.host || UNKNOWN : partialNote,
copy: rootKnown ? root : undefined,
unknown: !rootKnown,
},
{
key: 'success',
label: '最近成功',
value: recent ? recent.latestSuccessAt || '无' : hostValue,
note: recent ? `近 ${RECENT_WINDOW_DAYS} 天 ${recent.successCount} 次` : partialNote,
unknown: !recent,
},
{
key: 'failure',
label: '最近失败',
value: recent ? recent.latestFailureAt || '无' : hostValue,
note: recent ? `近 ${RECENT_WINDOW_DAYS} 天 ${recent.failureCount} 次` : partialNote,
unknown: !recent,
},
{
key: 'archive',
label: '归档占用',
value: archiveKnown ? formatSize(archive!.capacity.current_bytes) : UNKNOWN,
note: archiveFailed
? '归档读取失败'
: !archive || !archive.available
? '归档不可用'
: archive.capacity.configured
? `配额 ${formatSize(archive.capacity.budget_bytes)}`
: '配额未设置',
unknown: !archiveKnown,
},
{
key: 'disk',
label: '磁盘剩余',
value: diskKnown ? formatSize(capacity!.available_bytes) : sizes ? UNKNOWN : hostValue,
note: diskKnown
? `共 ${formatSize(capacity!.total_bytes)} · 可用 ${availablePercent}%`
: sizes
? '容量未上报'
: partialNote,
unknown: !diskKnown,
},
]
}
export interface SummaryAlert {
key: string
label: string
value: string
tone: Tone
conclusion: string
}
export interface StorageFacts {
diskAvailableBytes: number | null
diskTotalBytes: number | null
archiveUsedBytes: number | null
archiveBudgetBytes: number | null
}
export function storageFacts(
inventory: BackupInventory | null,
archive: LibraryStorage | null,
archiveFailed: boolean
): StorageFacts {
const capacity = inventory?.capacity
const diskKnown = hostState(inventory) === 'ready' && Boolean(capacity?.measured) && (capacity?.total_bytes ?? 0) > 0
const archiveCapacity = archive?.available && !archiveFailed ? archive.capacity : null
return {
diskAvailableBytes: diskKnown ? capacity!.available_bytes : null,
diskTotalBytes: diskKnown ? capacity!.total_bytes : null,
archiveUsedBytes: archiveCapacity ? archiveCapacity.current_bytes : null,
archiveBudgetBytes: archiveCapacity?.configured ? archiveCapacity.budget_bytes : null,
}
}
const tonePercent = (value: number, warn: number, critical: number): Tone =>
value >= critical ? 'bad' : value >= warn ? 'warn' : 'ok'
const conclusionText = (tone: Tone): string =>
tone === 'ok' ? '正常' : tone === 'warn' ? '注意' : tone === 'bad' ? '需处理' : UNKNOWN_STATE
export function storageAlerts(
inventory: BackupInventory | null,
archive: LibraryStorage | null,
archiveFailed: boolean
): SummaryAlert[] {
const state = hostState(inventory)
const facts = storageFacts(inventory, archive, archiveFailed)
const diskKnown = facts.diskAvailableBytes !== null && (facts.diskTotalBytes ?? 0) > 0
const availablePercent = diskKnown ? Math.round((facts.diskAvailableBytes! / facts.diskTotalBytes!) * 100) : 0
const diskTone: Tone = diskKnown
? availablePercent < DISK_CRITICAL_AVAILABLE_PERCENT
? 'bad'
: availablePercent < DISK_WARN_AVAILABLE_PERCENT
? 'warn'
: 'ok'
: 'none'
const quotaKnown = facts.archiveUsedBytes !== null && (facts.archiveBudgetBytes ?? 0) > 0
const usedPercent = quotaKnown ? Math.round((facts.archiveUsedBytes! / facts.archiveBudgetBytes!) * 100) : 0
const quotaTone: Tone = quotaKnown
? tonePercent(usedPercent, QUOTA_WARN_USED_PERCENT, QUOTA_CRITICAL_USED_PERCENT)
: 'none'
const bothTone: Tone =
diskTone === 'none' || quotaTone === 'none' ? 'none' : diskTone !== 'ok' && quotaTone !== 'ok' ? 'bad' : 'ok'
const overPhysical: Tone =
diskKnown && facts.archiveBudgetBytes !== null
? facts.archiveBudgetBytes > facts.diskAvailableBytes!
? 'bad'
: 'ok'
: 'none'
const hostValue = hostValueLabel(state)
return [
{
key: 'disk_low',
label: '磁盘不足',
value: diskKnown ? `${formatSize(facts.diskAvailableBytes)}(可用 ${availablePercent}%)` : hostValue,
tone: diskTone,
conclusion: diskKnown ? conclusionText(diskTone) : UNKNOWN_STATE,
},
{
key: 'quota_low',
label: '配额不足',
value: quotaKnown
? `${formatSize(facts.archiveUsedBytes)} / ${formatSize(facts.archiveBudgetBytes)}(${usedPercent}%)`
: archiveFailed
? UNKNOWN
: archive?.available
? '配额未设置'
: UNKNOWN,
tone: quotaTone,
conclusion: quotaKnown ? conclusionText(quotaTone) : UNKNOWN_STATE,
},
{
key: 'both_low',
label: '磁盘与配额同时不足',
value: diskKnown && quotaKnown ? `磁盘可用 ${availablePercent}% · 配额已用 ${usedPercent}%` : hostValue,
tone: bothTone,
conclusion: diskKnown && quotaKnown ? conclusionText(bothTone) : UNKNOWN_STATE,
},
{
key: 'quota_over_physical',
label: '配额超出物理空闲',
value:
diskKnown && facts.archiveBudgetBytes !== null
? `配额 ${formatSize(facts.archiveBudgetBytes)} · 可用 ${formatSize(facts.diskAvailableBytes)}`
: UNKNOWN,
tone: overPhysical,
conclusion: diskKnown && facts.archiveBudgetBytes !== null ? conclusionText(overPhysical) : UNKNOWN_STATE,
},
]
}
export const pendingAlertCount = (alerts: SummaryAlert[]): number =>
alerts.filter((alert) => alert.tone === 'warn' || alert.tone === 'bad').length