Compare commits

...

22 Commits

Author SHA1 Message Date
zheromiku 424a75d516 Merge pull request #37 from hifox-agent/rin/CYWL-28
build / build (push) Successful in 2m46s
feat(backup): 配额改按备份根占用并在超限时清理最旧批次

CYWL-28;make verify 17/17 success。
2026-11-25 22:58:16 +08:00
Zhero & Rin 144b49cb53 feat(backup): 配额改按备份根占用并在超限时清理最旧批次
build / build (push) Successful in 3m22s
- 采集器上报 backup_root/usage/quota(加性字段),API 用 BACKUP_HOST_ROOT 校验并分别降级占用/配额
- 页面配额行改为备份占用 X / 配额 50 GB,4 条告警改用备份口径,解除本页归档依赖
- logical-backup.sh 预检按字节清理(保留最新、空间不足零删除),dump 后复查保护新批次
- backup_layout 写入 KB_BACKUP_QUOTA_BYTES;--show 输出根占用;新增 prune 工具与自检
2026-11-25 22:46:32 +08:00
姚章浩 65476750b0 feat(cd): 通知标注 CD 结果并附站点链接
build / build (push) Successful in 3m12s
2026-11-25 18:34:06 +08:00
姚章浩 b59ec66387 feat(cd): 发布结果上报 ci-bridge
build / build (push) Successful in 2m23s
2026-11-25 17:38:05 +08:00
姚章浩 7801c163e4 feat(qa): 验收回执写明结论与用例
build / build (push) Successful in 2m31s
2026-11-25 17:06:51 +08:00
姚章浩 15dbc2469b docs: 记录候选访问测试 WeKnora 的通路
build / build (push) Successful in 3m6s
2026-11-25 16:48:21 +08:00
姚章浩 da568dfa2c fix(qa): 候选放行测试 WeKnora 的私网明文连接
build / build (push) Successful in 2m57s
2026-11-25 16:05:24 +08:00
姚章浩 7b4ec1f89d fix(qa): 为候选提供稳定的绑定主密钥
build / build (push) Successful in 3m16s
2026-11-25 16:01:02 +08:00
姚章浩 6a6fa7129a fix(qa): 在提交与登记前核对候选逐项报告
build / build (push) Successful in 3m21s
2026-11-25 14:21:04 +08:00
姚章浩 c12152529c fix(qa): 按可测试结论识别本次落地提交
build / build (push) Successful in 2m14s
2026-11-25 12:37:52 +08:00
zheromiku 4d73aa999b fix(kb): 去掉非 HTTPS 页面禁止录入 API Key 的拦截 (#36)
build / build (push) Successful in 3m33s
2026-11-25 12:21:50 +08:00
Zhero & Rin cc289b63e5 test(kb): 明文录入夹具改为运行期拼装
build / build (push) Successful in 2m35s
- 密钥扫描器把「api_key: '<16+ 字符字面量>'」判成真实泄漏,CI 因此变红。
- 夹具值改为数组拼接后引用,断言仍然覆盖验证/保存两条请求体。
2026-11-25 12:08:48 +08:00
Zhero & Rin 9ddc3291cc fix(kb): 保存 API Key 时落来源审计
- 修订历史新增 source_address/source_origin:操作人、时间、环境之外,
  再记录客户端地址与控制台来源,明文录入事后可追溯。
- 来源只用于取证,不参与放行;最近一跳代理追加的 X-Forwarded-For 才可信,
  直连请求不能用伪造链改地址;解析不出就留空,绝不猜值。
- 截断按 UTF-8 边界收口,避免恶意 Origin 让整条保存变成存储错误。
- 迁移 083 只追加列,回滚只删这两列。
2026-11-25 12:06:36 +08:00
Zhero & Miku 32c7074f41 fix(kb): 不再按控制台传输形态拦截 API Key
- 删除 KBBindingSnapshot 的 secret_entry_allowed 能力位与服务端 catalog/save 的 KB 传输门禁
- 非 HTTPS 控制台保留明文传输提示,但不再阻断 Key 录入
- 保留 QA AI 严格 HTTPS/回环校验、管理员认证、写意图头与 Key 不回显
- 补齐明文 HTTP 页面与服务端写入回归测试,同步运行手册和 CHANGELOG
2026-11-25 10:50:52 +08:00
姚章浩 7926c8e8b9 fix(qa): 为候选库验收预留连接容量
build / build (push) Successful in 2m9s
2026-11-25 01:09:01 +08:00
姚章浩 bb57a9835c revert(cd): 恢复原生产发布脚本
build / build (push) Successful in 1m57s
2026-11-24 23:37:56 +08:00
姚章浩 49f9994ea6 fix(release): 需求单状态改由负责人手动切换
build / build (push) Successful in 2m5s
2026-11-24 23:15:15 +08:00
姚章浩 501fbae6ff feat(release): 原需求单按预检顺序接续候选验收
build / build (push) Successful in 2m7s
2026-11-24 22:58:42 +08:00
姚章浩 45aef5016a fix(release): 识别预检评论中的落地 merge 提交
build / build (push) Successful in 2m17s
2026-11-24 21:56:43 +08:00
zheromiku c90cb803fa Merge pull request 'feat(release): 原需求单完成候选验收与发布授权' (#35) from feat/single-task-release into main
build / build (push) Successful in 2m4s
2026-11-24 19:06:15 +08:00
姚章浩 e6a9acc32c feat(release): 在原需求单自动准备并登记验收候选
build / build (push) Successful in 2m14s
2026-11-24 19:03:28 +08:00
zheromiku a3dcaa2f5b Merge pull request 'fix(release): 支持提示中的带引号确认回复' (#34) from fix/release-confirm-quotes into main
build / build (push) Successful in 2m6s
2026-11-24 14:56:49 +08:00
54 changed files with 2155 additions and 573 deletions
+1 -2
View File
@@ -28,8 +28,7 @@ QA_AI_MASTER_KEY_FILE=
# 留空时页面仍能读旧部署的文件凭据/默认绑定,但保存新密钥会被拒绝(不落明文)。 # 留空时页面仍能读旧部署的文件凭据/默认绑定,但保存新密钥会被拒绝(不落明文)。
WEKNORA_BINDING_MASTER_KEY_FILE= WEKNORA_BINDING_MASTER_KEY_FILE=
# 同网段 http(生产 18093 反代)放行:只接受 RFC1918/回环/链路本地,公网 http 仍拒绝。 # 同网段 http(生产 18093 反代)放行:只接受 RFC1918/回环/链路本地,公网 http 仍拒绝。
# 同时决定「知识库绑定」页是否允许录入新 Key(能力位来自服务端);开启后页面显示明文传输风险。 # 只影响治理 API/worker 访问 WeKnora 的地址校验;控制台自身的密钥录入不再由该开关控制。
# 控制台自身经 TLS 反代提供时,仍需 QA_AI_TRUST_TLS_PROXY=true 且反代传 X-Forwarded-Proto=https。
WEKNORA_ALLOW_PRIVATE_HTTP=false WEKNORA_ALLOW_PRIVATE_HTTP=false
# Empty uses system DNS; alidns enables certificate-verified public DNS-over-TLS for this client only. # Empty uses system DNS; alidns enables certificate-verified public DNS-over-TLS for this client only.
QA_AI_DNS_OVER_TLS= QA_AI_DNS_OVER_TLS=
+36
View File
@@ -80,3 +80,39 @@ jobs:
KG_CD_SSH_HOST: ${{ vars.KG_CD_SSH_HOST }} KG_CD_SSH_HOST: ${{ vars.KG_CD_SSH_HOST }}
KG_CD_SSH_PORT: ${{ vars.KG_CD_SSH_PORT }} KG_CD_SSH_PORT: ${{ vars.KG_CD_SSH_PORT }}
run: python3 scripts/production_cd.py send --event "$GITHUB_EVENT_PATH" run: python3 scripts/production_cd.py send --event "$GITHUB_EVENT_PATH"
notify:
needs: [guard, publish]
if: always()
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
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: 上报 ci-bridge(发布结果,通知失败不改变发布结论)
if: always()
env:
BRIDGE_URL: ${{ vars.CI_BRIDGE_URL }}
BRIDGE_TOKEN: ${{ secrets.CI_BRIDGE_TOKEN }}
CI_PUBLIC_BASE_URL: https://gitea.zheromiku.top
GUARD_RESULT: ${{ needs.guard.result }}
PUBLISH_RESULT: ${{ needs.publish.result }}
DEPLOY_SHA: ${{ inputs.sha }}
DEPLOY_BUNDLE: ${{ inputs.bundle }}
DEPLOY_TASK: ${{ inputs.task }}
run: |
set +e; set +o pipefail
B="${BRIDGE_URL:-}"
for cand in "$B" "http://172.17.0.1:8899" "http://192.168.50.134:8899" "http://100.92.49.78:8899"; do
if [ -n "$cand" ]; then curl -s -m 5 -o /dev/null "$cand/healthz" && { B="$cand"; break; }; fi
done
echo "使用 ci-bridge: ${B:-(不可达)}"
CI_BRIDGE_RESOLVED="$B" python3 scripts/cd_notify.py
echo "上报结束(通知失败不改变发布结论)"
+66
View File
@@ -1,5 +1,71 @@
# Changelog # Changelog
## 开发快照 0.1.423(存储与备份:配额改按备份根占用)
### Fixed
- **页面配额行读错数据源**:`归档占用` 卡片读 `/api/v1/library/storage`(`runtime/library`
归档库,现场 1.67 MB),与 `/srv/kb-backups` 的整库逻辑备份无关;现改为「备份占用 X / 配额 50 GB」,
只读宿主采集器上报的备份根累计占用。归档库接口仍服务归档写入门禁,不再被本页调用。
- **备份没有按字节的执行路径**:`logical-backup.sh` 过去只有按份数/月份轮转;现在 dump 前按
`KB_BACKUP_QUOTA_BYTES` 预检,最旧优先清理且保留最新一份,空间仍不够时零删除并取消本次备份;
dump 后复查并保护本次新批次。只删 `rds-logical` 完整批次,`es-snapshots`/`target-kb-snapshots`/
`logs` 与 `*.incomplete` 不动。
- **根占用不完整不牵连批次**:采集器对根树遍历失败时 `usage.actual_bytes=null`,批次表与磁盘容量仍可用;
旧采集器快照缺 `usage/quota` 时显式「未上报」,不用批次和冒充。
### Added
- 采集器 `collect_backup_metadata.py` 新增 `--usage-root/--quota-bytes/--config`,快照新增
`backup_root/usage/quota_bytes/quota_error`(加性字段,schema 仍为 1),根占用与 `du -sB1` 对拍。
- `scripts/prune_backup_batches.py`:配额清理独立工具 + self-test(最旧优先、预检保留最新、
不足零删除、非批次日录/符号链接不动、dump 后保护新批次)。
- API 校验 `usage.root == BACKUP_HOST_ROOT`,占用与配额不完整/非法时只降级对应字段;
`install_backup_schedule.sh --show` 增加备份根占用/配额读数。
### Changed
- `backup_layout.sh` 把 `KB_BACKUP_QUOTA_BYTES=53687091200` 写入 `backup.env`(已有值不覆盖);
页面 4 条容量告警的配额项统一改用备份占用/配额,磁盘项仍取文件系统实测值。
- 契约与核验命令更新到 `docs/STORAGE_BACKUP_READONLY_API.md`、`docs/PRODUCTION_BACKUP_RECOVERY.md`。
## 开发快照 0.1.422(知识库绑定:不再按控制台传输形态拦截 Key)
### Fixed
- **非 HTTPS 控制台仍无法录入 API Key**:页面删除 `secret_entry_allowed` 能力位与
`secure`/`keyEntryBlocked` 传输判定,服务端删除 KB 专用的
`secretTransportAllowedForPrivateConsole` 写侧校验。管理员在任意同源控制台都能录入/
更换 Key,不再出现「可输入但保存 400」的半修复。
- **提示与录入门禁解耦**:非 HTTPS、非回环页面保留「当前通过明文 HTTP 访问:录入的
API Key 会在内网明文传输。」,只提示不阻断;HTTPS 页面不再提示反代是否受信。
- **保存落审计**:`weknora_environment_binding_history` 同一事务写入操作人、时间、
环境、客户端地址与控制台来源(`source_address`/`source_origin`),明文录入事后可追溯;
来源只做取证,不参与放行判定,解析不出就留空而不猜值。
### Changed
- `WEKNORA_ALLOW_PRIVATE_HTTP` 仅控制治理 API/worker 访问同网段 http 目标,不再决定
控制台密钥录入。问答 AI 模型密钥仍走严格 HTTPS/回环校验;管理员、`X-Governance-Action`
写意图与 Key 不回显边界不变。Web 与 API 是独立镜像,须同批次发布/回滚:旧 Web 对新
API 会禁用录入,新 Web 对旧 API 仍会被 400 拒绝。
## 开发快照 0.1.421(负责人手动切换需求状态)
- 原需求单在候选就绪和主站发布成功时回填回执,负责人按回执手动切换状态。
## 开发快照 0.1.420(需求单候选排队)
- 需求单预检通过后自动排队等待验收环境,构建链接回填原单。已发布批次释放其测试容器,接续下一张需求。
## 开发快照 0.1.419(候选预检识别落地 merge)
- 预检支持从含多个版本号的提交链中识别 `落地 merge`,并分别提示缺少和存在多个落地版本。
## 开发快照 0.1.418(原需求单发布)
- 白盒预检后在原需求单自动准备候选,业务与批次回归证据同单登记。负责人在原单切到「待发布」批准上线。
## 开发快照 0.1.417(知识治理发布助理接收提测交接) ## 开发快照 0.1.417(知识治理发布助理接收提测交接)
- 预检通过后按实际落地版本创建发布范围预览,支持单独选择已进入主线的修复提交。 - 预检通过后按实际落地版本创建发布范围预览,支持单独选择已进入主线的修复提交。
+1 -1
View File
@@ -1978,7 +1978,7 @@
"Settings" "Settings"
], ],
"operationId": "getBackupScheduleInventory", "operationId": "getBackupScheduleInventory",
"summary": "读取宿主元数据快照:批次、子库完整路径、实际占盘与文件系统容量(陈旧/不完整一律未知)", "summary": "读取宿主元数据快照:批次、子库完整路径、备份根累计占用、配额与文件系统容量(陈旧/不完整一律未知)",
"responses": { "responses": {
"200": { "200": {
"$ref": "#/components/responses/Envelope" "$ref": "#/components/responses/Envelope"
+1
View File
@@ -349,6 +349,7 @@ func run(ctx context.Context, getenv func(string) string) error {
BackupInventory: backupinventory.New(backupinventory.Config{ BackupInventory: backupinventory.New(backupinventory.Config{
MetadataPath: config.BackupHostMetadataPath, MetadataPath: config.BackupHostMetadataPath,
HostRoot: config.BackupHostReadonlyHostPath, HostRoot: config.BackupHostReadonlyHostPath,
BackupRoot: config.BackupHostRoot,
Source: backupInventorySource(config), Source: backupInventorySource(config),
MaxAge: config.BackupHostMetadataMaxAge, MaxAge: config.BackupHostMetadataMaxAge,
}), }),
+1 -1
View File
@@ -69,7 +69,7 @@ services:
# 留空 = 可以读取旧部署的 file 凭据/绑定,但不能在页面保存新密钥。 # 留空 = 可以读取旧部署的 file 凭据/绑定,但不能在页面保存新密钥。
WEKNORA_BINDING_MASTER_KEY_FILE: "${WEKNORA_BINDING_MASTER_KEY_FILE:-}" WEKNORA_BINDING_MASTER_KEY_FILE: "${WEKNORA_BINDING_MASTER_KEY_FILE:-}"
# 生产 18093 是同网段 http 反代:显式放行私网 http(只放行 RFC1918/回环/ # 生产 18093 是同网段 http 反代:显式放行私网 http(只放行 RFC1918/回环/
# 链路本地,公网 http 仍被拒绝)。客户端、探活与连接页共用同一判定。 # 链路本地,公网 http 仍被拒绝)。客户端与探活共用同一判定;控制台密钥录入不受此开关控制。
WEKNORA_ALLOW_PRIVATE_HTTP: "${WEKNORA_ALLOW_PRIVATE_HTTP:-false}" WEKNORA_ALLOW_PRIVATE_HTTP: "${WEKNORA_ALLOW_PRIVATE_HTTP:-false}"
QA_AI_DNS_OVER_TLS: "${QA_AI_DNS_OVER_TLS:-}" QA_AI_DNS_OVER_TLS: "${QA_AI_DNS_OVER_TLS:-}"
QA_AI_TRUST_TLS_PROXY: "${QA_AI_TRUST_TLS_PROXY:-false}" QA_AI_TRUST_TLS_PROXY: "${QA_AI_TRUST_TLS_PROXY:-false}"
+7
View File
@@ -0,0 +1,7 @@
[Unit]
Description=Advance original-task candidate queue
[Service]
Type=oneshot
ExecStart=%h/.local/lib/kg-candidate-release/python3 %h/.local/lib/kg-candidate-release/scripts/candidate_queue.py
TimeoutStartSec=180
+10
View File
@@ -0,0 +1,10 @@
[Unit]
Description=Check reviewed demand tasks waiting for QA
[Timer]
OnStartupSec=30s
OnUnitInactiveSec=45s
AccuracySec=5s
[Install]
WantedBy=timers.target
+19 -7
View File
@@ -1,16 +1,14 @@
# 知识治理候选和批次验收 # 知识治理候选和批次验收
「知识治理版本与发布 Agent」管理一条 HiFox 发布任务。开发和合并按正常 PR 流程处理。三生三测仍由业务任务进入「测试中」触发,现有白小浅和三生三测规则无需改动。正式发布由发布负责人确认,沿用 [主站 CD](PRODUCTION_CD_RUNBOOK.md)。 ## 需求单的六个状态
## 从提测评论接单 新需求默认「规划中」。负责人手动按「规划中 → 进行中 → 待测试 → 测试中 → 待发布 → 已发布」切换状态。切到「待测试」触发预检和候选排队,收到候选就绪回执后切到「测试中」派测。原单显示「批次验收通过」后切到「待发布」触发 CD,收到主站发布完成回执后切到「已发布」。
白小浅在业务单提交通过的预检后,评论自动化把来源任务和评论 UUID 交给 `scripts/release_handoff.py preflight`。执行器核验作者、最新结论、知识治理仓库的落地记录、主线范围和所选版本的 CI。相同业务单与提交复用同一发布单。已在测试中的旧单可用 `recover <业务任务号>` 从原记录补接。 ## 在原需求单发布
发布单的预览列明线上基线、候选提交及所有其他随批提交。负责人在**该预览的评论线程**回复「确认范围」后准备候选。已有负责人计划仍可使用。每项来源支持 `{"task":"<UUID>","pr":123}` 或 `{"task":"<UUID>","commit":"<完整落地 SHA>"}`。固定历史候选可用 `release_assistant.py plan <发布单> <业务单>:<来源> --sha <完整 SHA>`。 白小浅预检通过后,执行器从原单核对合入版本与 CI,在同一张单列出线上基线和随批提交,自动准备隔离候选。候选就绪后由负责人切到「测试中」。QA 在原单对同一归档执行需求用例和批次回归,结构化报告的 `cases.business` 与 `cases.regression` 分别列出唯一的已通过用例编号,总数与 `required` 一致。系统登记后,在原单显示「批次验收通过」。发布负责人将原单切到「待发布」即触发 CD。负责人可从原单查看归档、证据和发布记录。
候选就绪后,业务和批次 QA 均按下方格式提交真实报告。`kg-qa-v1` 评论触发登记,两处报告全部齐全才写入验收记录。已在「测试中」的业务单通过原单召唤 QA 执行新包复测。遇到建单或派测回执未知,核对远端记录后恢复。 ## 旧版独立发布单的存量操作
## 发起候选
1. 发布负责人在发布任务的评论中填写下列 `kg-release-v1` 代码块。`base` 填主站实际运行的完整提交 SHA,`sha` 填选定的 `main` 完整提交 SHA。每条 `items` 关联一个已合入 `main` 的 PR 和一个 HiFox 业务任务 UUID。PR 的标题、正文或来源分支应包含该任务编号。`extra` 列出这段主干历史中经负责人确认一同发布的其他主干提交,通常为空。 1. 发布负责人在发布任务的评论中填写下列 `kg-release-v1` 代码块。`base` 填主站实际运行的完整提交 SHA,`sha` 填选定的 `main` 完整提交 SHA。每条 `items` 关联一个已合入 `main` 的 PR 和一个 HiFox 业务任务 UUID。PR 的标题、正文或来源分支应包含该任务编号。`extra` 列出这段主干历史中经负责人确认一同发布的其他主干提交,通常为空。
@@ -36,6 +34,20 @@
执行 `candidate_coordinator.py register <发布任务 UUID>`。脚本复验运行身份,逐项核对报告作者、候选版本和归档、时序与必测结果。全项通过后在发布任务登记附原始报告链接的汇总,再写入并读回 `cd_acceptance`。验收候选只接受专用 RDS 模式。 执行 `candidate_coordinator.py register <发布任务 UUID>`。脚本复验运行身份,逐项核对报告作者、候选版本和归档、时序与必测结果。全项通过后在发布任务登记附原始报告链接的汇总,再写入并读回 `cd_acceptance`。验收候选只接受专用 RDS 模式。
### 候选访问测试 WeKnora
候选容器不能直连测试宿主的内网地址。宿主用 `kg-qa-weknora-test-hop.service` 把 `0.0.0.0:18090` 转到测试 WeKnora 的 `127.0.0.1:8092`,候选与所有 docker 网桥都能通过 `http://172.17.0.1:18090` 访问;`172.17.0.1` 是 docker0 的固定地址,换候选不变。绑定地址要填 IP,服务端不接受主机名。API Key 由测试负责人经授权渠道录入,不写进评论。
### 候选的知识库绑定密钥
验收候选运行在 QA 库上,知识库绑定需要独立的 32 字节主密钥。执行器在 `~/.local/state/kg-candidate-release/qa-binding-master.key` 维护唯一一份(0600、属主为容器应用用户),以只读方式挂到 API 与 worker 的 `/run/qa/binding-master.key`。所有候选共用这一份,已保存的绑定在下一轮候选仍可解开。文件缺失时首个候选自动生成;权限、长度或属主不符时拒绝启动,不静默降级。
### 原需求单的逐项报告
测试机将 `scripts/qa_report.py` 安装为 `~/.local/bin/kg-qa-report`。在 QA 的 HiFox 任务会话中,从本轮测试设计取得完整编号,保存到 `plan.json` 的 `business`、`regression` 数组。执行 `kg-qa-report init <任务> plan.json sheet.json` 读取原单候选回执并生成待填清单。测试中填写各编号的 `status`(`passed`、`failed`、`blocked`)和 `evidence`。`candidate_check` 记录指定候选部署上的实际验证结果及证据。环境受阻时记录原因。
使用 `kg-qa-report check <任务> plan.json sheet.json` 预检。缺失项按编号提示。使用同一参数将 `check` 换为 `submit` 后,由 QA 本人的 HiFox 执行上下文发表评论。回执变化时,工具会提示重新核对。登记端重新核算汇总和候选实测结论。
HiFox 触发器按[主站 CD 手册](PRODUCTION_CD_RUNBOOK.md)在派发前交接并校验验收归档。交接失败时可修复后重试同一事件,已派发事件仍回放原记录。发布负责人完成确认后,将发布任务转入「待发布」。已有自动化使用该 UUID 和归档部署并回写。部署后回写失败时使用现有回执重试回写。 HiFox 触发器按[主站 CD 手册](PRODUCTION_CD_RUNBOOK.md)在派发前交接并校验验收归档。交接失败时可修复后重试同一事件,已派发事件仍回放原记录。发布负责人完成确认后,将发布任务转入「待发布」。已有自动化使用该 UUID 和归档部署并回写。部署后回写失败时使用现有回执重试回写。
## 执行器配置 ## 执行器配置
+5 -7
View File
@@ -70,13 +70,11 @@ docker inspect -f '{{.Name}} {{index .Config.Labels "release"}}' kg-test-storage
http,公网 http 仍被拒绝;不再需要测试机上的 `ssh -L 18092`,停掉隧道后生产连接仍 http,公网 http 仍被拒绝;不再需要测试机上的 `ssh -L 18092`,停掉隧道后生产连接仍
应可用。没有反代时继续填 `http://127.0.0.1:18092` 走隧道(回环地址不需要该开关)。 应可用。没有反代时继续填 `http://127.0.0.1:18092` 走隧道(回环地址不需要该开关)。
**页面为什么能看到开关。** 「知识库绑定」页不再用浏览器 URL 自行判断能否录入 Key;GET **页面为什么不看开关。** 「知识库绑定」页不再用浏览器 URL 或服务端能力位决定能否录入 Key;只要独立安全存储就绪,管理员即可录入/更换,服务端也不因控制台协议拒绝。经非 HTTPS、非回环地址打开时,页面只显示「当前通过明文 HTTP 访问:录入的 API Key 会在内网明文传输。」,提示但不阻断。`WEKNORA_ALLOW_PRIVATE_HTTP` 只控制治理 API/worker 访问同网段 http 目标,不再控制控制台录入;问答 AI 模型密钥仍只允许 HTTPS/回环录入。Web 与 API 是独立镜像,必须同批次发布/回滚:旧 Web 对新 API 会因缺少能力位禁用录入,新 Web 对旧 API 仍会被服务端 400 拒绝。
`/api/v1/kb-bindings` 返回 `secret_entry_allowed`,由服务端按本次连接的 TLS、回环、
`WEKNORA_ALLOW_PRIVATE_HTTP` 与受信反代判定。开启开关后,经私网 http 打开的控制台可以 **保存留审计。** 每次保存成功,`weknora_environment_binding_history` 在同一事务写入
录入/更换 Key,并显示「密钥会以明文经过这段内网」;关闭时保持 HTTPS/回环要求。控制台 操作人、时间、环境、客户端地址(`source_address`)与控制台来源(`source_origin`)。来源字段
自身经 TLS 反代提供时,必须同时设置 `QA_AI_TRUST_TLS_PROXY=true` 且反代传 只用于事后取证,不参与放行;地址解析不出来就留空,不用推测值填充。
`X-Forwarded-Proto: https`,否则页面提示「服务器未信任本控制台的 TLS 反代」并禁用录入。
先升级 API 再升级 Web:旧 API 不返回该字段时前端按不可录入处理(失败关闭),不会误放行。
**四态与尾号。** 「验证并读取知识库」会真实列库并区分:地址不可达 / 密钥无效(401) / **四态与尾号。** 「验证并读取知识库」会真实列库并区分:地址不可达 / 密钥无效(401) /
密钥无权限(403) / 成功(读到 N 个库)。保存后页面只显示「已配置 · 尾XXXX」; 密钥无权限(403) / 成功(读到 N 个库)。保存后页面只显示「已配置 · 尾XXXX」;
+10
View File
@@ -96,6 +96,16 @@ python3 scripts/restore_drill.py --snapshot-dir $KB_BACKUP_ROOT/target-kb-snapsh
写操作按角色网关(`classifyRole`)限管理员——这份计划会落到数据面主机的 cron 上。 写操作按角色网关(`classifyRole`)限管理员——这份计划会落到数据面主机的 cron 上。
- 主机侧:`scripts/install_backup_schedule.sh`(幂等)写 `/etc/knowledge-governance/backup-schedule.env` - 主机侧:`scripts/install_backup_schedule.sh`(幂等)写 `/etc/knowledge-governance/backup-schedule.env`
与 `/etc/cron.d/kb-logical-backup`;`logical-backup.sh` 从该文件读保留策略(显式传 `KEEP_DAILY/KEEP_MONTHS` 可覆盖)。 与 `/etc/cron.d/kb-logical-backup`;`logical-backup.sh` 从该文件读保留策略(显式传 `KEEP_DAILY/KEEP_MONTHS` 可覆盖)。
- **配额(按字节,硬上限)**:`/etc/knowledge-governance/backup.env` 的 `KB_BACKUP_QUOTA_BYTES`
约束**备份根累计占用**(默认 `53687091200` = 50 GiB,`backup_layout.sh` 写入,重跑不覆盖已有值)。
采集器把同一份配额与根占用写进快照,页面/告警只读该值,不再看归档库。
- dump 前预检:预留最近一份完整批次大小,从最旧开始计划删批次,**永不删最新一份**;
空间仍不够 → **一个都不删**、非 0 退出,本次备份取消。
- dump 后复查:保护本次新批次,允许删旧(含上一份);仍超限则保留新备份并告警退出。
- 只删 `rds-logical/<UTC>` 完整批次(含常规 `MANIFEST.json`、非符号链接);
`es-snapshots`/`target-kb-snapshots`/`logs` 与 `*.incomplete` 永不删。
- 现场对账:`du -sB1 -- $KB_BACKUP_ROOT` 与页面「备份占用」应一致(≤1%);
`bash scripts/install_backup_schedule.sh --show` 也会打印根占用/配额。
- 凭据:容器内只读挂载 `secrets/backup-host/{ssh_config,id_ed25519,known_hosts}`(0600), - 凭据:容器内只读挂载 `secrets/backup-host/{ssh_config,id_ed25519,known_hosts}`(0600),
环境变量 `BACKUP_HOST_SSH_CONFIG / BACKUP_HOST_TARGET / BACKUP_HOST_SCRIPT_DIR / BACKUP_HOST_ROOT`; 环境变量 `BACKUP_HOST_SSH_CONFIG / BACKUP_HOST_TARGET / BACKUP_HOST_SCRIPT_DIR / BACKUP_HOST_ROOT`;
**三项缺任一即"未接线"**,页面降级提示而不是报错。只读盘点另用宿主采集器 **三项缺任一即"未接线"**,页面降级提示而不是报错。只读盘点另用宿主采集器
+32 -5
View File
@@ -19,11 +19,15 @@
```sh ```sh
python3 collect_backup_metadata.py \ python3 collect_backup_metadata.py \
--root /srv/kb-backups/rds-logical \ --root /srv/kb-backups/rds-logical \
--usage-root /srv/kb-backups \
--output /var/lib/knowledge-governance/backup-metadata/metadata.json \ --output /var/lib/knowledge-governance/backup-metadata/metadata.json \
--source weknora-test:/srv/kb-backups/rds-logical --source weknora-test:/srv/kb-backups/rds-logical
``` ```
- 退出码:`0` 完整;`2` 已写快照但采集不完整/有错误;`1` 连快照都没写成。 - 备份根与配额来自 `/etc/knowledge-governance/backup.env`(`backup_layout.sh` 生成):
`KB_BACKUP_ROOT`(默认 `/srv/kb-backups`)与 `KB_BACKUP_QUOTA_BYTES`(默认 `53687091200` = 50 GiB)。
`--usage-root` / `--quota-bytes` 可显式覆盖;`--config` 换配置文件路径。
- 退出码:`0` 完整且配额可用;`2` 已写快照但批次/根占用不完整或配额非法;`1` 连快照都没写成。
- 只读取:目录项 `lstat`、`statvfs`、`/proc/self/mountinfo`、`MANIFEST.json`; - 只读取:目录项 `lstat`、`statvfs`、`/proc/self/mountinfo`、`MANIFEST.json`;
**不打开任何 `.dat/.gz` 数据文件**。 **不打开任何 `.dat/.gz` 数据文件**。
- 不跟随符号链接;`*.incomplete` 只计数不进入批次;单次最多 100 批(可调)。 - 不跟随符号链接;`*.incomplete` 只计数不进入批次;单次最多 100 批(可调)。
@@ -47,6 +51,8 @@ python3 collect_backup_metadata.py \
``` ```
目录 `0755`、文件 `0644`,只包含路径/清单摘要/计数,不含数据库内容。 目录 `0755`、文件 `0644`,只包含路径/清单摘要/计数,不含数据库内容。
采集器自己读 `/etc/knowledge-governance/backup.env` 拿 `KB_BACKUP_ROOT`/`KB_BACKUP_QUOTA_BYTES`,
所以配额调整不需要改 cron;只想临时覆盖时再加 `--usage-root`/`--quota-bytes`。
### 快照 schema(version 1) ### 快照 schema(version 1)
@@ -58,6 +64,10 @@ python3 collect_backup_metadata.py \
| `collected_at` | UTC RFC3339;超过 `BACKUP_HOST_METADATA_MAX_AGE` 即陈旧 | | `collected_at` | UTC RFC3339;超过 `BACKUP_HOST_METADATA_MAX_AGE` 即陈旧 |
| `generation` | 每次采集唯一 ID,便于核对读到的是哪一次原子快照 | | `generation` | 每次采集唯一 ID,便于核对读到的是哪一次原子快照 |
| `root` | 宿主上的 `rds-logical` 绝对路径;API 要求与配置完全一致 | | `root` | 宿主上的 `rds-logical` 绝对路径;API 要求与配置完全一致 |
| `backup_root` | 宿主上的备份根(`KB_BACKUP_ROOT`);API 要求等于 `BACKUP_HOST_ROOT` |
| `usage` | 备份根整棵树的累计占用:`root/complete/actual_bytes/apparent_bytes/file_count/dir_count/errors`;`complete=false` 时字节必须为 `null` |
| `quota_bytes` | 备份根累计占用硬上限(字节);非法/缺失时为 `null`,原因写 `quota_error` |
| `quota_error` | 配额不可用的原因(例如 `KB_BACKUP_QUOTA_BYTES` 不是正整数) |
| `complete` | 全局完整;权限失败/截断/有错误时为 false | | `complete` | 全局完整;权限失败/截断/有错误时为 false |
| `filesystem` | `mount_point/mount_source/fs_type/read_only/total/free/available` | | `filesystem` | `mount_point/mount_source/fs_type/read_only/total/free/available` |
| `batches[].complete` | 该批遍历完整;false 时字节必须为 null | | `batches[].complete` | 该批遍历完整;false 时字节必须为 null |
@@ -87,8 +97,16 @@ python3 collect_backup_metadata.py \
}, },
"root": "/srv/kb-backups/rds-logical", "root": "/srv/kb-backups/rds-logical",
"host_root": "/srv/kb-backups/rds-logical", "host_root": "/srv/kb-backups/rds-logical",
"backup_root": "/srv/kb-backups",
"source": "weknora-test:/srv/kb-backups/rds-logical", "source": "weknora-test:/srv/kb-backups/rds-logical",
"measurement": "host_collector", "measurement": "host_collector",
"usage": {
"root": "/srv/kb-backups", "complete": true,
"actual_bytes": 24318382080, "apparent_bytes": 23000000000,
"file_count": 900, "dir_count": 30, "errors": []
},
"quota_bytes": 53687091200,
"quota_error": "",
"mount": { "mount": {
"mount_verified": true, "read_only": false, "mount_verified": true, "read_only": false,
"mount_point": "/srv/kb-backups", "device": "/dev/sdb1", "fs_type": "ext4", "mount_point": "/srv/kb-backups", "device": "/dev/sdb1", "fs_type": "ext4",
@@ -135,8 +153,11 @@ python3 collect_backup_metadata.py \
| `wired=false` | `metadata.error=未接线`,批次空 | 显示未接线与安装方式,不显示空表当“没备份” | | `wired=false` | `metadata.error=未接线`,批次空 | 显示未接线与安装方式,不显示空表当“没备份” |
| 快照文件缺失/不可读 | `present=false`、`valid=false` | 显示缺失;不使用 SSH 最近一次补历史 | | 快照文件缺失/不可读 | `present=false`、`valid=false` | 显示缺失;不使用 SSH 最近一次补历史 |
| `collected_at` 超过 max age | `fresh=false`、`valid=false`、批次空、容量未测 | 显示陈旧;容量图/占盘未知 | | `collected_at` 超过 max age | `fresh=false`、`valid=false`、批次空、容量未测 | 显示陈旧;容量图/占盘未知 |
| 任一批不完整/权限失败/截断 | `valid=true`、`complete=false`;所有 `*_bytes=null` | 列出路径与清单状态;占盘/容量“未知”,不画色带 | | 任一批不完整/权限失败/截断 | `valid=true`、`complete=false`;所有批次 `*_bytes=null` | 列出路径与清单状态;批次/容量“未知”,不画色带;根占用若自身完整仍可显示 |
| 完整且新鲜 | 批次/子库字节与容量按快照 | 色带、批次、子库路径复制可用 | | 根占用遍历失败 | `metadata.valid=true`;`usage.actual_bytes=null`、`usage.error` 给原因 | 「备份占用 —」并显示原因;批次表与磁盘剩余不受影响 |
| 旧采集器无 `usage/quota` | 字段缺省,API 返回显式「未上报」原因 | 「备份占用 —」「配额未上报」,绝不用批次和冒充 |
| `usage.root` 与 `BACKUP_HOST_ROOT` 不一致 | `valid=false`,整块拒绝 | 显示校验失败,不展示可疑占用 |
| 完整且新鲜 | 批次/子库字节、根占用与配额按快照 | 色带、批次、`备份占用 X / 配额 50 GB` |
| 批次路径/子库路径与 root 不一致 | `valid=false`,整块拒绝 | 显示校验失败,不展示可疑路径 | | 批次路径/子库路径与 root 不一致 | `valid=false`,整块拒绝 | 显示校验失败,不展示可疑路径 |
API 的路径校验要求批次路径精确等于 `<root>/<stamp>`、子库精确等于 API 的路径校验要求批次路径精确等于 `<root>/<stamp>`、子库精确等于
@@ -187,7 +208,13 @@ curl -s http://127.0.0.1:28189/api/v1/backup-schedule/inventory | head -c 400
字段核对(以现场为准,示例值不写死): 字段核对(以现场为准,示例值不写死):
- `metadata.valid=true`、`fresh=true`;`complete=true` 才允许看占盘与容量。 - `metadata.valid=true`、`fresh=true`;`complete=true` 才允许看批次字节与容量。
- `usage.complete=true` 时,`usage.actual_bytes` 必须与宿主 `du -sB1 -- /srv/kb-backups` 一致
(误差 ≤1%);`quota_bytes` 与 `/etc/knowledge-governance/backup.env` 的 `KB_BACKUP_QUOTA_BYTES` 相同。
- `usage.actual_bytes` **不是** `totals.actual_bytes`:后者只累加 `rds-logical` 批次,
前者还包含 `es-snapshots`/`target-kb-snapshots`/`logs`。
- 根占用遍历失败:`usage.complete=false`、`usage.actual_bytes=null`,同时批次仍应可用;
**不要**用批次和代替根占用。
- `totals.batch_count=8`;`totals.latest_stamp=20261118T193001Z`。 - `totals.batch_count=8`;`totals.latest_stamp=20261118T193001Z`。
- 最近批 `databases` 含 `weknora_v090prod`、`present=true`,`host_path` 指向 - 最近批 `databases` 含 `weknora_v090prod`、`present=true`,`host_path` 指向
`/srv/kb-backups/rds-logical/20261118T193001Z/weknora_v090prod.dir`。 `/srv/kb-backups/rds-logical/20261118T193001Z/weknora_v090prod.dir`。
@@ -218,7 +245,7 @@ curl -s http://127.0.0.1:28189/api/v1/backup-schedule/inventory | head -c 400
## 6. 还需单独确认的后端写能力 ## 6. 还需单独确认的后端写能力
1. 配额 / 磁盘预留的持久化与执行(当前无字段)。 1. 配额 / 磁盘预留的持久化:配额已按部署配置(`backup.env`)执行并上报;**平台页面编辑/下发**仍未实现(需 DB 字段与写接口)。
2. 旧批次保留/删除与删除前审计、可恢复窗口。 2. 旧批次保留/删除与删除前审计、可恢复窗口。
3. 备份目录迁移/切换。 3. 备份目录迁移/切换。
4. 单库备份/单库恢复(现有 run 是整批)。 4. 单库备份/单库恢复(现有 run 是整批)。
+24
View File
@@ -0,0 +1,24 @@
package backuphost
import (
"os/exec"
"strings"
"testing"
)
// 配额清理工具是唯一会删历史备份的代码。它的 self-test 覆盖「最旧优先 / 预检保留最新 /
// 空间不够零删除 / 非批次日录与符号链接不动 / dump 后保护新批次」,必须随 Go 测试一起跑。
func TestPruneBackupBatchesSelfTest(t *testing.T) {
python, err := exec.LookPath("python3")
if err != nil {
t.Skip("python3 not available")
}
command := exec.Command(python, "../../scripts/prune_backup_batches.py", "--self-test")
output, err := command.CombinedOutput()
if err != nil {
t.Fatalf("prune self-test failed: %v\n%s", err, output)
}
if !strings.Contains(string(output), "self-test ok") {
t.Fatalf("prune self-test output unexpected: %s", output)
}
}
+104
View File
@@ -31,6 +31,9 @@ type Config struct {
MetadataPath string MetadataPath string
// HostRoot 是宿主上的 rds-logical 绝对路径,用于校验快照里的 root/批次路径。 // HostRoot 是宿主上的 rds-logical 绝对路径,用于校验快照里的 root/批次路径。
HostRoot string HostRoot string
// BackupRoot 是宿主上的备份根(KB_BACKUP_ROOT),用于校验快照里的根占用范围。
// 它必须与 BACKUP_HOST_ROOT 同源;不同源时占用不可信,整份快照拒绝。
BackupRoot string
// Source 是展示来源;快照里的 source 非空时以快照为准。 // Source 是展示来源;快照里的 source 非空时以快照为准。
Source string Source string
// MaxAge 超过即视为陈旧,旧快照的批次与容量一律不使用。 // MaxAge 超过即视为陈旧,旧快照的批次与容量一律不使用。
@@ -85,6 +88,19 @@ type Capacity struct {
Error string `json:"error,omitempty"` Error string `json:"error,omitempty"`
} }
// Usage 是**备份根累计占用**(配额约束的对象),不是 rds-logical 批次之和。
// Measured=false 时所有字节为 null:部分遍历永远不能当占盘。
type Usage struct {
Root string `json:"root"`
Measured bool `json:"measured"`
Complete bool `json:"complete"`
ActualBytes *int64 `json:"actual_bytes"`
ApparentBytes *int64 `json:"apparent_bytes"`
FileCount *int `json:"file_count"`
DirCount *int `json:"dir_count"`
Error string `json:"error,omitempty"`
}
type Database struct { type Database struct {
Name string `json:"name"` Name string `json:"name"`
DirName string `json:"dir_name"` DirName string `json:"dir_name"`
@@ -138,12 +154,16 @@ type Snapshot struct {
Metadata MetadataInfo `json:"metadata"` Metadata MetadataInfo `json:"metadata"`
Root string `json:"root"` Root string `json:"root"`
HostRoot string `json:"host_root"` HostRoot string `json:"host_root"`
BackupRoot string `json:"backup_root"`
Source string `json:"source"` Source string `json:"source"`
ObservedAt string `json:"observed_at"` ObservedAt string `json:"observed_at"`
Error string `json:"error,omitempty"` Error string `json:"error,omitempty"`
Measurement string `json:"measurement"` Measurement string `json:"measurement"`
Mount MountInfo `json:"mount"` Mount MountInfo `json:"mount"`
Capacity Capacity `json:"capacity"` Capacity Capacity `json:"capacity"`
Usage Usage `json:"usage"`
QuotaBytes *int64 `json:"quota_bytes"`
QuotaError string `json:"quota_error,omitempty"`
Batches []Batch `json:"batches"` Batches []Batch `json:"batches"`
Totals Totals `json:"totals"` Totals Totals `json:"totals"`
IncompleteCount int `json:"incomplete_count"` IncompleteCount int `json:"incomplete_count"`
@@ -181,6 +201,10 @@ type metadata struct {
Host string `json:"host"` Host string `json:"host"`
Source string `json:"source"` Source string `json:"source"`
Root string `json:"root"` Root string `json:"root"`
BackupRoot string `json:"backup_root"`
Usage metadataUsage `json:"usage"`
QuotaBytes *int64 `json:"quota_bytes"`
QuotaError string `json:"quota_error"`
Complete bool `json:"complete"` Complete bool `json:"complete"`
Errors []string `json:"errors"` Errors []string `json:"errors"`
Filesystem metadataFilesystem `json:"filesystem"` Filesystem metadataFilesystem `json:"filesystem"`
@@ -190,6 +214,16 @@ type metadata struct {
Batches []metadataBatch `json:"batches"` Batches []metadataBatch `json:"batches"`
} }
type metadataUsage struct {
Root string `json:"root"`
Complete bool `json:"complete"`
ActualBytes *int64 `json:"actual_bytes"`
ApparentBytes *int64 `json:"apparent_bytes"`
FileCount *int `json:"file_count"`
DirCount *int `json:"dir_count"`
Errors []string `json:"errors"`
}
type metadataFilesystem struct { type metadataFilesystem struct {
MountPoint string `json:"mount_point"` MountPoint string `json:"mount_point"`
MountSource string `json:"mount_source"` MountSource string `json:"mount_source"`
@@ -313,6 +347,14 @@ func (r *Reader) Snapshot(ctx context.Context) Snapshot {
return invalid(snapshot, fmt.Sprintf("元数据 root=%s 与配置 %s 不一致", root, expectedRoot)) return invalid(snapshot, fmt.Sprintf("元数据 root=%s 与配置 %s 不一致", root, expectedRoot))
} }
snapshot.Root = root snapshot.Root = root
backupRoot, usage, quotaBytes, quotaError, err := projectUsageAndQuota(r.config.BackupRoot, root, file)
if err != nil {
return invalid(snapshot, err.Error())
}
snapshot.BackupRoot = backupRoot
snapshot.Usage = usage
snapshot.QuotaBytes = quotaBytes
snapshot.QuotaError = quotaError
if err := validateBatches(root, file.Batches); err != nil { if err := validateBatches(root, file.Batches); err != nil {
return invalid(snapshot, err.Error()) return invalid(snapshot, err.Error())
} }
@@ -366,6 +408,66 @@ func (r *Reader) observedAt() string {
return r.now().UTC().Format(time.RFC3339) return r.now().UTC().Format(time.RFC3339)
} }
// projectUsageAndQuota 校验「备份根占用」与「配额」并把它们投影给页面。
//
// 三条独立边界:
// 1. 旧采集器没有 usage/quota —— 批次照旧可用,占用与配额显式「未上报」,绝不用批次和冒充;
// 2. 路径必须与部署配置的备份根完全一致,批次根必须在其下 —— 否则整份快照拒绝;
// 3. 遍历不完整/配额非法 —— 只把对应字段降为未知,不牵连批次表与磁盘容量。
func projectUsageAndQuota(configuredRoot, batchRoot string, file metadata) (string, Usage, *int64, string, error) {
expected := path.Clean(strings.TrimSpace(configuredRoot))
reported := strings.TrimSpace(file.Usage.Root)
declared := strings.TrimSpace(file.BackupRoot)
usageReported := reported != "" || declared != "" || file.Usage.Complete ||
file.Usage.ActualBytes != nil || len(file.Usage.Errors) > 0
if !usageReported {
quotaError := strings.TrimSpace(file.QuotaError)
if quotaError == "" {
quotaError = "采集器未上报备份配额(需要升级采集器)"
}
return expected, Usage{Error: "采集器未上报备份根占用(需要升级采集器)"}, nil, quotaError, nil
}
if expected == "" || !path.IsAbs(expected) {
return "", Usage{}, nil, "", errors.New("备份根未配置:无法校验快照里的根占用")
}
if reported != expected || declared != expected {
return "", Usage{}, nil, "", fmt.Errorf("快照 backup_root=%q/usage.root=%q 与配置 %q 不一致", declared, reported, expected)
}
if batchRoot != expected && !strings.HasPrefix(batchRoot, expected+"/") {
return "", Usage{}, nil, "", fmt.Errorf("批次根 %s 不在备份根 %s 下", batchRoot, expected)
}
usage := Usage{Root: reported, Complete: file.Usage.Complete}
if file.Usage.Complete && file.Usage.ActualBytes != nil {
usage.Measured = true
usage.ActualBytes = file.Usage.ActualBytes
usage.ApparentBytes = file.Usage.ApparentBytes
usage.FileCount = file.Usage.FileCount
usage.DirCount = file.Usage.DirCount
} else {
usage.Complete = false
usage.ActualBytes = nil
usage.ApparentBytes = nil
usage.FileCount = nil
usage.DirCount = nil
reasons := limit(file.Usage.Errors, 3)
if len(reasons) == 0 {
usage.Error = "备份根占用未知:采集器未给出完整字节"
} else {
usage.Error = "备份根占用未知:" + strings.Join(reasons, ";")
}
}
quota := file.QuotaBytes
quotaError := strings.TrimSpace(file.QuotaError)
if quota != nil && *quota <= 0 {
quota = nil
quotaError = fmt.Sprintf("备份配额必须为正整数:%d", *file.QuotaBytes)
}
if quota == nil && quotaError == "" {
quotaError = "采集器未上报备份配额(需要升级采集器)"
}
return expected, usage, quota, quotaError, nil
}
func invalid(snapshot Snapshot, reason string) Snapshot { func invalid(snapshot Snapshot, reason string) Snapshot {
snapshot.Metadata.Valid = false snapshot.Metadata.Valid = false
snapshot.Metadata.Complete = false snapshot.Metadata.Complete = false
@@ -374,6 +476,8 @@ func invalid(snapshot Snapshot, reason string) Snapshot {
snapshot.Batches = []Batch{} snapshot.Batches = []Batch{}
snapshot.Capacity = Capacity{Error: reason} snapshot.Capacity = Capacity{Error: reason}
snapshot.Totals = Totals{} snapshot.Totals = Totals{}
snapshot.Usage = Usage{Error: reason}
snapshot.QuotaBytes = nil
return snapshot return snapshot
} }
+85 -4
View File
@@ -28,8 +28,14 @@ func validMetadata() metadata {
Host: "weknora-test", Host: "weknora-test",
Source: "weknora-test:" + hostRoot, Source: "weknora-test:" + hostRoot,
Root: hostRoot, Root: hostRoot,
Complete: true, BackupRoot: "/srv/kb-backups",
Errors: []string{}, Usage: metadataUsage{
Root: "/srv/kb-backups", Complete: true,
ActualBytes: int64p(20000), ApparentBytes: int64p(18000), FileCount: intp(12), DirCount: intp(4),
},
QuotaBytes: int64p(53687091200),
Complete: true,
Errors: []string{},
Filesystem: metadataFilesystem{ Filesystem: metadataFilesystem{
MountPoint: "/srv/kb-backups", MountPoint: "/srv/kb-backups",
MountSource: "/dev/sdb1", MountSource: "/dev/sdb1",
@@ -108,7 +114,7 @@ func writeMetadata(t *testing.T, value metadata) string {
} }
func readerAt(filename string, now time.Time) *Reader { func readerAt(filename string, now time.Time) *Reader {
reader := New(Config{MetadataPath: filename, HostRoot: hostRoot, Source: "configured", MaxAge: 15 * time.Minute}) reader := New(Config{MetadataPath: filename, HostRoot: hostRoot, BackupRoot: "/srv/kb-backups", Source: "configured", MaxAge: 15 * time.Minute})
reader.now = func() time.Time { return now } reader.now = func() time.Time { return now }
return reader return reader
} }
@@ -156,7 +162,82 @@ func TestSnapshotReadsHostMetadataAndPaths(t *testing.T) {
t.Fatalf("汇总不对: %+v", snapshot.Totals) t.Fatalf("汇总不对: %+v", snapshot.Totals)
} }
if snapshot.Source != "weknora-test:"+hostRoot || snapshot.Measurement != "host_collector" { if snapshot.Source != "weknora-test:"+hostRoot || snapshot.Measurement != "host_collector" {
t.Fatalf("来源/测量方式不对: %+v", snapshot) t.Fatalf("来源/测量方式不对: %+v", snapshot.Source)
}
if snapshot.BackupRoot != "/srv/kb-backups" || !snapshot.Usage.Measured || snapshot.Usage.ActualBytes == nil || *snapshot.Usage.ActualBytes != 20000 {
t.Fatalf("备份根占用没有投影: %+v", snapshot.Usage)
}
if snapshot.QuotaBytes == nil || *snapshot.QuotaBytes != 53687091200 {
t.Fatalf("配额没有投影: %v", snapshot.QuotaBytes)
}
}
func TestSnapshotLegacyMetadataKeepsBatchesButOccupancyUnknown(t *testing.T) {
value := validMetadata()
value.BackupRoot = ""
value.Usage = metadataUsage{}
value.QuotaBytes = nil
value.QuotaError = ""
filename := writeMetadata(t, value)
snapshot := readerAt(filename, time.Date(2026, 11, 20, 1, 5, 0, 0, time.UTC)).Snapshot(context.Background())
if !snapshot.Metadata.Valid || !snapshot.Metadata.Complete {
t.Fatalf("旧快照仍应可用: %+v", snapshot.Metadata)
}
if len(snapshot.Batches) != 3 || snapshot.Totals.ActualBytes == nil {
t.Fatalf("旧快照的批次不能丢: %+v", snapshot.Batches)
}
if snapshot.Usage.Measured || snapshot.Usage.ActualBytes != nil || snapshot.Usage.Error == "" {
t.Fatalf("缺少 usage 必须显式未上报: %+v", snapshot.Usage)
}
if snapshot.QuotaBytes != nil || snapshot.QuotaError == "" {
t.Fatalf("缺少配额必须显式未上报: %v/%q", snapshot.QuotaBytes, snapshot.QuotaError)
}
}
func TestSnapshotRejectsUsageRootMismatch(t *testing.T) {
value := validMetadata()
value.Usage.Root = "/data/kb-backups"
filename := writeMetadata(t, value)
snapshot := readerAt(filename, time.Date(2026, 11, 20, 1, 5, 0, 0, time.UTC)).Snapshot(context.Background())
if snapshot.Metadata.Valid || len(snapshot.Batches) != 0 || snapshot.Usage.Measured {
t.Fatalf("占用根与配置不一致必须整块拒绝: %+v", snapshot)
}
if !strings.Contains(snapshot.Error, "不一致") {
t.Fatalf("不一致原因不清: %q", snapshot.Error)
}
}
func TestSnapshotIncompleteUsageDoesNotBlankBatches(t *testing.T) {
value := validMetadata()
value.Usage.Complete = false
value.Usage.ActualBytes = int64p(123) // 部分计数:必须被丢弃
value.Usage.Errors = []string{"遍历失败:PermissionError: Permission denied"}
filename := writeMetadata(t, value)
snapshot := readerAt(filename, time.Date(2026, 11, 20, 1, 5, 0, 0, time.UTC)).Snapshot(context.Background())
if !snapshot.Metadata.Valid || !snapshot.Metadata.Complete {
t.Fatalf("根占用不完整不能牵连整份快照: %+v", snapshot.Metadata)
}
if len(snapshot.Batches) != 3 || snapshot.Totals.ActualBytes == nil || !snapshot.Capacity.Measured {
t.Fatalf("批次与磁盘容量必须保留: %+v", snapshot)
}
if snapshot.Usage.Measured || snapshot.Usage.ActualBytes != nil || !strings.Contains(snapshot.Usage.Error, "Permission") {
t.Fatalf("占用必须为 null 并带原因: %+v", snapshot.Usage)
}
if snapshot.QuotaBytes == nil || *snapshot.QuotaBytes != 53687091200 {
t.Fatalf("配额是配置事实,应保留: %v", snapshot.QuotaBytes)
}
}
func TestSnapshotRejectsInvalidQuota(t *testing.T) {
value := validMetadata()
value.QuotaBytes = int64p(0)
filename := writeMetadata(t, value)
snapshot := readerAt(filename, time.Date(2026, 11, 20, 1, 5, 0, 0, time.UTC)).Snapshot(context.Background())
if snapshot.QuotaBytes != nil || !strings.Contains(snapshot.QuotaError, "正整数") {
t.Fatalf("非法配额必须降为未知: %v/%q", snapshot.QuotaBytes, snapshot.QuotaError)
}
if !snapshot.Metadata.Valid {
t.Fatalf("配额非法不应否掉批次: %+v", snapshot.Metadata)
} }
} }
+17 -5
View File
@@ -24,11 +24,16 @@ func TestBackupInventoryProjectionPassesRealFields(t *testing.T) {
actual := int64(1024) actual := int64(1024)
databaseActual := int64(512) databaseActual := int64(512)
config := Config{BackupInventory: fakeBackupInventory{snapshot: backupinventory.Snapshot{ config := Config{BackupInventory: fakeBackupInventory{snapshot: backupinventory.Snapshot{
Wired: true, Wired: true,
Root: "/srv/kb-backups/rds-logical", Root: "/srv/kb-backups/rds-logical",
HostRoot: "/srv/kb-backups/rds-logical", HostRoot: "/srv/kb-backups/rds-logical",
Source: "weknora-test:/srv/kb-backups/rds-logical", Source: "weknora-test:/srv/kb-backups/rds-logical",
Metadata: backupinventory.MetadataInfo{Configured: true, Present: true, Valid: true, Fresh: true, Complete: true}, Metadata: backupinventory.MetadataInfo{Configured: true, Present: true, Valid: true, Fresh: true, Complete: true},
BackupRoot: "/srv/kb-backups",
Usage: backupinventory.Usage{
Root: "/srv/kb-backups", Measured: true, Complete: true, ActualBytes: &actual,
},
QuotaBytes: func() *int64 { value := int64(53687091200); return &value }(),
Mount: backupinventory.MountInfo{ Mount: backupinventory.MountInfo{
MountVerified: true, MountVerified: true,
ReadOnly: true, ReadOnly: true,
@@ -70,6 +75,13 @@ func TestBackupInventoryProjectionPassesRealFields(t *testing.T) {
if payload.Data.Batches[0].ActualBytes == nil || *payload.Data.Batches[0].ActualBytes != 1024 { if payload.Data.Batches[0].ActualBytes == nil || *payload.Data.Batches[0].ActualBytes != 1024 {
t.Fatalf("实际占盘字段丢失: %+v", payload.Data.Batches[0]) t.Fatalf("实际占盘字段丢失: %+v", payload.Data.Batches[0])
} }
if payload.Data.BackupRoot != "/srv/kb-backups" || !payload.Data.Usage.Measured ||
payload.Data.Usage.ActualBytes == nil || *payload.Data.Usage.ActualBytes != 1024 {
t.Fatalf("备份根占用字段丢失: %+v", payload.Data.Usage)
}
if payload.Data.QuotaBytes == nil || *payload.Data.QuotaBytes != 53687091200 {
t.Fatalf("配额字段丢失: %v", payload.Data.QuotaBytes)
}
} }
func TestBackupInventoryUnconfiguredIsNotAnError(t *testing.T) { func TestBackupInventoryUnconfiguredIsNotAnError(t *testing.T) {
+43 -11
View File
@@ -3,7 +3,9 @@ package httpapi
import ( import (
"context" "context"
"errors" "errors"
"net"
"net/http" "net/http"
"net/url"
"strings" "strings"
"time" "time"
@@ -37,9 +39,6 @@ func (config Config) handleKBBindings(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{ writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{
"environments": views, "environments": views,
"storage_ready": storageReady, "storage_ready": storageReady,
// The page cannot test the server's transport rule from the browser URL
// alone (a TLS proxy and an untrusted proxy look identical there).
"secret_entry_allowed": consoleSecretEntryAllowed(r, config.QAAITrustTLSProxy, config.WeKnoraAllowPrivateHTTP),
}}) }})
} }
@@ -62,10 +61,6 @@ func (config Config) handleKBBindingCatalog(w http.ResponseWriter, r *http.Reque
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid knowledge base catalog request"}) writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid knowledge base catalog request"})
return return
} }
if input.APIKey != "" && !secretTransportAllowedForPrivateConsole(r, config.QAAITrustTLSProxy, config.WeKnoraAllowPrivateHTTP) {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "密钥仅可通过有效HTTPS或本机回环地址录入;未保存、未发送密钥"})
return
}
catalog, err := config.KBBindings.Catalog(r.Context(), env, input) catalog, err := config.KBBindings.Catalog(r.Context(), env, input)
if err != nil { if err != nil {
writeKBBindingError(w, err) writeKBBindingError(w, err)
@@ -93,10 +88,7 @@ func (config Config) handleKBBindingSave(w http.ResponseWriter, r *http.Request)
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid knowledge base binding request"}) writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid knowledge base binding request"})
return return
} }
if input.APIKey != "" && !secretTransportAllowedForPrivateConsole(r, config.QAAITrustTLSProxy, config.WeKnoraAllowPrivateHTTP) { input.SourceAddress, input.SourceOrigin = requestAuditSource(r)
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "密钥仅可通过有效HTTPS或本机回环地址录入;未保存、未发送密钥"})
return
}
view, err := config.KBBindings.Save(r.Context(), env, input, actorFor(r), config.Now().UTC()) view, err := config.KBBindings.Save(r.Context(), env, input, actorFor(r), config.Now().UTC())
if err != nil { if err != nil {
writeKBBindingError(w, err) writeKBBindingError(w, err)
@@ -125,3 +117,43 @@ func writeKBBindingError(w http.ResponseWriter, err error) {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "knowledge base binding operation failed"}) writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "knowledge base binding operation failed"})
} }
} }
// requestAuditSource records the two facts the save audit needs: which console
// origin the admin used and the client address behind it. Audit only — nothing
// here decides whether a key may be typed or saved.
//
// The nearest proxy appends its peer to the END of X-Forwarded-For, so that hop
// is the trustworthy one; earlier entries are whatever the browser sent. A
// forwarded chain is honoured only when the direct peer is private/loopback
// (the deployment's own nginx), so a request that reaches the API directly
// cannot launder its address through a forged header.
func requestAuditSource(r *http.Request) (address, origin string) {
peer := r.RemoteAddr
if host, _, err := net.SplitHostPort(peer); err == nil {
peer = host
}
ip := net.ParseIP(strings.Trim(peer, "[]"))
if ip != nil {
address = ip.String()
if ip.IsLoopback() || ip.IsPrivate() {
hops := strings.Split(r.Header.Get("X-Forwarded-For"), ",")
if last := net.ParseIP(strings.TrimSpace(hops[len(hops)-1])); last != nil {
address = last.String()
}
}
}
if parsed, err := url.Parse(strings.TrimSpace(r.Header.Get("Origin"))); err == nil &&
(parsed.Scheme == "http" || parsed.Scheme == "https") && parsed.Host != "" {
origin = parsed.Scheme + "://" + parsed.Host
return address, origin
}
if r.Host != "" {
scheme := "http"
if r.TLS != nil || strings.EqualFold(r.Header.Get("X-Forwarded-Proto"), "https") {
scheme = "https"
}
origin = scheme + "://" + r.Host
}
return address, origin
}
+110 -91
View File
@@ -3,7 +3,6 @@ package httpapi
import ( import (
"bytes" "bytes"
"context" "context"
"encoding/json"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"strings" "strings"
@@ -88,34 +87,37 @@ func TestKBBindingSaveReturnsConflictAndKeepsTheOldValue(t *testing.T) {
} }
} }
func TestKBBindingCatalogRequiresSecureKeyTransport(t *testing.T) { func TestKBBindingCatalogAndSaveAcceptTypedKeysOnPlainHTTP(t *testing.T) {
store := &fakeKBBindings{catalog: kbbinding.Catalog{Status: "ok", Message: "已读取 1 个知识库", Page: 1, PageSize: 20, Total: 1}} store := &fakeKBBindings{
views: []kbbinding.View{{Environment: kbbinding.EnvTest, Revision: 1, StorageReady: true}},
catalog: kbbinding.Catalog{Status: "ok", Message: "已读取 1 个知识库", Page: 1, PageSize: 20, Total: 1},
}
config := kbBindingHandler(t, store) config := kbBindingHandler(t, store)
body := `{"base_url":"https://weknora.test.example","key_action":"replace","api_key":"typed-key","page":1,"page_size":20}` catalogBody := `{"base_url":"https://weknora.test.example","key_action":"replace","api_key":"typed-key","page":1,"page_size":20}`
request := httptest.NewRequest(http.MethodPost, "http://console.example/api/v1/kb-bindings/test/catalog", bytes.NewBufferString(body)) request := httptest.NewRequest(http.MethodPost, "http://console.example/api/v1/kb-bindings/test/catalog", bytes.NewBufferString(catalogBody))
request.SetPathValue("environment", "test") request.SetPathValue("environment", "test")
request.Header.Set("X-Governance-Action", "kb-bindings") request.Header.Set("X-Governance-Action", "kb-bindings")
response := httptest.NewRecorder() response := httptest.NewRecorder()
config.handleKBBindingCatalog(response, request) config.handleKBBindingCatalog(response, request)
if response.Code != http.StatusBadRequest || !strings.Contains(response.Body.String(), "HTTPS") {
t.Fatalf("plain HTTP key entry status=%d body=%s", response.Code, response.Body.String())
}
request = httptest.NewRequest(http.MethodPost, "http://127.0.0.1:8080/api/v1/kb-bindings/test/catalog", bytes.NewBufferString(body))
request.SetPathValue("environment", "test")
request.Header.Set("X-Governance-Action", "kb-bindings")
response = httptest.NewRecorder()
config.handleKBBindingCatalog(response, request)
if response.Code != http.StatusOK { if response.Code != http.StatusOK {
t.Fatalf("loopback catalog status=%d body=%s", response.Code, response.Body.String()) t.Fatalf("plain HTTP catalog status=%d body=%s", response.Code, response.Body.String())
}
var payload map[string]any
if err := json.Unmarshal(response.Body.Bytes(), &payload); err != nil {
t.Fatal(err)
} }
if strings.Contains(response.Body.String(), "typed-key") { if strings.Contains(response.Body.String(), "typed-key") {
t.Fatal("catalog response echoed the typed key") t.Fatal("catalog response echoed the typed key")
} }
saveBody := `{"base_revision":1,"base_url":"https://weknora.test.example","key_action":"replace","api_key":"typed-key","internal_kb_id":"kb-in","external_kb_id":"kb-out"}`
request = httptest.NewRequest(http.MethodPut, "http://console.example/api/v1/kb-bindings/test", bytes.NewBufferString(saveBody))
request.SetPathValue("environment", "test")
request.Header.Set("X-Governance-Action", "kb-bindings")
response = httptest.NewRecorder()
config.handleKBBindingSave(response, request)
if response.Code != http.StatusOK {
t.Fatalf("plain HTTP save status=%d body=%s", response.Code, response.Body.String())
}
if store.lastSave.APIKey != "typed-key" {
t.Fatalf("save did not forward the typed key: %q", store.lastSave.APIKey)
}
} }
func TestKBBindingWritesAreAdminOnly(t *testing.T) { func TestKBBindingWritesAreAdminOnly(t *testing.T) {
@@ -129,95 +131,112 @@ func TestKBBindingWritesAreAdminOnly(t *testing.T) {
} }
} }
func TestKBBindingsReadReportsSecretEntryCapability(t *testing.T) { func TestKBBindingsReadDoesNotReportTransportCapability(t *testing.T) {
store := &fakeKBBindings{views: []kbbinding.View{{Environment: kbbinding.EnvTest, Revision: 1, StorageReady: true}}} store := &fakeKBBindings{views: []kbbinding.View{{Environment: kbbinding.EnvTest, Revision: 1, StorageReady: true}}}
for _, tc := range []struct { config := kbBindingHandler(t, store)
name string request := httptest.NewRequest(http.MethodGet, "/api/v1/kb-bindings", nil)
host string request.Host = "172.29.151.11:28188"
allow bool response := httptest.NewRecorder()
want bool config.handleKBBindings(response, request)
}{ if response.Code != http.StatusOK {
{name: "private console with toggle", host: "172.29.151.11:28188", allow: true, want: true}, t.Fatalf("GET status = %d body=%s", response.Code, response.Body.String())
{name: "private console without toggle", host: "172.29.151.11:28188", want: false}, }
{name: "loopback console", host: "127.0.0.1:8080", want: true}, if strings.Contains(response.Body.String(), "secret_entry_allowed") {
} { t.Fatalf("read response still reports the removed capability: %s", response.Body.String())
t.Run(tc.name, func(t *testing.T) {
config := kbBindingHandler(t, store)
config.WeKnoraAllowPrivateHTTP = tc.allow
request := httptest.NewRequest(http.MethodGet, "/api/v1/kb-bindings", nil)
request.Host = tc.host
response := httptest.NewRecorder()
config.handleKBBindings(response, request)
if response.Code != http.StatusOK {
t.Fatalf("GET status = %d body=%s", response.Code, response.Body.String())
}
var payload struct {
Data struct {
SecretEntryAllowed bool `json:"secret_entry_allowed"`
} `json:"data"`
}
if err := json.Unmarshal(response.Body.Bytes(), &payload); err != nil {
t.Fatal(err)
}
if payload.Data.SecretEntryAllowed != tc.want {
t.Fatalf("secret_entry_allowed = %v, want %v", payload.Data.SecretEntryAllowed, tc.want)
}
})
} }
} }
func TestKBBindingPrivatePlainHTTPWritesRequireToggle(t *testing.T) { func TestKBBindingPlainHTTPWritesDoNotDependOnPrivateToggle(t *testing.T) {
const ( const (
privateHost = "172.29.151.11:28188" saveBody = `{"base_revision":1,"base_url":"http://172.29.151.11:9001","key_action":"replace","api_key":"typed-key","internal_kb_id":"kb-in","external_kb_id":"kb-out"}`
origin = "http://172.29.151.11:28188" catalogBody = `{"base_revision":1,"base_url":"http://172.29.151.11:9001","key_action":"replace","api_key":"typed-key","page":1,"page_size":20}`
) )
store := &fakeKBBindings{ store := &fakeKBBindings{
views: []kbbinding.View{{Environment: kbbinding.EnvTest, Revision: 1, StorageReady: true}}, views: []kbbinding.View{{Environment: kbbinding.EnvTest, Revision: 1, StorageReady: true}},
catalog: kbbinding.Catalog{Status: "ok", Message: "已读取 1 个知识库", Page: 1, PageSize: 20, Total: 1}, catalog: kbbinding.Catalog{Status: "ok", Message: "已读取 1 个知识库", Page: 1, PageSize: 20, Total: 1},
} }
body := `{"base_revision":1,"base_url":"http://172.29.151.11:9001","key_action":"replace","api_key":"typed-key","internal_kb_id":"kb-in","external_kb_id":"kb-out"}` for _, allow := range []bool{false, true} {
config := kbBindingHandler(t, store)
config.WeKnoraAllowPrivateHTTP = allow
save := func(config *Config) *httptest.ResponseRecorder { request := httptest.NewRequest(http.MethodPut, "http://console.example/api/v1/kb-bindings/test", bytes.NewBufferString(saveBody))
request := httptest.NewRequest(http.MethodPut, "http://"+privateHost+"/api/v1/kb-bindings/test", bytes.NewBufferString(body))
request.Host = privateHost
request.SetPathValue("environment", "test") request.SetPathValue("environment", "test")
request.Header.Set("X-Governance-Action", "kb-bindings") request.Header.Set("X-Governance-Action", "kb-bindings")
request.Header.Set("Sec-Fetch-Site", "same-origin")
request.Header.Set("Origin", origin)
response := httptest.NewRecorder() response := httptest.NewRecorder()
config.handleKBBindingSave(response, request) config.handleKBBindingSave(response, request)
return response if response.Code != http.StatusOK {
} t.Fatalf("save with toggle=%v status=%d body=%s", allow, response.Code, response.Body.String())
catalog := func(config *Config) *httptest.ResponseRecorder { }
request := httptest.NewRequest(http.MethodPost, "http://"+privateHost+"/api/v1/kb-bindings/test/catalog", if store.lastSave.APIKey != "typed-key" {
bytes.NewBufferString(`{"base_revision":1,"base_url":"http://172.29.151.11:9001","key_action":"replace","api_key":"typed-key","page":1,"page_size":20}`)) t.Fatalf("save with toggle=%v did not forward the typed key: %q", allow, store.lastSave.APIKey)
request.Host = privateHost }
request = httptest.NewRequest(http.MethodPost, "http://console.example/api/v1/kb-bindings/test/catalog", bytes.NewBufferString(catalogBody))
request.SetPathValue("environment", "test") request.SetPathValue("environment", "test")
request.Header.Set("X-Governance-Action", "kb-bindings") request.Header.Set("X-Governance-Action", "kb-bindings")
request.Header.Set("Sec-Fetch-Site", "same-origin") response = httptest.NewRecorder()
request.Header.Set("Origin", origin)
response := httptest.NewRecorder()
config.handleKBBindingCatalog(response, request) config.handleKBBindingCatalog(response, request)
return response if response.Code != http.StatusOK {
} t.Fatalf("catalog with toggle=%v status=%d body=%s", allow, response.Code, response.Body.String())
}
enabled := kbBindingHandler(t, store) }
enabled.WeKnoraAllowPrivateHTTP = true }
if response := save(enabled); response.Code != http.StatusOK {
t.Fatalf("save with toggle status=%d body=%s", response.Code, response.Body.String()) func TestKBBindingSaveAuditSourcePrefersTheProxyAppendedHop(t *testing.T) {
} store := &fakeKBBindings{views: []kbbinding.View{{Environment: kbbinding.EnvTest, Revision: 1}}}
if store.lastSave.APIKey != "typed-key" { config := kbBindingHandler(t, store)
t.Fatalf("save did not forward the typed key: %q", store.lastSave.APIKey) body := `{"base_revision":0,"base_url":"https://weknora.test.example","key_action":"keep","internal_kb_id":"kb-in","external_kb_id":"kb-out"}`
} for _, tc := range []struct {
if response := catalog(enabled); response.Code != http.StatusOK { name string
t.Fatalf("catalog with toggle status=%d body=%s", response.Code, response.Body.String()) remote string
} forwarded string
origin string
disabled := kbBindingHandler(t, store) proto string
if response := save(disabled); response.Code != http.StatusBadRequest { host string
t.Fatalf("save without toggle status=%d body=%s", response.Code, response.Body.String()) wantAddress string
} wantOrigin string
if response := catalog(disabled); response.Code != http.StatusBadRequest { }{
t.Fatalf("catalog without toggle status=%d body=%s", response.Code, response.Body.String()) {
name: "private proxy appends the real client after a forged hop",
remote: "10.0.0.5:41234", forwarded: "6.6.6.6, 172.29.151.11",
origin: "http://172.29.151.11:8088", host: "172.29.151.11:8088",
wantAddress: "172.29.151.11", wantOrigin: "http://172.29.151.11:8088",
},
{
name: "direct peer cannot launder its address through a forged chain",
remote: "203.0.113.9:41234", forwarded: "6.6.6.6",
host: "console.example",
wantAddress: "203.0.113.9", wantOrigin: "http://console.example",
},
{
name: "trusted proxy scheme fills in for a missing Origin",
remote: "10.0.0.5:41234", proto: "https", host: "kb.example",
wantAddress: "10.0.0.5", wantOrigin: "https://kb.example",
},
} {
t.Run(tc.name, func(t *testing.T) {
request := httptest.NewRequest(http.MethodPut, "http://"+tc.host+"/api/v1/kb-bindings/test", strings.NewReader(body))
request.SetPathValue("environment", "test")
request.Header.Set("X-Governance-Action", "kb-bindings")
request.RemoteAddr = tc.remote
if tc.forwarded != "" {
request.Header.Set("X-Forwarded-For", tc.forwarded)
}
if tc.origin != "" {
request.Header.Set("Origin", tc.origin)
}
if tc.proto != "" {
request.Header.Set("X-Forwarded-Proto", tc.proto)
}
response := httptest.NewRecorder()
config.handleKBBindingSave(response, request)
if response.Code != http.StatusOK {
t.Fatalf("status=%d body=%s", response.Code, response.Body.String())
}
if store.lastSave.SourceAddress != tc.wantAddress || store.lastSave.SourceOrigin != tc.wantOrigin {
t.Fatalf("audit source = %q/%q, want %q/%q",
store.lastSave.SourceAddress, store.lastSave.SourceOrigin, tc.wantAddress, tc.wantOrigin)
}
})
} }
} }
+5 -58
View File
@@ -7,11 +7,11 @@ import (
"strings" "strings"
) )
// secretTransportAllowed is the single rule for typing a secret into the // secretTransportAllowed is the strict rule for QA AI model keys: a real TLS
// console: a real TLS connection, a loopback request, or a same-origin HTTPS // connection, a loopback request, or a same-origin HTTPS request that a trusted
// request that a trusted reverse proxy forwarded. The browser's origin scheme // reverse proxy forwarded. The browser's origin scheme must agree, so a
// must agree, so a plain-HTTP page behind a misconfigured proxy cannot submit // plain-HTTP page behind a misconfigured proxy cannot submit a key even if it
// a key even if it spoofs X-Forwarded-Proto. // spoofs X-Forwarded-Proto. Knowledge base keys deliberately do not use it.
func secretTransportAllowed(r *http.Request, trustTLSProxy bool) bool { func secretTransportAllowed(r *http.Request, trustTLSProxy bool) bool {
if r.TLS != nil { if r.TLS != nil {
return true return true
@@ -26,47 +26,6 @@ func secretTransportAllowed(r *http.Request, trustTLSProxy bool) bool {
return false return false
} }
// secretTransportAllowedForPrivateConsole additionally accepts a same-origin
// fetch from the operator console itself when it is served over plain http on a
// private address. That is the only non-TLS shape this deployment needs, and it
// still requires an exact Origin/Host match. It deliberately does not require
// Sec-Fetch-Site: Chrome only sends Sec-Fetch-* from secure contexts, so an
// http console on a private address never carries that header.
func secretTransportAllowedForPrivateConsole(r *http.Request, trustTLSProxy, allowPrivateHTTP bool) bool {
if secretTransportAllowed(r, trustTLSProxy) {
return true
}
if !allowPrivateHTTP {
return false
}
origin := strings.TrimSpace(r.Header.Get("Origin"))
if origin == "" {
return false
}
parsed, err := url.Parse(origin)
if err != nil || parsed.Host == "" || !strings.EqualFold(parsed.Host, r.Host) {
return false
}
host := parsed.Hostname()
return privateAddressHost(host)
}
// consoleSecretEntryAllowed mirrors the transports the write gates accept, but
// it cannot simply call secretTransportAllowed: that gate guards a write and
// therefore insists on a same-origin Origin header, which a GET navigation
// never sends. Trusting X-Forwarded-Proto alone on a read is safe because
// browsers cannot set it and the deployment already declares the proxy
// trusted; a forged header still cannot make the write gate accept anything.
func consoleSecretEntryAllowed(r *http.Request, trustTLSProxy, allowPrivateHTTP bool) bool {
if r.TLS != nil || loopbackHost(r.Host) {
return true
}
if trustTLSProxy && r.Header.Get("X-Forwarded-Proto") == "https" {
return true
}
return allowPrivateHTTP && privateAddressHost(r.Host)
}
// requestHostname strips the optional port and IPv6 brackets. Brackets come // requestHostname strips the optional port and IPv6 brackets. Brackets come
// off only around a real IPv6 literal: "[127.0.0.1]", "[localhost]" and their // off only around a real IPv6 literal: "[127.0.0.1]", "[localhost]" and their
// ported forms are not address spellings the server or a browser ever emits, // ported forms are not address spellings the server or a browser ever emits,
@@ -103,15 +62,3 @@ func loopbackHost(host string) bool {
ip := net.ParseIP(host) ip := net.ParseIP(host)
return ip != nil && ip.IsLoopback() return ip != nil && ip.IsLoopback()
} }
// privateAddressHost accepts loopback and private addresses. Names other than
// localhost are rejected because the deployment toggle is about addresses,
// not about trusting whatever DNS resolves to.
func privateAddressHost(host string) bool {
host = requestHostname(host)
if strings.EqualFold(host, "localhost") {
return true
}
ip := net.ParseIP(host)
return ip != nil && (ip.IsPrivate() || ip.IsLoopback() || ip.IsLinkLocalUnicast())
}
-73
View File
@@ -1,60 +1,11 @@
package httpapi package httpapi
import ( import (
"crypto/tls"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"testing" "testing"
) )
func TestConsoleSecretEntryAllowedMatrix(t *testing.T) {
cases := []struct {
name string
host string
tls bool
xfp string
trust bool
allow bool
want bool
}{
{name: "direct TLS", host: "console.example", tls: true, want: true},
{name: "loopback name", host: "localhost:8080", want: true},
{name: "loopback v4", host: "127.0.0.1:8080", want: true},
{name: "loopback v6 with port", host: "[::1]:8080", want: true},
{name: "loopback v6 without port", host: "[::1]", want: true},
// Bracketed non-IPv6 hosts are not address spellings; they must not
// borrow loopback trust from the bracket stripper.
{name: "bracketed v4 is not loopback", host: "[127.0.0.1]", want: false},
{name: "bracketed localhost is not loopback", host: "[localhost]", want: false},
{name: "bracketed v4 with toggle is not private", host: "[127.0.0.1]", allow: true, want: false},
{name: "private address with toggle", host: "172.29.151.11:28188", allow: true, want: true},
{name: "private address without toggle", host: "172.29.151.11:28188", want: false},
{name: "link-local with toggle", host: "169.254.10.7:8080", allow: true, want: true},
{name: "public address with toggle", host: "203.0.113.10:8080", allow: true, want: false},
{name: "public name with toggle", host: "console.example", allow: true, want: false},
{name: "trusted proxy https", host: "console.example", xfp: "https", trust: true, want: true},
{name: "untrusted proxy https", host: "console.example", xfp: "https", want: false},
{name: "trusted proxy reports http", host: "console.example", xfp: "http", trust: true, want: false},
// A forged header must not beat the address rule when the proxy is not trusted.
{name: "untrusted proxy on private host", host: "172.29.151.11:28188", xfp: "https", want: false},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
request := httptest.NewRequest(http.MethodGet, "http://placeholder/api/v1/kb-bindings", nil)
request.Host = tc.host
if tc.tls {
request.TLS = &tls.ConnectionState{}
}
if tc.xfp != "" {
request.Header.Set("X-Forwarded-Proto", tc.xfp)
}
if got := consoleSecretEntryAllowed(request, tc.trust, tc.allow); got != tc.want {
t.Fatalf("consoleSecretEntryAllowed = %v, want %v", got, tc.want)
}
})
}
}
func TestSecretTransportAllowedAcceptsBareIPv6Loopback(t *testing.T) { func TestSecretTransportAllowedAcceptsBareIPv6Loopback(t *testing.T) {
request := httptest.NewRequest(http.MethodPost, "http://placeholder/api/v1/kb-bindings/test", nil) request := httptest.NewRequest(http.MethodPost, "http://placeholder/api/v1/kb-bindings/test", nil)
request.Host = "[::1]" request.Host = "[::1]"
@@ -67,25 +18,6 @@ func TestSecretTransportAllowedAcceptsBareIPv6Loopback(t *testing.T) {
} }
} }
// Plain-http consoles are not secure contexts, so Chrome never sends
// Sec-Fetch-* with their fetches. A matching Origin is the whole contract.
func TestSecretTransportPrivateConsoleNeedsOriginNotSecFetch(t *testing.T) {
request := httptest.NewRequest(http.MethodPost, "http://placeholder/api/v1/kb-bindings/test/catalog", nil)
request.Host = "192.168.50.134:18093"
request.Header.Set("Origin", "http://192.168.50.134:18093")
if !secretTransportAllowedForPrivateConsole(request, false, true) {
t.Fatal("same-origin private console without Sec-Fetch-Site was rejected")
}
request.Header.Set("Origin", "http://evil.example")
if secretTransportAllowedForPrivateConsole(request, false, true) {
t.Fatal("cross-origin request was accepted as a private console")
}
request.Header.Set("Origin", "http://192.168.50.134:18093")
if secretTransportAllowedForPrivateConsole(request, false, false) {
t.Fatal("private console was accepted with the deployment toggle off")
}
}
func TestSecretTransportRejectsBracketedNonIPv6Hosts(t *testing.T) { func TestSecretTransportRejectsBracketedNonIPv6Hosts(t *testing.T) {
for _, host := range []string{"[127.0.0.1]", "[127.0.0.1]:28188", "[localhost]", "[localhost]:28188"} { for _, host := range []string{"[127.0.0.1]", "[127.0.0.1]:28188", "[localhost]", "[localhost]:28188"} {
request := httptest.NewRequest(http.MethodPost, "http://placeholder/api/v1/kb-bindings/test", nil) request := httptest.NewRequest(http.MethodPost, "http://placeholder/api/v1/kb-bindings/test", nil)
@@ -93,11 +25,6 @@ func TestSecretTransportRejectsBracketedNonIPv6Hosts(t *testing.T) {
if secretTransportAllowed(request, false) { if secretTransportAllowed(request, false) {
t.Fatalf("Host %q was accepted as a loopback transport", host) t.Fatalf("Host %q was accepted as a loopback transport", host)
} }
request.Header.Set("Sec-Fetch-Site", "same-origin")
request.Header.Set("Origin", "http://"+host)
if secretTransportAllowedForPrivateConsole(request, false, true) {
t.Fatalf("Host %q was accepted as a private console", host)
}
} }
} }
+2 -2
View File
@@ -142,8 +142,8 @@ type Config struct {
// internal/external bindings saved together. Nil keeps the page read-only // internal/external bindings saved together. Nil keeps the page read-only
// and reports unavailable, never a fake success. // and reports unavailable, never a fake success.
KBBindings KBBindingStore KBBindings KBBindingStore
// WeKnoraAllowPrivateHTTP 允许在私网治理台(明文 http)上录入 WeKnora API Key; // WeKnoraAllowPrivateHTTP 决定客户端/探活是否放行同网段 http(生产 18093 反代);
// 同时决定客户端/探活是否放行同网段 http(生产 18093 反代)。 // 不再参与控制台密钥录入判定。
WeKnoraAllowPrivateHTTP bool WeKnoraAllowPrivateHTTP bool
// ProductionBindings is the 源库 → 目标库 mapping store; ProductionKnowledgeBases // ProductionBindings is the 源库 → 目标库 mapping store; ProductionKnowledgeBases
// enumerates the production-side bases the operator can bind. // enumerates the production-side bases the operator can bind.
+4
View File
@@ -112,6 +112,10 @@ type SaveInput struct {
APIKey string `json:"api_key"` APIKey string `json:"api_key"`
InternalKBID string `json:"internal_kb_id"` InternalKBID string `json:"internal_kb_id"`
ExternalKBID string `json:"external_kb_id"` ExternalKBID string `json:"external_kb_id"`
// 审计用:由 HTTP 层按连接事实填充,不属于请求体(严格解码下客户端
// 提交同名字段会被拒绝)。只是事后取证,不参与任何放行判定。
SourceAddress string `json:"-"`
SourceOrigin string `json:"-"`
} }
// Target is what consumers (readiness, upload, listing, monitoring) need to // Target is what consumers (readiness, upload, listing, monitoring) need to
+12
View File
@@ -12,6 +12,7 @@ import (
"strings" "strings"
"testing" "testing"
"time" "time"
"unicode/utf8"
"github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5"
@@ -209,3 +210,14 @@ func TestUnboundSideReportsWhereItFallsBackTo(t *testing.T) {
t.Fatalf("bound view must not claim a fallback: %+v", bound) t.Fatalf("bound view must not claim a fallback: %+v", bound)
} }
} }
func TestAuditTextBoundsWithoutSplittingUTF8(t *testing.T) {
// 恶意 Origin 可能带非 ASCII:截断若切开跑码点,PostgreSQL text 会拒收整条保存。
got := auditText(strings.Repeat("密钥", 100), 10)
if len(got) > 10 || !utf8.ValidString(got) || got == "" {
t.Fatalf("auditText = %q (%d bytes)", got, len(got))
}
if auditText(" ", 10) != "" {
t.Fatal("blank audit source must stay empty, never a placeholder")
}
}
@@ -286,6 +286,8 @@ func TestClearKeyKeepsNamesIDsAndFrozenIdentity(t *testing.T) {
cleared, err := store.Save(ctx, kbbinding.EnvTest, kbbinding.SaveInput{ cleared, err := store.Save(ctx, kbbinding.EnvTest, kbbinding.SaveInput{
BaseRevision: saved.Revision, BaseURL: server.URL, KeyAction: "clear", BaseRevision: saved.Revision, BaseURL: server.URL, KeyAction: "clear",
InternalKBID: saved.InternalKBID, ExternalKBID: saved.ExternalKBID, InternalKBID: saved.InternalKBID, ExternalKBID: saved.ExternalKBID,
// 非 HTTPS 控制台保存:审计行必须能还原当时的入口与客户端地址。
SourceAddress: "172.29.151.11", SourceOrigin: "http://172.29.151.11:8088",
}, "admin", now.Add(time.Minute)) }, "admin", now.Add(time.Minute))
if err != nil { if err != nil {
t.Fatalf("clear Save() error = %v", err) t.Fatalf("clear Save() error = %v", err)
@@ -364,6 +366,17 @@ WHERE environment='test' AND revision=2`).Scan(&keyConfigured); err != nil {
if keyConfigured { if keyConfigured {
t.Fatal("history still says the cleared key is configured") t.Fatal("history still says the cleared key is configured")
} }
var sourceAddress, sourceOrigin, sourceActor string
var sourceEnv string
if err := pool.QueryRow(ctx, `
SELECT source_address,source_origin,actor,environment FROM weknora_environment_binding_history
WHERE environment='test' AND revision=2`).Scan(&sourceAddress, &sourceOrigin, &sourceActor, &sourceEnv); err != nil {
t.Fatal(err)
}
if sourceAddress != "172.29.151.11" || sourceOrigin != "http://172.29.151.11:8088" ||
sourceActor != "admin" || sourceEnv != "test" {
t.Fatalf("save audit = %q/%q actor=%q env=%q", sourceAddress, sourceOrigin, sourceActor, sourceEnv)
}
var secretColumns int var secretColumns int
if err := pool.QueryRow(ctx, ` if err := pool.QueryRow(ctx, `
SELECT COUNT(*) FROM information_schema.columns SELECT COUNT(*) FROM information_schema.columns
+22 -3
View File
@@ -7,6 +7,7 @@ import (
"net/http" "net/http"
"strings" "strings"
"time" "time"
"unicode/utf8"
"github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5"
@@ -206,9 +207,11 @@ ON CONFLICT(environment) DO UPDATE SET
} }
if _, err := tx.Exec(ctx, ` if _, err := tx.Exec(ctx, `
INSERT INTO weknora_environment_binding_history( INSERT INTO weknora_environment_binding_history(
environment,revision,base_url,key_configured,internal_kb_id,external_kb_id,verification,actor,created_at) environment,revision,base_url,key_configured,internal_kb_id,external_kb_id,verification,actor,created_at,
VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9)`, source_address,source_origin)
env, revision, baseURL, len(sealed) > 0, internal, external, verification, actor, now.UTC()); err != nil { VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11)`,
env, revision, baseURL, len(sealed) > 0, internal, external, verification, actor, now.UTC(),
auditText(input.SourceAddress, 128), auditText(input.SourceOrigin, 300)); err != nil {
return View{}, ErrStorage return View{}, ErrStorage
} }
replan := postgresstore.RoutingBindingReplanResult{} replan := postgresstore.RoutingBindingReplanResult{}
@@ -353,3 +356,19 @@ func shortID(value string) string {
} }
return value return value
} }
// auditText bounds one audit column. An empty value stays empty: the audit row
// must never present a guessed address as fact. Truncation stops on a rune
// boundary because PostgreSQL text refuses invalid UTF-8 (a hostile Origin
// header must not turn a save into a storage error).
func auditText(value string, limit int) string {
value = strings.ToValidUTF8(strings.TrimSpace(value), "")
if len(value) <= limit {
return value
}
value = value[:limit]
for len(value) > 0 && !utf8.ValidString(value) {
value = value[:len(value)-1]
}
return value
}
@@ -0,0 +1,3 @@
ALTER TABLE weknora_environment_binding_history
DROP COLUMN IF EXISTS source_origin,
DROP COLUMN IF EXISTS source_address;
@@ -0,0 +1,6 @@
-- 「知识库绑定」保存审计需要回答“从哪个地址录入的”:管理员可能在非 HTTPS
-- 控制台录入明文密钥,事后只能靠这条记录还原当时的访问入口。来源地址只做
-- 审计,不参与任何放行/拒绝判定;空串表示无法可靠解析,不用猜测值填充。
ALTER TABLE weknora_environment_binding_history
ADD COLUMN IF NOT EXISTS source_address TEXT NOT NULL DEFAULT '',
ADD COLUMN IF NOT EXISTS source_origin TEXT NOT NULL DEFAULT '';
@@ -11,8 +11,15 @@ func TestEmbeddedMigrationsAreVersionSorted(t *testing.T) {
if err != nil { if err != nil {
t.Fatalf("loadMigrations() error = %v", err) t.Fatalf("loadMigrations() error = %v", err)
} }
if len(migrations) != 82 { if len(migrations) != 83 {
t.Fatalf("migration count = %d, want 82", len(migrations)) t.Fatalf("migration count = %d, want 83", len(migrations))
}
// 83 是密钥保存审计的来源列:只追加取证字段,来源解析不出时留空。
if source := migrations[82]; source.Version != 83 ||
!strings.Contains(source.UpSQL, "source_address") ||
!strings.Contains(source.UpSQL, "source_origin") ||
!strings.Contains(source.DownSQL, "DROP COLUMN IF EXISTS source_address") {
t.Fatalf("migration 83 = %#v", source)
} }
// 82 是实例身份约束:绑定冻结候选实例地址/租户,发布项与测试对象都记录 // 82 是实例身份约束:绑定冻结候选实例地址/租户,发布项与测试对象都记录
// 实际实例身份;克隆实例同名/同 ID 不能冒充。 // 实际实例身份;克隆实例同名/同 ID 不能冒充。
+14
View File
@@ -22,10 +22,22 @@ set -euo pipefail
KB_BACKUP_ROOT="${KB_BACKUP_ROOT:-/srv/kb-backups}" KB_BACKUP_ROOT="${KB_BACKUP_ROOT:-/srv/kb-backups}"
CONFIG_FILE="${CONFIG_FILE:-/etc/knowledge-governance/backup.env}" CONFIG_FILE="${CONFIG_FILE:-/etc/knowledge-governance/backup.env}"
SUBDIRS=(target-kb-snapshots rds-logical es-snapshots logs) SUBDIRS=(target-kb-snapshots rds-logical es-snapshots logs)
# 配额与备份根写在同一份契约里:页面/采集器/备份脚本读的是同一个值。
# 重跑本脚本时沿用已有配额,避免把运维显式调过的值重置回默认。
QUOTA_BYTES="${KB_BACKUP_QUOTA_BYTES:-}"
if [ -z "$QUOTA_BYTES" ] && [ -f "$CONFIG_FILE" ]; then
QUOTA_BYTES="$(sed -n 's/^[[:space:]]*KB_BACKUP_QUOTA_BYTES=//p' "$CONFIG_FILE" | tail -1 | tr -d "\"' \r")"
fi
QUOTA_BYTES="${QUOTA_BYTES:-53687091200}"
case "$QUOTA_BYTES" in
''|*[!0-9]*) echo "KB_BACKUP_QUOTA_BYTES 必须是正整数,收到 '$QUOTA_BYTES'" >&2; exit 1 ;;
esac
[ "$QUOTA_BYTES" -gt 0 ] || { echo "KB_BACKUP_QUOTA_BYTES 必须大于 0" >&2; exit 1; }
PRINT_ONLY=0 PRINT_ONLY=0
[ "${1:-}" = "--print" ] && PRINT_ONLY=1 [ "${1:-}" = "--print" ] && PRINT_ONLY=1
echo "备份根目录: $KB_BACKUP_ROOT" echo "备份根目录: $KB_BACKUP_ROOT"
echo "备份配额 : $QUOTA_BYTES 字节"
echo "配置文件 : $CONFIG_FILE" echo "配置文件 : $CONFIG_FILE"
echo "子目录 :" echo "子目录 :"
total_bytes=0 total_bytes=0
@@ -52,6 +64,8 @@ mkdir -p "$(dirname "$CONFIG_FILE")"
cat >"$CONFIG_FILE" <<EOF cat >"$CONFIG_FILE" <<EOF
# 由 scripts/backup_layout.sh 生成:备份目录契约(换主机时只改这里) # 由 scripts/backup_layout.sh 生成:备份目录契约(换主机时只改这里)
KB_BACKUP_ROOT=$KB_BACKUP_ROOT KB_BACKUP_ROOT=$KB_BACKUP_ROOT
# 备份根累计占用硬上限(字节):采集器上报、logical-backup.sh 执行同一条线。
KB_BACKUP_QUOTA_BYTES=$QUOTA_BYTES
EOF EOF
echo "已写入 $CONFIG_FILE" echo "已写入 $CONFIG_FILE"
echo echo
+51 -5
View File
@@ -8,6 +8,7 @@ import re
import sys import sys
from urllib.error import HTTPError from urllib.error import HTTPError
import qa_report
import candidate_release as candidate import candidate_release as candidate
import candidate_runtime as runtime import candidate_runtime as runtime
import hifox_release_trigger as hfx import hifox_release_trigger as hfx
@@ -38,6 +39,12 @@ def timeline(task_id):
def owner_plan(task_id): def owner_plan(task_id):
task(task_id) task(task_id)
single = STATE / 'handoffs' / (task_id + '.single.json')
if single.is_file():
plan = cd.read_json(cd.immutable_file(single))
candidate.check_plan(plan)
cd.require(plan['task'] == task_id and [i['task'] for i in plan['items']] == [task_id], 'invalid single-task plan')
return plan
matches = [candidate.FENCE.search(row.get('content') or '') for row in reversed(sorted( 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] 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) match = next((row for row in matches if row), None)
@@ -105,24 +112,35 @@ def publish_candidate(plan, receipt, run):
f'发布任务 {task(plan["task"])["url"]}') f'发布任务 {task(plan["task"])["url"]}')
body += ('\n\n请在本包执行实测,用 kg-qa-v1 代码块回填 sha、bundle、url、required、passed、failed、blocked、verdict。' body += ('\n\n请在本包执行实测,用 kg-qa-v1 代码块回填 sha、bundle、url、required、passed、failed、blocked、verdict。'
'业务单记录用例,发布单记录批次回归;每份报告附对应证据。') '业务单记录用例,发布单记录批次回归;每份报告附对应证据。')
single = [item['task'] for item in plan['items']] == [plan['task']]
if single:
body = body.split('业务单记录用例')[0] + '请在本单逐项记录实测证据。在结构化报告加 cases 对象,business 和 regression 各列本轮通过的业务及同批回归用例编号,两组编号独立,合计等于 required。验收登记后,由负责人在本单切到待发布。'
record = task(plan['task']) if single else {}
manual = (record.get('typeId') or (record.get('type') or {}).get('id')) == '1b7f1bb1-72c2-4106-b305-85604cf6d7e2'
if manual:
body += '\n候选已就绪。负责人可在本单切到「测试中」启动同包测试。'
if single:
body += '\nQA 请在测试机用 ~/.local/bin/kg-qa-report 从本轮用例清单生成报告,逐项填写结果和证据,正式候选无法登录时报告 blocked。'
key = 'ready ' + receipt['bundle'] key = 'ready ' + receipt['bundle']
add_comment(plan['task'], key, body) add_comment(plan['task'], key, body)
for item in plan['items']: for item in plan['items']:
item_id = item['task'] item_id = item['task']
status = (task(item_id).get('status') or {}).get('id') status = (task(item_id).get('status') or {}).get('id')
if manual and status == WAIT_TEST:
continue
if status == TESTING: if status == TESTING:
if not any(f'[KG candidate {key}]' in (row.get('content') or '') for row in timeline(item_id)): if not any(f'[KG candidate {key}]' in (row.get('content') or '') for row in timeline(item_id)):
cd.require((STATE / 'handoffs' / (plan['task'] + '.preview.json')).is_file(), cd.require((STATE / 'handoffs' / (plan['task'] + '.preview.json')).is_file(),
f'{item_id}: another QA round is already in progress') f'{item_id}: another QA round is already in progress')
add_comment(item_id, key, body) add_comment(item_id, key, body)
if (STATE / 'handoffs' / (plan['task'] + '.preview.json')).is_file(): if single or (STATE / 'handoffs' / (plan['task'] + '.preview.json')).is_file():
summon_qa(plan, item_id, body) summon_qa(plan, item_id, body)
continue continue
cd.require(status == WAIT_TEST, f'{item_id}: requirement must be in 待测试') cd.require(status == WAIT_TEST, f'{item_id}: requirement must be in 待测试')
add_comment(item_id, key, body) add_comment(item_id, key, body)
cd.require((task(item_id).get('status') or {}).get('id') == WAIT_TEST, cd.require((task(item_id).get('status') or {}).get('id') == WAIT_TEST,
f'{item_id}: task status changed during candidate handoff') f'{item_id}: task status changed during candidate handoff')
managed = (STATE / 'handoffs' / (plan['task'] + '.preview.json')).is_file() managed = single or (STATE / 'handoffs' / (plan['task'] + '.preview.json')).is_file()
invitation = STATE / cd.acceptance_digest(plan) / (item_id + '.qa-invite.json') invitation = STATE / cd.acceptance_digest(plan) / (item_id + '.qa-invite.json')
if managed: if managed:
cd.record(invitation, {'state': 'sending'}) cd.record(invitation, {'state': 'sending'})
@@ -131,7 +149,7 @@ def publish_candidate(plan, receipt, run):
if managed: if managed:
cd.record(invitation, {'state': 'sent', 'via': 'status'}) cd.record(invitation, {'state': 'sent', 'via': 'status'})
if (STATE / 'handoffs' / (plan['task'] + '.preview.json')).is_file(): if not single and (STATE / 'handoffs' / (plan['task'] + '.preview.json')).is_file():
summon_qa(plan, plan['task'], body + '\n请实测批次回归,报告写在本发布单。') summon_qa(plan, plan['task'], body + '\n请实测批次回归,报告写在本发布单。')
@@ -146,6 +164,27 @@ def summon_qa(plan, target, body):
cd.record(path, {'state': 'sent', 'result': result}) cd.record(path, {'state': 'sent', 'result': result})
def acceptance_body(sha, bundle, tasks, reports, url_of, links):
"""State the registered verdict and its counts on the task itself, not only in metadata."""
lines = ['批次验收通过', '', f'提交 `{sha}`', '', f'归档 `{bundle}`', '']
single = len(tasks) == 1
for item in tasks:
row, result = reports[item]
if single:
lines.append(f'必测 {result["required"]} · 通过 {result["passed"]} · 失败 {result["failed"]} '
f'· 阻塞 {result["blocked"]} · 结论 {result["verdict"]}')
if result.get('url'):
lines.append(f'候选地址 {result["url"]}')
cases = result.get('cases') or {}
for group, label in (('business', '业务用例'), ('regression', '回归用例')):
if isinstance(cases.get(group), list) and cases[group]:
lines.append(f'{label}({len(cases[group])}):' + '、'.join(cases[group]))
else:
lines.append(f'{url_of(item)}#comment-{row["id"]}')
lines += ['', '需求验收与批次回归报告', links]
return '\n'.join(lines)
def register(task_id): def register(task_id):
plan = owner_plan(task_id) plan = owner_plan(task_id)
directory = STATE / cd.acceptance_digest(plan) directory = STATE / cd.acceptance_digest(plan)
@@ -154,7 +193,7 @@ def register(task_id):
cd.require(receipt.get('mode') == 'acceptance', 'isolated smoke results are ineligible for publication') cd.require(receipt.get('mode') == 'acceptance', 'isolated smoke results are ineligible for publication')
runtime.attest(directory / 'bundle', receipt) runtime.attest(directory / 'bundle', receipt)
reports = {} reports = {}
tasks = [item['task'] for item in plan['items']] + [task_id] tasks = list(dict.fromkeys([item['task'] for item in plan['items']] + [task_id]))
for item_id in tasks: for item_id in tasks:
obj = task(item_id) obj = task(item_id)
rows = sorted(timeline(item_id), key=lambda row: row.get('createdAt', ''), reverse=True) rows = sorted(timeline(item_id), key=lambda row: row.get('createdAt', ''), reverse=True)
@@ -170,6 +209,13 @@ def register(task_id):
row = reports[item_id][0] row = reports[item_id][0]
cd.require(cd.matches(cd.UUID, row.get('id')) and obj.get('url', '').startswith('https://app.hifox.com/'), cd.require(cd.matches(cd.UUID, row.get('id')) and obj.get('url', '').startswith('https://app.hifox.com/'),
'invalid QA evidence link') 'invalid QA evidence link')
if [item['task'] for item in plan['items']] == [task_id] and task_id in reports:
accepted = cd.metadata(task(task_id), 'cd_acceptance') or {}
if (accepted.get('sha'), accepted.get('bundle')) != (receipt['sha'], receipt['bundle']):
try:
qa_report.verify_report(reports[task_id][1])
except ValueError as error:
raise cd.CDError(f'QA 请在测试机提交逐项报告:{error}') from error
candidate.check_qa(plan, receipt, reports, QA_AUTHORS) candidate.check_qa(plan, receipt, reports, QA_AUTHORS)
fresh = owner_plan(task_id) fresh = owner_plan(task_id)
cd.require(fresh == plan, 'release plan changed during registration') cd.require(fresh == plan, 'release plan changed during registration')
@@ -178,7 +224,7 @@ def register(task_id):
'register QA before the owner moves the release task to 待发布') 'register QA before the owner moves the release task to 待发布')
sha, bundle = receipt['sha'], receipt['bundle'] sha, bundle = receipt['sha'], receipt['bundle']
links = '\n'.join(f'- {task(item)["url"]}#comment-{reports[item][0]["id"]}' for item in tasks) 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}' body = acceptance_body(sha, bundle, tasks, reports, lambda item: task(item)['url'], links)
comment = add_comment(task_id, 'acceptance ' + bundle, body) comment = add_comment(task_id, 'acceptance ' + bundle, body)
acceptance = {'verdict': 'passed', 'sha': sha, 'bundle': bundle, 'evidence': rel['url'] + '#comment-' + comment} acceptance = {'verdict': 'passed', 'sha': sha, 'bundle': bundle, 'evidence': rel['url'] + '#comment-' + comment}
if cd.metadata(task(task_id), 'cd_acceptance') != acceptance: if cd.metadata(task(task_id), 'cd_acceptance') != acceptance:
+89
View File
@@ -0,0 +1,89 @@
#!/usr/bin/env python3
"""Drain reviewed demand tasks through the shared candidate environment."""
import json
import release_handoff as h
cd = h.cd
coordinator = h.coordinator
def release_published_slot(compose):
directory = compose.parent
ready = cd.read_json(cd.immutable_file(directory / 'ready.json'))
task = h.assistant.task_record(ready['task'])
published = cd.metadata(task, 'cd_release') or {}
if task['status']['id'] != cd.PUBLISHED or not all(published.get(k) == ready[k] for k in ('sha', 'bundle')):
return False
project = 'kg-batch-' + ready['bundle'][:20]
cd.require(ready['mode'] == 'acceptance' and cd.hash_file(directory / 'bundle/release.json') == ready['bundle'],
'published QA archive changed')
cd.require(set(ready['containers']) == {'api', 'web', 'worker'}, 'unexpected candidate service set')
ids = []
for role, name in ready['containers'].items():
cd.require(name == project + '-' + role, 'candidate name mismatch')
info = json.loads(cd.run(['docker', 'inspect', name], 'inspect QA container'))[0]
labels = info['Config']['Labels']
cd.require(labels.get('com.docker.compose.project') == project and info['Image'] == ready['images'][role],
'candidate container identity changed')
ids.append(info['Id'])
cd.run(['docker', 'stop', *ids], 'retire published QA environment', timeout=90)
info = json.loads(cd.run(['docker', 'inspect', *ids], 'verify stopped QA containers'))
cd.require(len(info) == len(ids) and not any(row['State']['Running'] for row in info), 'QA slot still running')
compose.rename(directory / 'compose.released.json')
return True
def in_flight(state):
for path in state.glob('*.dispatch.json'):
claim = cd.read_json(cd.immutable_file(path))
key = path.name.split('.')[0]
if (state / key / 'ready.json').is_file():
continue
if claim['state'] != 'queued':
return True
run = h.candidate.read_forge(h.candidate.API + '/actions/runs/' + str(claim['run']))
if run['status'] != 'completed' or run.get('conclusion') == 'success':
return True
return False
def drain():
state = coordinator.STATE
waiting = state / 'waiting'
waiting.mkdir(mode=0o700, parents=True, exist_ok=True)
with cd.deploy_lock(waiting / 'queue.lock'):
entries = sorted(waiting.glob('*.json'), key=lambda p: (p.stat().st_mtime_ns, p.name))
entries = [(p, cd.read_json(cd.immutable_file(p))) for p in entries]
entries = [(p, e) for p, e in entries if e['state'] == 'waiting_for_slot']
if not entries:
return 'idle'
with cd.deploy_lock(state / 'runtime.lock'):
for compose in state.glob('*/compose.json'):
if not release_published_slot(compose):
return 'occupied'
if in_flight(state):
return 'building'
path, entry = entries[0]
task = h.assistant.task_record(entry['task'])
try:
sha, _ = h.resolve(task, entry['event'])
cd.require(sha == entry['sha'], 'review changed before building')
live = h.assistant.worker.main_site_sha()
if h.candidate.git('merge-base', live, sha, cwd=h.assistant.SOURCE, allowed=(0, 1)) == sha:
notice = f'主站当前版本 `{live}` 已包含候选提交 `{sha}`。请核对该需求的发布与验收记录。'
entry.update(state='included_in_live')
else:
result = h.prepare_from_review(task, entry['event'])
entry.update(state='dispatched', result=result)
notice = '候选构建已排队。' + result['url']
except cd.CDError as exc:
entry.update(state='blocked', reason=str(exc))
notice = '候选准备已停止。' + str(exc)
cd.record(path, entry)
coordinator.add_comment(task['id'], 'queue-result ' + entry['event'], notice)
return entry['state']
if __name__ == '__main__':
print(drain())
+8 -1
View File
@@ -42,7 +42,7 @@ def check_plan(plan):
items = plan['items'] items = plan['items']
cd.require(isinstance(items, list) and 0 < len(items) <= 100, 'require one to 100 requirements') cd.require(isinstance(items, list) and 0 < len(items) <= 100, 'require one to 100 requirements')
for item in items: for item in items:
cd.require(isinstance(item, dict) and cd.matches(cd.UUID, item.get('task')) and item['task'] != plan['task'], cd.require(isinstance(item, dict) and cd.matches(cd.UUID, item.get('task')) and (item['task'] != plan['task'] or len(items) == 1),
'invalid requirement identity') 'invalid requirement identity')
by_pr = set(item) == {'task', 'pr'} and type(item['pr']) is int and item['pr'] > 0 by_pr = set(item) == {'task', 'pr'} and type(item['pr']) is int and item['pr'] > 0
by_commit = set(item) == {'task', 'commit'} and cd.matches(cd.SHA, item['commit']) by_commit = set(item) == {'task', 'commit'} and cd.matches(cd.SHA, item['commit'])
@@ -91,6 +91,13 @@ def check_qa(plan, receipt, reports, authors):
cd.require(all(type(v) is int for v in values) and values[0] > 0 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', and values == [values[0], values[0], 0, 0] and report.get('verdict') == 'passed',
f'{task}: required QA cases have not passed') f'{task}: required QA cases have not passed')
if [i['task'] for i in plan['items']] == [plan['task']]:
cases = report.get('cases')
cd.require(isinstance(cases, dict) and all(isinstance(cases.get(k), list) and cases[k]
for k in ('business', 'regression')), 'single-task QA needs business and regression cases')
ids = cases['business'] + cases['regression']
cd.require(all(isinstance(v, str) and v.strip() for v in ids) and len(set(ids)) == len(ids) == values[0],
'single-task QA case IDs must match the required count')
def git(*args, cwd=None, allowed=(0,)): def git(*args, cwd=None, allowed=(0,)):
+36 -1
View File
@@ -15,6 +15,8 @@ from urllib.parse import quote
import production_cd as cd import production_cd as cd
import qa_env import qa_env
STATE = Path.home() / '.local/state/kg-candidate-release'
def isolated_subnet(exclude=()): def isolated_subnet(exclude=()):
nets = cd.run(['docker', 'network', 'ls', '-q'], 'list Docker networks').decode().split() nets = cd.run(['docker', 'network', 'ls', '-q'], 'list Docker networks').decode().split()
@@ -49,6 +51,29 @@ def qa_database(path):
return url, cert return url, cert
def qa_process_command(role):
if role not in ('api', 'worker'):
raise ValueError('unexpected QA process')
return ['/bin/sh', '-ec', 'export DATABASE_URL="$${DATABASE_URL}&pool_max_conns=2"; exec /app/' + role]
APP_UID = 65532
def qa_binding_key(image):
"""Give QA candidates one stable binding master key, readable by the application user."""
path = STATE / 'qa-binding-master.key'
if not path.exists():
cd.atomic_write(path, secrets.token_bytes(32), mode=0o600)
cd.run(['docker', 'run', '--rm', '--user', '0', '-v', f'{path.parent}:/run/kg-key', image,
'chown', f'{APP_UID}:{APP_UID}', f'/run/kg-key/{path.name}'],
'hand the QA binding master key to the application user', timeout=90)
info = path.lstat()
cd.require(info.st_mode & 0o777 == 0o600 and info.st_size == 32 and info.st_uid == APP_UID,
'QA binding master key must be a 32-byte file owned by the application user with mode 0600')
return path
def ready(directory, bundle, test_database=None): def ready(directory, bundle, test_database=None):
bundle = bundle.resolve() bundle = bundle.resolve()
manifest = cd.read_json(bundle / 'release.json') manifest = cd.read_json(bundle / 'release.json')
@@ -82,6 +107,9 @@ def ready(directory, bundle, test_database=None):
url, cert = qa_database(test_database) url, cert = qa_database(test_database)
env['DATA' + 'BASE_URL'] = url env['DATA' + 'BASE_URL'] = url
cd.atomic_write(directory / 'rds-ca.pem', cert.read_bytes(), mode=0o444) cd.atomic_write(directory / 'rds-ca.pem', cert.read_bytes(), mode=0o444)
env['WEKNORA_BINDING_MASTER_KEY_FILE'] = '/run/qa/binding-master.key'
# 验收候选要连 QA 的测试 WeKnora(同网段明文 http),与生产部署口径一致。
env['WEKNORA_ALLOW_PRIVATE_HTTP'] = 'true'
app_env = directory / 'app.env' app_env = directory / 'app.env'
cd.atomic_write(app_env, ''.join(f'{k}={v}\n' for k, v in env.items()).encode()) 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} names = {role: f'{project}-{role}' for role in cd.ROLES}
@@ -90,15 +118,22 @@ def ready(directory, bundle, test_database=None):
cd.verify_archive(archive, item['id']) cd.verify_archive(archive, item['id'])
cd.run(['docker', 'load', '-i', str(archive)], 'load sealed candidate image', timeout=150) cd.run(['docker', 'load', '-i', str(archive)], 'load sealed candidate image', timeout=150)
services[role] = {'image': item['id'], 'container_name': names[role]} services[role] = {'image': item['id'], 'container_name': names[role]}
key = qa_binding_key(manifest['images']['api']['id']) if test_database is not None else None
for role in ('api', 'worker'): for role in ('api', 'worker'):
services[role]['env_file'] = [str(app_env)] services[role]['env_file'] = [str(app_env)]
if test_database is not None: if test_database is not None:
services[role]['volumes'] = [f'{directory / "rds-ca.pem"}:/run/qa/rds-ca.pem:ro'] services[role]['volumes'] = [f'{directory / "rds-ca.pem"}:/run/qa/rds-ca.pem:ro',
f'{key}:/run/qa/binding-master.key:ro']
services['api']['healthcheck'] = {'test': ['CMD', 'curl', '-fsS', 'http://127.0.0.1:8080/health'], services['api']['healthcheck'] = {'test': ['CMD', 'curl', '-fsS', 'http://127.0.0.1:8080/health'],
'interval': '2s', 'timeout': '3s', 'retries': 45} 'interval': '2s', 'timeout': '3s', 'retries': 45}
if test_database is None: if test_database is None:
services['api']['depends_on'] = {'postgres': {'condition': 'service_healthy'}} services['api']['depends_on'] = {'postgres': {'condition': 'service_healthy'}}
services['worker'].update(command=['/app/worker'], depends_on={'api': {'condition': 'service_healthy'}}) services['worker'].update(command=['/app/worker'], depends_on={'api': {'condition': 'service_healthy'}})
if test_database is not None:
# Apply the pgx budget to the application process. The independent libpq
# migration probe reads the original, TLS-verified DSN from Docker exec.
for role in ('api', 'worker'):
services[role]['command'] = qa_process_command(role)
services['web'].update(ports=['127.0.0.1::8080'], 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() internal_subnet = isolated_subnet()
networks = {'default': {'internal': test_database is None, 'ipam': {'config': [{'subnet': internal_subnet}]}}} networks = {'default': {'internal': test_database is None, 'ipam': {'config': [{'subnet': internal_subnet}]}}}
+96
View File
@@ -0,0 +1,96 @@
#!/usr/bin/env python3
"""把一次发布运行的结果上报 ci-bridge,与 build 的通知同一出口。
发布失败也必须上报:群里要知道是「发布失败」而不是没有消息。
上报失败只打印,不改变发布的结论。
"""
from __future__ import annotations
import argparse
import json
import os
import subprocess
import sys
import urllib.error
import urllib.request
def env(name, default=''):
return (os.environ.get(name) or default).strip()
def git(*args):
try:
return subprocess.check_output(['git', *args], text=True, stderr=subprocess.DEVNULL).strip()
except (OSError, subprocess.CalledProcessError):
return ''
def result_status(value):
return {'success': 'success', 'failure': 'failure', 'cancelled': 'cancelled'}.get(value, 'failure')
def payload():
deploy_sha = env('DEPLOY_SHA') or env('GITHUB_SHA')
publish = result_status(env('PUBLISH_RESULT'))
guard = result_status(env('GUARD_RESULT'))
status = publish if publish != 'success' else guard
subject = git('log', '-1', '--format=%s', deploy_sha) if deploy_sha else ''
steps = []
for name, value in (('guard', env('GUARD_RESULT')), ('publish', env('PUBLISH_RESULT'))):
steps.append({'name': name, 'status': result_status(value), 'duration_s': ''})
return {
'repo': env('GITHUB_REPOSITORY', 'unknown/unknown'),
'sha': deploy_sha,
'branch': 'main',
'actor': env('GITHUB_ACTOR'),
'workflow': 'deploy-production',
'kind': 'deploy',
'site_url': env('DEPLOY_SITE_URL', 'http://100.85.111.121:8088/'),
'status': status,
'commit_subject': subject,
'commit_count': '1',
'duration_s': '',
'preview_url': '',
'steps': steps,
'manifest': ['guard', 'publish'],
'bundle': env('DEPLOY_BUNDLE'),
'task': env('DEPLOY_TASK'),
'run_id': env('GITHUB_RUN_ID'),
'run_number': env('GITHUB_RUN_NUMBER'),
'run_attempt': env('GITHUB_RUN_ATTEMPT', '1'),
'commit_url': f"{env('CI_PUBLIC_BASE_URL', env('GITHUB_SERVER_URL'))}/{env('GITHUB_REPOSITORY')}/commit/{deploy_sha}",
'run_url': f"{env('CI_PUBLIC_BASE_URL', env('GITHUB_SERVER_URL'))}/{env('GITHUB_REPOSITORY')}/actions/runs/{env('GITHUB_RUN_ID')}",
}
def post(data, base, token):
body = json.dumps(data, ensure_ascii=False).encode()
req = urllib.request.Request(base.rstrip('/') + '/api/ci/report', data=body, method='POST',
headers={'Content-Type': 'application/json', 'X-CI-Token': token})
with urllib.request.urlopen(req, timeout=30) as response:
return response.read().decode()[:300]
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--no-post', action='store_true')
args = parser.parse_args()
data = payload()
if args.no_post:
print(json.dumps(data, ensure_ascii=False, indent=2))
return 0
base = env('CI_BRIDGE_RESOLVED') or env('BRIDGE_URL') or env('CI_BRIDGE_URL')
if not base:
print('跳过上报:未找到 ci-bridge 地址', file=sys.stderr)
return 0
try:
print('✅ 已上报 ci-bridge:' + post(data, base, env('BRIDGE_TOKEN')))
except (urllib.error.URLError, OSError) as error:
# 通知失败不改变发布结论,只记一行。
print(f'❌ 上报 ci-bridge 失败(发布结论不变):{error}', file=sys.stderr)
return 0
if __name__ == '__main__':
sys.exit(main())
+163 -1
View File
@@ -37,12 +37,71 @@ COLLECTOR_VERSION = "backup-metadata/1"
MAX_MANIFEST_BYTES = 8 << 20 MAX_MANIFEST_BYTES = 8 << 20
MAX_ERRORS = 50 MAX_ERRORS = 50
STAMP_NAME = re.compile(r"^[A-Za-z0-9._-]+$") STAMP_NAME = re.compile(r"^[A-Za-z0-9._-]+$")
# 备份根与配额是**同一份部署契约**:backup_layout.sh 写、采集器读、备份脚本执行。
# 采集器不自己发明 50 GB,缺配置时用同一默认值,页面上报的配额因此就是脚本执行的值。
DEFAULT_BACKUP_ROOT = "/srv/kb-backups"
DEFAULT_QUOTA_BYTES = 53687091200 # 50 GiB
LAYOUT_CONFIG = "/etc/knowledge-governance/backup.env"
class CollectError(Exception): class CollectError(Exception):
pass pass
def read_layout(path: str) -> dict[str, str]:
"""读 backup.env 的 KEY=VALUE(只取本脚本认识的键)。
为什么不用 sh source:采集器是 Python,且这里只需要两个标量;整文件执行会把无关的
主机配置带进进程。文件不存在返回空(本地/未接线按默认值),显式给了路径却读不到则报错。
"""
try:
with open(path, "r", encoding="utf-8") as handle:
lines = handle.readlines()
except FileNotFoundError:
return {}
except OSError as error:
raise CollectError(f"备份配置不可读:{_error_text(error)}") from error
values: dict[str, str] = {}
for line in lines:
stripped = line.strip()
if not stripped or stripped.startswith("#") or "=" not in stripped:
continue
key, _, value = stripped.partition("=")
key = key.strip()
if key in ("KB_BACKUP_ROOT", "KB_BACKUP_QUOTA_BYTES"):
values[key] = value.strip().strip('"').strip("'")
return values
def resolve_backup_settings(
batch_root: str,
usage_root: str | None,
quota: int | None,
config_path: str,
) -> tuple[str, int | None, str]:
"""解析备份根与配额:显式参数 > backup.env > 默认值。
配额非法时返回 quota=None + 原因(不是猜一个值);配额/路径错误都不阻止批次盘点,
由 API 把「占用/配额未知」和「批次可用」分开呈现。
"""
batch_root = os.path.abspath(batch_root)
layout = read_layout(config_path)
raw_root = usage_root or layout.get("KB_BACKUP_ROOT") or DEFAULT_BACKUP_ROOT
if not os.path.isabs(raw_root) or os.path.normpath(raw_root) != raw_root:
raise CollectError(f"备份根不是规范绝对路径:{raw_root}")
backup_root = raw_root
if batch_root != backup_root and not batch_root.startswith(backup_root.rstrip("/") + "/"):
raise CollectError(f"批次根 {batch_root} 不在备份根 {backup_root} 下")
quota_text = str(quota) if quota is not None else layout.get("KB_BACKUP_QUOTA_BYTES", str(DEFAULT_QUOTA_BYTES))
try:
quota_value = int(quota_text)
except (TypeError, ValueError):
return backup_root, None, f"备份配额不是整数:{quota_text!r}"
if quota_value <= 0:
return backup_root, None, f"备份配额必须为正整数:{quota_value}"
return backup_root, quota_value, ""
def _error_text(error: BaseException) -> str: def _error_text(error: BaseException) -> str:
if isinstance(error, OSError) and error.filename: if isinstance(error, OSError) and error.filename:
return f"{type(error).__name__}: {error.strerror or error} ({error.filename})" return f"{type(error).__name__}: {error.strerror or error} ({error.filename})"
@@ -212,6 +271,28 @@ def measure_tree(path: str, scan: Callable[[str], Iterable[Any]] = os.scandir, m
} }
def project_usage(root: str, tree: dict[str, Any]) -> dict[str, Any]:
"""把根树测量投影成「可展示的占用」:不完整时一律不给字节。
与批次同样的纪律(0.1.408/0.1.410):部分计数永远不能当占盘;
但这里的 error 只属于 usage,不会被塞进 snapshot.errors 去污染批次完整性。
"""
complete = bool(tree["complete"])
errors = list(tree["errors"])[:MAX_ERRORS]
if not complete and not errors:
errors = ["备份根遍历不完整"]
return {
"root": root,
"complete": complete,
"actual_bytes": tree["actual_bytes"] if complete else None,
"apparent_bytes": tree["apparent_bytes"] if complete else None,
"file_count": tree["file_count"] if complete else None,
"dir_count": tree["dir_count"] if complete else None,
"errors": errors,
"error": "" if complete else "备份根占用未知:" + ";".join(errors[:3]),
}
def collect( def collect(
root: str, root: str,
source: str = "", source: str = "",
@@ -219,8 +300,12 @@ def collect(
max_batches: int = 100, max_batches: int = 100,
scan: Callable[[str], Iterable[Any]] = os.scandir, scan: Callable[[str], Iterable[Any]] = os.scandir,
now: dt.datetime | None = None, now: dt.datetime | None = None,
backup_root: str = "",
quota_bytes: int | None = None,
quota_error: str = "",
) -> dict[str, Any]: ) -> dict[str, Any]:
root = os.path.abspath(root) root = os.path.abspath(root)
backup_root = os.path.abspath(backup_root or root)
collected_at = (now or dt.datetime.now(dt.timezone.utc)).astimezone(dt.timezone.utc) collected_at = (now or dt.datetime.now(dt.timezone.utc)).astimezone(dt.timezone.utc)
snapshot: dict[str, Any] = { snapshot: dict[str, Any] = {
"schema_version": SCHEMA_VERSION, "schema_version": SCHEMA_VERSION,
@@ -230,6 +315,10 @@ def collect(
"host": host or socket.gethostname(), "host": host or socket.gethostname(),
"source": source, "source": source,
"root": root, "root": root,
"backup_root": backup_root,
"usage": {},
"quota_bytes": quota_bytes,
"quota_error": quota_error,
"complete": True, "complete": True,
"errors": [], "errors": [],
"filesystem": {}, "filesystem": {},
@@ -239,6 +328,9 @@ def collect(
"batches": [], "batches": [],
} }
errors: list[str] = snapshot["errors"] errors: list[str] = snapshot["errors"]
# 根占用与批次完整性**分开**:某个保护目录读不到时,占用可以说「未知」,
# 但批次表/磁盘容量仍然有效;把两者绑在一起会把「占用未知」扩大成「全部未知」。
snapshot["usage"] = project_usage(backup_root, measure_tree(backup_root, scan))
try: try:
if not os.path.isdir(root): if not os.path.isdir(root):
raise CollectError(f"备份根不是目录:{root}") raise CollectError(f"备份根不是目录:{root}")
@@ -529,6 +621,61 @@ def _self_test() -> None:
assert ignored["incomplete_count"] == 1 assert ignored["incomplete_count"] == 1
assert [item["stamp"] for item in ignored["batches"]] == [stamp] assert [item["stamp"] for item in ignored["batches"]] == [stamp]
# 根占用:测整棵备份根(不只是 rds-logical),与 du -sB1 对拍。
kb_root = os.path.join(base, "kb-backups")
kb_batch_root = os.path.join(kb_root, "rds-logical")
kb_batch = os.path.join(kb_batch_root, "20261119T193001Z")
os.makedirs(os.path.join(kb_batch, "weknora_kb.dir"))
with open(os.path.join(kb_batch, "weknora_kb.dir", "toc.dat"), "wb") as handle:
handle.write(b"k" * 1000)
with open(os.path.join(kb_batch, "MANIFEST.json"), "w", encoding="utf-8") as handle:
json.dump({"databases": ["weknora_kb"]}, handle)
es_dir = os.path.join(kb_root, "es-snapshots")
os.makedirs(es_dir)
with open(os.path.join(es_dir, "index-0"), "wb") as handle:
handle.write(b"e" * 2000)
rooted = collect(kb_batch_root, backup_root=kb_root, quota_bytes=DEFAULT_QUOTA_BYTES, now=fixed)
assert rooted["complete"] is True, rooted
assert rooted["usage"]["complete"] is True, rooted["usage"]
assert rooted["usage"]["root"] == kb_root
assert rooted["quota_bytes"] == DEFAULT_QUOTA_BYTES
assert rooted["usage"]["actual_bytes"] >= 3000
if shutil.which("du"):
assert rooted["usage"]["actual_bytes"] == du_bytes(kb_root), rooted["usage"]
assert rooted["usage"]["actual_bytes"] > rooted["batches"][0]["actual_bytes"]
# 根占用遍历失败:只让占用未知,批次与整体 complete 不受影响。
def denied_root_scan(target: str):
if target == kb_root:
raise PermissionError(errno.EACCES, "Permission denied", target)
return os.scandir(target)
partial = collect(kb_batch_root, backup_root=kb_root, scan=denied_root_scan, now=fixed)
assert partial["usage"]["complete"] is False
assert partial["usage"]["actual_bytes"] is None
assert "Permission denied" in partial["usage"]["error"]
assert partial["complete"] is True, partial
assert len(partial["batches"]) == 1
# 配置解析:备份根/配额来自 backup.env;非法配额给原因而不是默认放行。
config_path = os.path.join(base, "backup.env")
with open(config_path, "w", encoding="utf-8") as handle:
handle.write(f"KB_BACKUP_ROOT={kb_root}\nKB_BACKUP_QUOTA_BYTES=12345\n")
resolved_root, resolved_quota, resolved_error = resolve_backup_settings(
kb_batch_root, None, None, config_path
)
assert resolved_root == kb_root and resolved_quota == 12345 and resolved_error == ""
with open(config_path, "w", encoding="utf-8") as handle:
handle.write(f"KB_BACKUP_ROOT={kb_root}\nKB_BACKUP_QUOTA_BYTES=50GB\n")
_, bad_quota, bad_error = resolve_backup_settings(kb_batch_root, None, None, config_path)
assert bad_quota is None and "不是整数" in bad_error
try:
resolve_backup_settings(kb_batch_root, os.path.join(base, "outside"), None, config_path)
except CollectError:
pass
else:
raise AssertionError("批次根不在备份根下必须拒绝")
output = os.path.join(base, "out", "metadata.json") output = os.path.join(base, "out", "metadata.json")
write_snapshot(output, ignored) write_snapshot(output, ignored)
with open(output, encoding="utf-8") as handle: with open(output, encoding="utf-8") as handle:
@@ -548,6 +695,9 @@ def main(argv: list[str] | None = None) -> int:
parser.add_argument("--source", default="", help="展示来源,如 weknora-test:/srv/...") parser.add_argument("--source", default="", help="展示来源,如 weknora-test:/srv/...")
parser.add_argument("--host", default="", help="采集主机名(默认当前主机)") parser.add_argument("--host", default="", help="采集主机名(默认当前主机)")
parser.add_argument("--max-batches", type=int, default=100) parser.add_argument("--max-batches", type=int, default=100)
parser.add_argument("--usage-root", default="", help="备份根(默认读 backup.env 的 KB_BACKUP_ROOT)")
parser.add_argument("--quota-bytes", type=int, default=None, help="备份配额(默认读 backup.env)")
parser.add_argument("--config", default=LAYOUT_CONFIG, help="部署配置 backup.env")
parser.add_argument("--self-test", action="store_true") parser.add_argument("--self-test", action="store_true")
args = parser.parse_args(argv) args = parser.parse_args(argv)
if args.self_test: if args.self_test:
@@ -556,11 +706,17 @@ def main(argv: list[str] | None = None) -> int:
if not args.root or not args.output: if not args.root or not args.output:
parser.error("--root and --output are required unless --self-test") parser.error("--root and --output are required unless --self-test")
try: try:
backup_root, quota_bytes, quota_error = resolve_backup_settings(
args.root, args.usage_root or None, args.quota_bytes, args.config
)
snapshot = collect( snapshot = collect(
args.root, args.root,
source=args.source, source=args.source,
host=args.host or None, host=args.host or None,
max_batches=max(1, args.max_batches), max_batches=max(1, args.max_batches),
backup_root=backup_root,
quota_bytes=quota_bytes,
quota_error=quota_error,
) )
write_snapshot(args.output, snapshot) write_snapshot(args.output, snapshot)
except (CollectError, OSError) as error: except (CollectError, OSError) as error:
@@ -570,11 +726,17 @@ def main(argv: list[str] | None = None) -> int:
"complete": snapshot["complete"], "complete": snapshot["complete"],
"batches": len(snapshot["batches"]), "batches": len(snapshot["batches"]),
"incomplete_count": snapshot["incomplete_count"], "incomplete_count": snapshot["incomplete_count"],
"backup_root": snapshot["backup_root"],
"usage_bytes": snapshot["usage"].get("actual_bytes"),
"usage_complete": snapshot["usage"].get("complete"),
"quota_bytes": snapshot["quota_bytes"],
"quota_error": snapshot["quota_error"],
"collected_at": snapshot["collected_at"], "collected_at": snapshot["collected_at"],
"output": args.output, "output": args.output,
} }
print(json.dumps(summary, ensure_ascii=False)) print(json.dumps(summary, ensure_ascii=False))
return 0 if snapshot["complete"] else 2 healthy = bool(snapshot["complete"] and snapshot["usage"].get("complete") and not snapshot["quota_error"])
return 0 if healthy else 2
if __name__ == "__main__": if __name__ == "__main__":
+4 -1
View File
@@ -54,7 +54,10 @@ show_state() {
if command -v systemctl >/dev/null 2>&1; then if command -v systemctl >/dev/null 2>&1; then
echo "cron 服务: $(systemctl is-active cron 2>/dev/null || systemctl is-active crond 2>/dev/null || echo unknown)" echo "cron 服务: $(systemctl is-active cron 2>/dev/null || systemctl is-active crond 2>/dev/null || echo unknown)"
fi fi
echo "备份根目录: $KB_BACKUP_ROOT($(du -sh "$KB_BACKUP_ROOT/rds-logical" 2>/dev/null | cut -f1 || echo 0) 已用)" QUOTA_BYTES="${KB_BACKUP_QUOTA_BYTES:-53687091200}"
if ROOT_BYTES="$(du -sB1 -- "$KB_BACKUP_ROOT" 2>/dev/null | cut -f1)"; then :; else ROOT_BYTES="未知"; fi
LOGICAL_USAGE="$(du -sh "$KB_BACKUP_ROOT/rds-logical" 2>/dev/null | cut -f1 || echo 未知)"
echo "备份根占用: $KB_BACKUP_ROOT(${ROOT_BYTES:-未知} 字节 / 配额 $QUOTA_BYTES 字节;rds-logical $LOGICAL_USAGE)"
} }
if [ "$MODE" = "show" ]; then if [ "$MODE" = "show" ]; then
+57 -3
View File
@@ -21,6 +21,7 @@
# JOBS 并行度(默认 4) # JOBS 并行度(默认 4)
# KEEP_DAILY 保留最近几份每日备份(默认 7) # KEEP_DAILY 保留最近几份每日备份(默认 7)
# KEEP_MONTHS 额外保留最近几个自然月各一份(默认 3) # KEEP_MONTHS 额外保留最近几个自然月各一份(默认 3)
# KB_BACKUP_QUOTA_BYTES 备份根累计占用硬上限(默认 53687091200 = 50 GiB,来自 backup.env)
# EXCLUDE_DBS 逗号分隔的跳过列表(默认 rdsadmin:RDS 管理库,普通账号导不出来) # EXCLUDE_DBS 逗号分隔的跳过列表(默认 rdsadmin:RDS 管理库,普通账号导不出来)
set -euo pipefail set -euo pipefail
@@ -31,7 +32,28 @@ if [ -z "${KB_BACKUP_ROOT:-}" ] && [ -f /etc/knowledge-governance/backup.env ];
. /etc/knowledge-governance/backup.env . /etc/knowledge-governance/backup.env
fi fi
KB_BACKUP_ROOT="${KB_BACKUP_ROOT:-/srv/kb-backups}" KB_BACKUP_ROOT="${KB_BACKUP_ROOT:-/srv/kb-backups}"
# 配额与备份根同属 backup.env;KB_BACKUP_ROOT 显式传入时仍要读到配额,所以单独取值。
layout_value() {
local key="$1"
[ -f "${KB_BACKUP_LAYOUT_ENV:-/etc/knowledge-governance/backup.env}" ] || return 0
sed -n "s/^[[:space:]]*${key}=//p" "${KB_BACKUP_LAYOUT_ENV:-/etc/knowledge-governance/backup.env}" \
| tail -1 | tr -d "\"' \r"
}
BACKUP_ROOT="${BACKUP_ROOT:-$KB_BACKUP_ROOT/rds-logical}" BACKUP_ROOT="${BACKUP_ROOT:-$KB_BACKUP_ROOT/rds-logical}"
# 配额约束的是备份根(含 es-snapshots/target-kb-snapshots/logs),不是批次根。
# 若显式把 BACKUP_ROOT 指到别处,就以它的父目录为准,避免量错盘。
case "$BACKUP_ROOT" in
"$KB_BACKUP_ROOT"/*) QUOTA_ROOT="$KB_BACKUP_ROOT" ;;
*) QUOTA_ROOT="$(dirname "$BACKUP_ROOT")" ;;
esac
QUOTA_BYTES="${KB_BACKUP_QUOTA_BYTES:-$(layout_value KB_BACKUP_QUOTA_BYTES)}"
QUOTA_BYTES="${QUOTA_BYTES:-53687091200}"
case "$QUOTA_BYTES" in
''|*[!0-9]*) echo "KB_BACKUP_QUOTA_BYTES 必须是正整数,收到 '$QUOTA_BYTES'" >&2; exit 1 ;;
esac
[ "$QUOTA_BYTES" -gt 0 ] || { echo "KB_BACKUP_QUOTA_BYTES 必须大于 0" >&2; exit 1; }
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PRUNE_TOOL="$SCRIPT_DIR/prune_backup_batches.py"
APP_CONTAINER="${APP_CONTAINER:-weknora-test-v071-app-1}" APP_CONTAINER="${APP_CONTAINER:-weknora-test-v071-app-1}"
PG_IMAGE="${PG_IMAGE:-postgres:17.9-alpine}" PG_IMAGE="${PG_IMAGE:-postgres:17.9-alpine}"
JOBS="${JOBS:-4}" JOBS="${JOBS:-4}"
@@ -49,6 +71,26 @@ DRY_RUN="${DRY_RUN:-0}"
DBS="${DBS:-}" DBS="${DBS:-}"
EXCLUDE_DBS="${EXCLUDE_DBS:-rdsadmin}" EXCLUDE_DBS="${EXCLUDE_DBS:-rdsadmin}"
STAMP="$(date -u +%Y%m%dT%H%M%SZ)" STAMP="$(date -u +%Y%m%dT%H%M%SZ)"
TARGET="$BACKUP_ROOT/$STAMP"
[ -f "$PRUNE_TOOL" ] || { echo "缺少配额清理工具:$PRUNE_TOOL(未开始备份)" >&2; exit 1; }
# 配额预检在 dump 之前、且不依赖 DB 凭据:失败时旧备份原样保留,也不会留下半成品目录。
# 预留量取最近一份完整批次大小;prune 内部保证「保留最新一份」和「不够就一个都不删」。
run_quota_prune() {
local label="$1"; shift
echo "-- 配额检查:$label --"
python3 "$PRUNE_TOOL" \
--backup-root "$QUOTA_ROOT" \
--batch-root "$BACKUP_ROOT" \
--quota-bytes "$QUOTA_BYTES" "$@"
}
if [ "$DRY_RUN" = "1" ]; then
run_quota_prune "预检(DRY_RUN,只打印计划)" --estimate latest --keep-latest || true
echo "DRY_RUN=1,不执行"
exit 0
fi
env_value() { env_value() {
docker inspect "$APP_CONTAINER" --format '{{range .Config.Env}}{{println .}}{{end}}' \ docker inspect "$APP_CONTAINER" --format '{{range .Config.Env}}{{println .}}{{end}}' \
@@ -81,8 +123,6 @@ print(','.join(d for d in sys.argv[1].split(',') if d and d not in exclude))
fi fi
if [ -z "$DBS" ]; then echo "没有可备份的库" >&2; exit 1; fi if [ -z "$DBS" ]; then echo "没有可备份的库" >&2; exit 1; fi
TARGET="$BACKUP_ROOT/$STAMP"
# 失败或被中断(含被 head/管道 SIGPIPE 杀掉):把目录显式标记为半成品, # 失败或被中断(含被 head/管道 SIGPIPE 杀掉):把目录显式标记为半成品,
# 这样"最近一次备份"的选择器与人都不会把它误当成功结果。 # 这样"最近一次备份"的选择器与人都不会把它误当成功结果。
mark_incomplete() { mark_incomplete() {
@@ -97,7 +137,14 @@ echo "备份目标: $TARGET"
echo "库列表 : $DBS" echo "库列表 : $DBS"
echo "镜像 : $PG_IMAGE (并行 $JOBS)" echo "镜像 : $PG_IMAGE (并行 $JOBS)"
echo "保留策略: 每日 $KEEP_DAILY 份 / 每月 $KEEP_MONTHS 份" echo "保留策略: 每日 $KEEP_DAILY 份 / 每月 $KEEP_MONTHS 份"
if [ "$DRY_RUN" = "1" ]; then echo "DRY_RUN=1,不执行"; exit 0; fi echo "配额 : $QUOTA_BYTES 字节(备份根 $QUOTA_ROOT)"
# 真正删除旧批次放在凭据/库列表校验之后:连不上库时不应该先清历史备份。
if run_quota_prune "预检" --estimate latest --keep-latest --apply; then :; else
rc=$?
echo "配额预检未通过(rc=$rc):本次备份取消,旧备份未被删除" >&2
exit "$rc"
fi
mkdir -p "$TARGET" mkdir -p "$TARGET"
STARTED_AT="$(date -u +%Y-%m-%dT%H:%M:%SZ)" STARTED_AT="$(date -u +%Y-%m-%dT%H:%M:%SZ)"
@@ -215,6 +262,13 @@ for path in stamps:
print("kept:", len([p for p in stamps if p.name in keep])) print("kept:", len([p for p in stamps if p.name in keep]))
PY PY
# dump 后按实际占用复查:保护本次新批次,旧批次可删;仍超限则保留数据并告警。
if run_quota_prune "dump 后复查" --estimate none --protect "$STAMP" --apply; then :; else
rc=$?
echo "本次备份已完成,但配额仍超出(rc=$rc):新批次保留,请扩容或人工清理" >&2
exit "$rc"
fi
if [ -n "$FAILED_DBS" ]; then if [ -n "$FAILED_DBS" ]; then
echo "done(有失败的库): $TARGET | failed: $FAILED_DBS" >&2 echo "done(有失败的库): $TARGET | failed: $FAILED_DBS" >&2
exit 1 exit 1
+356
View File
@@ -0,0 +1,356 @@
#!/usr/bin/env python3
"""按字节配额清理整库逻辑备份批次(宿主脚本,**只动平台自己的批次日录**)。
为什么单独成脚本:配额清理是唯一会删历史备份的动作,必须能离线、确定性地证明
「最旧优先、预检保留最新、空间仍不够时零删除、非批次日录不动」。塞进
logical-backup.sh 的内联 Python 只能靠跑 docker/psql 才能验证。
口径:占用用 `du -sB1 <备份根>`,与采集器声明的一致(0.1.408/0.1.409 的对拍口径)。
`du` 退出非 0(权限/IO 错误)⇒ 不清理、非 0 退出:绝不拿部分统计去删备份。
用法:
# 预检(dump 前):预留最近一份完整批次的大小,保留最新一份,不动就退出 3
python3 prune_backup_batches.py --backup-root /srv/kb-backups \
--quota-bytes 53687091200 --estimate latest --keep-latest --apply
# dump 后复查:保护本次新批次,其余旧批次可删
python3 prune_backup_batches.py --backup-root /srv/kb-backups \
--quota-bytes 53687091200 --estimate none --protect 20261125T033000Z --apply
退出码:0 已满足配额(可能删了旧批次);2 du/路径错误,未删除;3 空间仍不够,未删除;
4 删除失败(已删的已生效,报错退出)。
"""
from __future__ import annotations
import argparse
import os
import re
import shutil
import subprocess
import sys
import tempfile
from dataclasses import dataclass
from typing import Iterable
STAMP_NAME = re.compile(r"^\d{8}T\d{6}Z$")
class QuotaError(Exception):
pass
@dataclass(frozen=True)
class Candidate:
name: str
path: str
size: int
def measure(path: str) -> int:
"""`du -sB1` 的实际分配字节;失败即抛错(部分和不能用)。"""
try:
result = subprocess.run(
["du", "-sB1", "--", path], capture_output=True, text=True, check=False
)
except OSError as error:
raise QuotaError(f"du 无法执行:{error}") from error
if result.returncode != 0:
raise QuotaError(f"du 失败({path}):{(result.stderr or result.stdout).strip()[:300]}")
first = result.stdout.strip().splitlines()
if not first:
raise QuotaError(f"du 没有输出({path})")
try:
return int(first[0].split()[0])
except (IndexError, ValueError) as error:
raise QuotaError(f"du 输出无法解析({path}):{first[0]!r}") from error
def _is_regular_file(path: str) -> bool:
try:
info = os.lstat(path)
except OSError:
return False
return not os.path.islink(path) and os.path.isfile(path)
def candidates(batch_root: str, measure_bytes=measure) -> list[Candidate]:
"""只认批次根的直接子目录:名字像 UTC 戳、不是符号链接、含常规 MANIFEST.json。
`*.incomplete` 名字不匹配,自然排除;符号链接不跟随(否则会删到别处)。
"""
try:
entries = list(os.scandir(batch_root))
except OSError as error:
raise QuotaError(f"批次根不可读({batch_root}):{error}") from error
found: list[Candidate] = []
for entry in entries:
if not STAMP_NAME.match(entry.name):
continue
if entry.is_symlink() or not entry.is_dir(follow_symlinks=False):
continue
if not _is_regular_file(os.path.join(entry.path, "MANIFEST.json")):
continue
found.append(Candidate(entry.name, entry.path, measure_bytes(entry.path)))
found.sort(key=lambda item: item.name)
return found
def plan_deletions(
usage: int,
candidates_oldest_first: Iterable[Candidate],
quota: int,
estimate: int,
protect: set[str],
) -> tuple[list[Candidate], int, bool]:
"""返回(应删列表、删除后预计占用、是否仍超限)。
超出配额时从最旧开始删,直到「预计占用 + 预留」装得下;`protect` 里的批次永不删。
仍超限时调用方必须**一个都不删**(见 apply)。
"""
projected = usage
planned: list[Candidate] = []
for candidate in candidates_oldest_first:
if projected + estimate <= quota:
break
if candidate.name in protect:
continue
planned.append(candidate)
projected -= candidate.size
insufficient = projected + estimate > quota
return planned, projected, insufficient
def resolve_estimate(value: str, candidates_oldest_first: list[Candidate]) -> int:
if value in ("", "none"):
return 0
if value == "latest":
if not candidates_oldest_first:
return 0
return candidates_oldest_first[-1].size
try:
number = int(value)
except ValueError as error:
raise QuotaError(f"--estimate 只接受 latest/none/字节数,收到 {value!r}") from error
if number < 0:
raise QuotaError("--estimate 不能为负数")
return number
def prune(
backup_root: str,
batch_root: str,
quota: int,
estimate: int,
protect: set[str],
keep_latest: bool,
apply: bool,
measure_bytes=measure,
) -> dict:
if quota <= 0:
raise QuotaError("--quota-bytes 必须是正整数")
backup_root = os.path.abspath(backup_root)
batch_root = os.path.abspath(batch_root)
if batch_root != backup_root and not batch_root.startswith(backup_root.rstrip("/") + "/"):
raise QuotaError(f"批次根 {batch_root} 不在备份根 {backup_root} 下")
found = candidates(batch_root, measure_bytes)
usage = measure_bytes(backup_root)
protected = set(protect)
if keep_latest and found:
protected.add(found[-1].name)
planned, projected, insufficient = plan_deletions(usage, found, quota, estimate, protected)
result = {
"backup_root": backup_root,
"batch_root": batch_root,
"quota_bytes": quota,
"usage_bytes": usage,
"estimate_bytes": estimate,
"projected_bytes": projected,
"protected": sorted(protected),
"plan": [item.name for item in planned],
"insufficient": insufficient,
"applied": False,
}
if insufficient:
return result
if not apply:
return result
for item in planned:
target = os.path.abspath(item.path)
if os.path.dirname(target) != batch_root:
raise QuotaError(f"拒绝删除批次根之外的路径:{target}")
if os.path.islink(target) or not os.path.isdir(target):
raise QuotaError(f"拒绝删除非目录或符号链接:{target}")
try:
shutil.rmtree(target)
except OSError as error:
raise QuotaError(f"删除失败({target}):{error}") from error
result["applied"] = True
result["usage_after_bytes"] = measure_bytes(backup_root)
return result
def _self_test() -> None:
base = tempfile.mkdtemp(prefix="backup-quota-test-")
try:
root = os.path.join(base, "kb-backups")
batch_root = os.path.join(root, "rds-logical")
os.makedirs(batch_root)
es_dir = os.path.join(root, "es-snapshots")
os.makedirs(es_dir)
with open(os.path.join(es_dir, "index-0"), "wb") as handle:
handle.write(b"e" * 8192)
def make_batch(stamp: str, kib: int) -> str:
path = os.path.join(batch_root, stamp)
db = os.path.join(path, "weknora.dir")
os.makedirs(db)
with open(os.path.join(db, "toc.dat"), "wb") as handle:
handle.write(b"x" * (kib * 1024))
with open(os.path.join(path, "MANIFEST.json"), "w", encoding="utf-8") as handle:
handle.write('{"databases":["weknora"]}')
return path
stamps = ["20261101T030000Z", "20261102T030000Z", "20261103T030000Z", "20261104T030000Z"]
paths = [make_batch(stamp, 256) for stamp in stamps]
# 非批次日录、半成品、指向别处的符号链接都不能进候选/被删。
os.makedirs(os.path.join(root, "logs"))
with open(os.path.join(root, "logs", "logical-backup.log"), "wb") as handle:
handle.write(b"l" * 4096)
os.makedirs(os.path.join(batch_root, "notes"))
with open(os.path.join(batch_root, "notes", "keep.txt"), "wb") as handle:
handle.write(b"n" * 1024)
os.makedirs(os.path.join(batch_root, "20261105T030000Z.incomplete"))
outside = os.path.join(base, "outside")
os.makedirs(outside)
with open(os.path.join(outside, "MANIFEST.json"), "w", encoding="utf-8") as handle:
handle.write("{}")
os.symlink(outside, os.path.join(batch_root, "20261106T030000Z"))
found = candidates(batch_root)
assert [item.name for item in found] == stamps, found
usage = measure(root)
assert usage > sum(item.size for item in found)
newest_size = found[-1].size
# 1) 预检:需要腾出空间时从最旧删,最新一份永不在计划里。
estimate = newest_size
quota = usage - found[0].size + estimate
planned, projected, insufficient = plan_deletions(
usage, found, quota, estimate, {found[-1].name}
)
assert not insufficient
assert [item.name for item in planned] == [found[0].name], planned
assert all(item.name != found[-1].name for item in planned)
assert projected + estimate <= quota
# 2) 空间仍不够:一个都不删,目录全部还在。
too_tight = max(1, estimate)
result = prune(
root, batch_root, too_tight, estimate, set(), keep_latest=True, apply=True
)
assert result["insufficient"] is True and result["applied"] is False, result
assert all(os.path.isdir(path) for path in paths)
assert os.path.isdir(os.path.join(batch_root, "notes"))
assert os.path.isdir(os.path.join(root, "logs"))
assert os.path.isdir(os.path.join(root, "es-snapshots"))
# 3) dump 后:保护新批次,允许删上一份最新;只删计划内、非批次日录不动。
new_stamp = "20261109T030000Z"
new_path = make_batch(new_stamp, 256)
after_usage = measure(root)
protect = {new_stamp}
result = prune(
root,
batch_root,
after_usage - found[0].size,
0,
protect,
keep_latest=False,
apply=True,
)
assert result["applied"] is True and result["plan"] == [found[0].name], result
assert not os.path.exists(found[0].path)
assert os.path.isdir(new_path)
assert os.path.isdir(found[-1].path)
assert os.path.isdir(os.path.join(batch_root, "notes"))
assert os.path.isdir(os.path.join(batch_root, "20261105T030000Z.incomplete"))
assert os.path.isdir(os.path.join(root, "es-snapshots"))
# 4) 测量失败必须零删除:注入抛错的 measure。
def broken(_path: str) -> int:
raise QuotaError("du 失败(注入)")
try:
prune(root, batch_root, 1, 0, set(), keep_latest=True, apply=True, measure_bytes=broken)
except QuotaError:
pass
else:
raise AssertionError("测量失败必须中止")
assert os.path.isdir(found[-1].path)
# 5) 批次根逃逸必须拒绝。
try:
prune(root, os.path.join(base, "outside"), 1 << 40, 0, set(), True, True)
except QuotaError:
pass
else:
raise AssertionError("批次根不在备份根下必须拒绝")
print("prune_backup_batches self-test ok")
finally:
shutil.rmtree(base, ignore_errors=True)
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description="按字节配额清理整库备份批次")
parser.add_argument("--backup-root", default="", help="备份根(默认 backup.env 的 KB_BACKUP_ROOT)")
parser.add_argument("--batch-root", default="", help="批次日录根(默认 <备份根>/rds-logical)")
parser.add_argument("--quota-bytes", type=int, default=0)
parser.add_argument("--estimate", default="none", help="新批次预留:latest / none / 字节数")
parser.add_argument("--protect", action="append", default=[], help="永不删除的批次戳(可重复)")
parser.add_argument("--keep-latest", action="store_true", help="预检模式:保留最新一份完整批次")
parser.add_argument("--apply", action="store_true", help="真的删除;缺省只打印计划")
parser.add_argument("--json", action="store_true")
parser.add_argument("--self-test", action="store_true")
args = parser.parse_args(argv)
if args.self_test:
_self_test()
return 0
try:
backup_root = args.backup_root or os.environ.get("KB_BACKUP_ROOT", "") or "/srv/kb-backups"
batch_root = args.batch_root or os.path.join(backup_root, "rds-logical")
found = candidates(batch_root)
estimate = resolve_estimate(args.estimate, found)
result = prune(
backup_root,
batch_root,
args.quota_bytes,
estimate,
set(args.protect),
args.keep_latest,
args.apply,
)
except QuotaError as error:
print(f"quota prune failed: {error}", file=sys.stderr)
return 2
if args.json:
import json
print(json.dumps(result, ensure_ascii=False))
else:
print(
f"备份占用 {result['usage_bytes']} / 配额 {result['quota_bytes']}"
f"(预留 {result['estimate_bytes']},保护 {result['protected'] or '无'})"
)
print("删除计划:" + ("、".join(result["plan"]) if result["plan"] else "无"))
if result["insufficient"]:
print("空间仍不够:未删除任何批次", file=sys.stderr)
elif result["applied"]:
print(f"已删除 {len(result['plan'])} 个批次,占用 {result['usage_after_bytes']}")
if result["insufficient"]:
return 3
return 0
if __name__ == "__main__":
raise SystemExit(main())
+138
View File
@@ -0,0 +1,138 @@
#!/usr/bin/env python3
"""Prepare candidate QA reports from a case list and per-case evidence."""
import argparse
import hashlib
import json
from pathlib import Path
import re
import shutil
import subprocess
import sys
POLICY = 'KG-QA-REPORT/v1'
STATES = ('passed', 'failed', 'blocked')
def require(condition, message):
if not condition:
raise ValueError(message)
def summarize(plan, results, host):
require(isinstance(plan, dict), '缺少原用例清单')
ids = []
for group in ('business', 'regression'):
group_ids = plan.get(group)
require(isinstance(group_ids, list) and group_ids, f'缺少 {group} 用例编号')
for case_id in group_ids:
require(isinstance(case_id, str) and case_id.strip() == case_id and case_id, '存在空用例编号')
require(case_id not in ids, f'重复编号 {case_id}')
ids.append(case_id)
require(isinstance(results, dict), '缺少逐项结果')
extras = set(results) - set(ids)
require(not extras, '清单外编号 ' + ', '.join(sorted(extras)))
counts = dict.fromkeys(STATES, 0)
missing = []
for case_id in ids:
entry = results.get(case_id)
if not valid_entry(entry):
missing.append(case_id)
else:
counts[entry['status']] += 1
require(not missing, '请填写结果和证据:' + ', '.join(missing))
require(valid_entry(host), '请填写正式候选环境的实测结果和证据,无法登录请填 blocked')
states = {host['status']} | {k for k, count in counts.items() if count}
verdict = 'failed' if 'failed' in states else 'blocked' if 'blocked' in states else 'passed'
return dict(cases=plan, results=results, candidate_check=host, required=len(ids), verdict=verdict, **counts)
def valid_entry(entry):
return (isinstance(entry, dict) and entry.get('status') in STATES
and isinstance(entry.get('evidence'), str) and bool(entry['evidence'].strip()))
def verify_report(report):
expected = summarize(report.get('cases'), report.get('results'), report.get('candidate_check'))
for key, value in expected.items():
require(type(report.get(key)) is type(value) and report[key] == value, f'报告字段 {key} 与逐项结果不一致')
def cli(*args, body=None):
program = shutil.which('hifox') or str(Path.home() / '.local/bin/hifox')
output = subprocess.check_output([program, *args, '--output', 'json'], input=body, text=True, timeout=45)
return json.loads(output)
def ready(rows):
candidates = sorted((r for r in rows if r['content'].startswith('[KG candidate ready ')
and (r.get('author') or {}).get('id') == '39ae59fb-876c-4587-ab5d-a12a841c6c09'),
key=lambda r: r['createdAt'])
require(candidates, '原单缺少候选就绪回执')
row = candidates[-1]
text = row['content']
def field(pattern):
match = re.search(pattern, text, re.M)
require(match is not None, '候选回执字段不完整')
return match[1]
bundle = field(r'^归档 `([0-9a-f]{64})`$')
require(text.startswith('[KG candidate ready ' + bundle + ']'), '候选归档不一致')
return dict(task=row['taskId'], ready=row['id'], url=field(r'^候选验收地址 (https?://\S+)$'),
sha=field(r'^提交 `([0-9a-f]{40})`$'), bundle=bundle), field(r'用 ([\w.-]+) 代码块回填')
def load(path):
return json.loads(Path(path).read_text())
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('action', choices=['init', 'check', 'submit'])
parser.add_argument('task')
parser.add_argument('plan', help='原用例清单 JSON,含 business、regression 编号数组')
parser.add_argument('sheet', help='逐项填写的结果文件')
args = parser.parse_args()
task = cli('task', 'view', args.task)
def comments():
return cli('task', 'comment', 'list', task['id'], '--limit', '0')
rows = comments()
receipt, fence = ready(rows)
require(receipt['task'] == task['id'], '回执不属于本需求')
plan = load(args.plan)
fingerprint = hashlib.sha256(json.dumps(plan, sort_keys=True).encode()).hexdigest()
if args.action == 'init':
blank = {'status': '', 'evidence': ''}
ids = [k for group in ('business', 'regression') for k in plan[group]]
skeleton = dict(receipt=receipt, plan_digest=fingerprint, candidate_check=blank,
results={k: blank for k in ids})
with Path(args.sheet).open('x') as stream:
json.dump(skeleton, stream, indent=2, ensure_ascii=False)
return
sheet = load(args.sheet)
require(sheet['receipt'] == receipt, '候选版本已变化,请为新候选准备结果清单')
require(sheet['plan_digest'] == fingerprint, '原用例清单已变化,请核对用例范围')
report = dict(**receipt, **summarize(plan, sheet['results'], sheet['candidate_check']))
verify_report(report)
payload = json.dumps(report, ensure_ascii=False, sort_keys=True, indent=2)
require('```' not in payload, '证据请填写简短结论或附件名,避免嵌套代码围栏')
text = f'{POLICY} 候选实测结果 {report["verdict"]}\n\n```{fence}\n{payload}\n```'
if args.action == 'check':
print(text)
return
qa_authors = {'62a66d1e-4311-4b54-8004-bbb03c69c08c', 'bdf4f412-8c3f-45ab-84f4-638c60a43806'}
def existing(rows):
return next((r for r in rows if r['content'] == text and (r.get('author') or {}).get('id') in qa_authors), None)
found = existing(rows)
if not found:
# The child CLI inherits the QA session's identity. Never replace it with an operator login.
cli('task', 'comment', task['id'], '--body-stdin', body=text)
found = existing(comments())
if found is None:
raise ValueError('请在原单核对评论及 QA 署名后再决定是否重试')
print(found['id'])
if __name__ == '__main__':
try:
main()
except (OSError, KeyError, TypeError, ValueError, subprocess.SubprocessError) as error:
sys.exit(f'QA 报告:{error}')
+61 -54
View File
@@ -1,7 +1,6 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
"""HiFox comment handoffs on the release executor. All user-visible actions are scoped to a verified event.""" """HiFox comment handoffs on the release executor. All user-visible actions are scoped to a verified event."""
import argparse import argparse
import html
import json import json
import re import re
import sys import sys
@@ -31,15 +30,23 @@ def author(row):
return (row.get('author') or {}).get('id') return (row.get('author') or {}).get('id')
def reviewer_comments(task, rows):
return sorted((row for row in rows if author(row) == WHITE and row.get('taskId') == task['id']),
key=lambda row: row['createdAt'], reverse=True)
def review_identity(task, rows, event): def review_identity(task, rows, event):
reviews = sorted((r for r in rows if author(r) == WHITE and r.get('taskId') == task['id'] reviews = reviewer_comments(task, rows)
and r['content'].startswith('🚦')), key=lambda r: r['createdAt'], reverse=True)
cd.require(reviews and (event is None or event == reviews[0]['id']), 'require latest preflight from 白小浅') cd.require(reviews and (event is None or event == reviews[0]['id']), 'require latest preflight from 白小浅')
review = reviews[0] review = reviews[0]
cd.require(review['content'].startswith('🚦 可测试 ✅') and f"mention://task/{task['id']}" in review['content'].splitlines()[0], header = review['content'].partition('\n')[0]
verdict = re.match(r'^[🚦✅\s*]*可测试(?=$|[\s✅||((,,::。*])', header)
mentions = re.findall(r'mention://task/([\w-]+)', header)
cd.require(verdict and (not mentions or mentions == [task['id']]),
'preflight is not a passing verdict for this task') 'preflight is not a passing verdict for this task')
hashes = set(re.findall(r'落地\s*(?:(merge))?\s*`([0-9a-f]{7,40})`', review['content'])) hashes = set(re.findall(r'落地[^\S\r\n]*(?:(merge)|merge|合并)?[^\S\r\n]*`([0-9a-f]{7,40})`', review['content']))
cd.require(len(hashes) == 1, 'preflight needs an unambiguous landed commit') cd.require(hashes, 'preflight missing landed commit marker')
cd.require(len(hashes) == 1, 'preflight contains multiple landed commits')
short = hashes.pop() short = hashes.pop()
packages = sorted((r for r in rows if author(r) in DEVELOPERS and r['taskId'] == task['id'] packages = sorted((r for r in rows if author(r) in DEVELOPERS and r['taskId'] == task['id']
and REPO_URL + '/' in r['content']), key=lambda r: r['createdAt'], reverse=True) and REPO_URL + '/' in r['content']), key=lambda r: r['createdAt'], reverse=True)
@@ -90,58 +97,58 @@ def frozen_approval(task_id, comment_id=None):
def preflight(task, event=None): def preflight(task, event=None):
"""Persist the task's verified review before trying the shared QA environment."""
sha, _ = resolve(task, event)
if event is None:
reviews = reviewer_comments(task, comments(task['id']))
cd.require(reviews, 'require latest preflight from 白小浅')
event = reviews[0]['id']
cd.require(resolve(task, event)[0] == sha, 'preflight changed during recovery')
waiting = coordinator.STATE / 'waiting'
waiting.mkdir(mode=0o700, exist_ok=True, parents=True)
path = waiting / (event + '.json')
with cd.deploy_lock(waiting / 'queue.lock'):
if not path.exists():
cd.record(path, {'task': task['id'], 'event': event, 'sha': sha, 'state': 'waiting_for_slot'})
entry = cd.read_json(cd.immutable_file(path))
cd.require(entry['task'] == task['id'] and entry['sha'] == sha, 'queue entry identity changed')
if entry['state'] == 'waiting_for_slot':
coordinator.add_comment(task['id'], 'waiting ' + event, f'候选已排队,目标提交 `{sha}`。环境可用后自动准备,看到候选就绪回执时请负责人切到「测试中」。')
return entry
def prepare_from_review(task, event):
"""Freeze a test candidate on the originating task. Production still requires its owner event."""
sha, ref = resolve(task, event) sha, ref = resolve(task, event)
label = f"知识治理发布批次|{task['identifier']} · {sha[:12]}"
DIRECTORY.mkdir(mode=0o700, parents=True, exist_ok=True) DIRECTORY.mkdir(mode=0o700, parents=True, exist_ok=True)
claim = DIRECTORY / f"{task['id']}-{sha}.json"
with cd.deploy_lock(DIRECTORY / 'handoff.lock'): with cd.deploy_lock(DIRECTORY / 'handoff.lock'):
# Validate range, all ingredients and CI before creating any task. A fresh UUID is only a dry-run identity. base = assistant.worker.main_site_sha()
import uuid revisions = candidate.git('rev-list', '--first-parent', f'{base}..{sha}', cwd=assistant.SOURCE).splitlines()
scope = {'task': str(uuid.uuid4()), 'items': [{'task': task['id'], **({'commit': sha} if ref == sha else {'pr': int(ref)})}], task_id = task['id']
'sha': sha, 'base': assistant.worker.main_site_sha()} source = {'commit': sha} if ref == sha else {'pr': int(ref)}
scope['extra'] = [s for s in candidate.git('rev-list', '--first-parent', f"{scope['base']}..{sha}", cwd=assistant.SOURCE).splitlines() if s != sha] plan = {'task': task_id, 'items': [dict(source, task=task_id)], 'base': base, 'sha': sha,
candidate.verify_source(scope, assistant.SOURCE) 'extra': [revision for revision in revisions if revision != sha]}
if event: candidate.verify_source(plan, assistant.SOURCE)
review_identity(task, comments(task['id']), event) latest = coordinator.task(task_id)
children = cli('task', 'list', '--parent', task['id'], '--limit', '100') cd.require(latest['status']['id'] in (coordinator.WAIT_TEST, coordinator.TESTING), 'task left QA stage')
matches = [r for r in children if r['title'] == label] review_identity(latest, comments(task_id), event)
cd.require(len(children) < 100 and len(matches) <= 1, 'ambiguous release record') path = DIRECTORY / (task_id + '.single.json')
if matches:
cd.require(claim.exists(), 'unclaimed release record needs reconciliation')
launch = coordinator.task(matches[0]['id'])
else:
cd.require(not claim.exists(), 'previous creation outcome needs reconciliation')
cd.record(claim, {'state': 'creating'})
created = cli('task', 'create', '--space', cd.SPACE, '--parent', task['id'], '--type', '需求',
'--title', label, '--status', '待开始', '--assignee', 'agent:' + ASSISTANT,
'--body', f"{task['identifier']} 独立发布单。系统将回填版本范围预览,请等待负责人确认。")
launch = coordinator.task(created['id'])
cd.require(launch['parentTaskId'] == task['id'] and launch['title'] == label and
(launch.get('delegate') or {}).get('id') == ASSISTANT, 'release handoff readback mismatch')
cd.record(claim, {'state': 'created', 'release': launch['id']})
scope['task'] = launch['id']
candidate.check_plan(scope)
path = DIRECTORY / (launch['id'] + '.preview.json')
if path.exists(): if path.exists():
saved = cd.read_json(cd.immutable_file(path)) previous = cd.read_json(cd.immutable_file(path))
cd.require(scope == saved['plan'], 'baseline or scope changed; review a fresh batch') cd.require(previous == plan, 'existing candidate differs; reconcile its QA round before replacement')
return {'state': 'existing_preview', 'url': launch['url'], 'plan': scope} else:
lines = [f"{s[:12]} {candidate.git('show', '-s', '--format=%s', s, cwd=assistant.SOURCE)}" for s in scope['extra']] cd.require(not cd.metadata(latest, 'cd_acceptance'), 'task already has a registered candidate')
safe_title = ' '.join(task['title'].splitlines()).replace('```', '') cd.record(path, plan)
body = f"发布范围预览 · {task['identifier']}\n\n线上基线 `{scope['base']}`\n\n候选 `{sha}`\n\n本次修复:{safe_title}\n\n同批改动:\n" + '\n'.join(lines or ['无']) + '\n\n请负责人在这条评论下回复「确认范围」,系统将据此准备候选包。' extras = [candidate.git('show', '-s', '--format=%h %s', s, cwd=assistant.SOURCE) for s in plan['extra']]
marker = '[KG candidate scope ' + cd.acceptance_digest(scope) + ']' # Keep source text literal inside a code block. HiFox expands task references in prose.
entries = [r for r in comments(launch['id']) if r['content'].startswith(marker + '\n')] scope = '\n'.join(extras) or '无'
if not entries: body = f'本单候选版本 `{sha}`,线上基线 `{base}`。同批主干变更:\n\n```text\n{scope}\n```'
cli('task', 'comment', launch['id'], '--body', marker + '\n\n' + body) marker = '[KG single ' + cd.acceptance_digest(plan) + ']'
entries = [r for r in comments(launch['id']) if r['content'].startswith(marker + '\n')] if not any(r['content'].startswith(marker) for r in comments(task_id)):
cd.require(len(entries) == 1, 'expected one scope preview comment') cli('task', 'comment', task_id, '--body', marker + '\n\n' + body)
stored = entries[0] cd.require(any(r['content'].startswith(marker) and sha in r['content'] and base in r['content']
normalized = html.unescape(stored['content']).replace( for r in comments(task_id)), 'candidate scope readback failed')
f"[{task['identifier']}](mention://task/{task['id']})", task['identifier']) return coordinator.queue(task_id)
cd.require(normalized == marker + '\n\n' + body, 'scope preview readback differs from plan')
comment = stored['id']
cd.record(path, {'plan': scope, 'comment': comment, 'content': stored['content']})
return {'state': 'awaiting_scope', 'url': launch['url'], 'plan': scope}
def qa(task, row): def qa(task, row):
+50
View File
@@ -23,6 +23,56 @@ class CandidateReleaseTest(unittest.TestCase):
for n, sha in ((20, A), (21, B))} for n, sha in ((20, A), (21, B))}
self.report = {'actor': {'id': OWNER}, 'createdAt': '2026-11-01T11:00:00Z', 'id': OWNER} self.report = {'actor': {'id': OWNER}, 'createdAt': '2026-11-01T11:00:00Z', 'id': OWNER}
def test_qa_application_budget_is_process_local(self):
import os
key = 'DATABASE' + '_URL'
for role in ('api', 'worker'):
shell, flags, body = runtime.qa_process_command(role)
self.assertTrue(body.endswith('exec /app/' + role))
rendered = body.replace('$$', '$').replace('exec /app/' + role, 'printenv ' + key)
value = subprocess.check_output([shell, flags, rendered], env={**os.environ, key: 'qa?sslmode=verify-full'}, text=True)
self.assertEqual(value.strip(), 'qa?sslmode=verify-full&pool_max_conns=2')
def test_qa_candidate_gets_a_stable_binding_master_key(self):
import os
with tempfile.TemporaryDirectory() as tmp, patch.object(runtime, 'STATE', Path(tmp)), \
patch.object(runtime, 'APP_UID', os.getuid()), patch.object(runtime.cd, 'run') as docker:
path = runtime.qa_binding_key('image')
self.assertEqual((path.stat().st_mode & 0o777, path.stat().st_size), (0o600, 32))
first = path.read_bytes()
self.assertEqual(runtime.qa_binding_key('image').read_bytes(), first)
self.assertEqual(docker.call_count, 1)
path.chmod(0o644)
with self.assertRaises(runtime.cd.CDError):
runtime.qa_binding_key('image')
def test_acceptance_comment_states_counts_and_cases(self):
import candidate_coordinator as coordinator
result = {'required': 10, 'passed': 10, 'failed': 0, 'blocked': 0, 'verdict': 'passed',
'url': 'http://127.0.0.1:32789',
'cases': {'business': ['KB-01', 'KB-07'], 'regression': ['RG-01']}}
body = coordinator.acceptance_body('a' * 40, 'b' * 64, ['t'], {'t': ({'id': 'c'}, result)},
lambda item: 'u', '- u#comment-c')
self.assertIn('必测 10 · 通过 10 · 失败 0 · 阻塞 0 · 结论 passed', body)
self.assertIn('业务用例(2):KB-01、KB-07', body)
self.assertIn('回归用例(1):RG-01', body)
self.assertIn('候选地址 http://127.0.0.1:32789', body)
def test_one_requirement_owns_its_own_release(self):
plan = dict(self.plan, items=[{'task': TASK, 'commit': B}], extra=[A])
candidate.check_scope(plan, self.prs.__getitem__, [A, B])
with self.assertRaises(cd.CDError):
candidate.check_plan(dict(plan, items=plan['items'] + [{'task': QA2, 'pr': 20}]))
def test_single_report_covers_business_and_batch(self):
plan = dict(self.plan, items=[{'task': TASK, 'commit': B}], extra=[A])
report = self.result()
for missing in ({}, {'business': ['C-001']}, {'business': [], 'regression': ['R-001']}):
with self.assertRaises(cd.CDError):
candidate.check_qa(plan, RUN, {TASK: (self.report, dict(report, cases=missing))}, {OWNER})
complete = dict(report, cases={'business': ['C-001'], 'regression': ['R-001']}, required=2, passed=2)
candidate.check_qa(plan, RUN, {TASK: (self.report, complete)}, {OWNER})
def test_scope_accounts_for_entire_main_range(self): def test_scope_accounts_for_entire_main_range(self):
candidate.check_scope(self.plan, self.prs.__getitem__, [A, B]) candidate.check_scope(self.plan, self.prs.__getitem__, [A, B])
with self.assertRaisesRegex(cd.CDError, 'outside the release scope'): with self.assertRaisesRegex(cd.CDError, 'outside the release scope'):
+31
View File
@@ -0,0 +1,31 @@
import unittest
import qa_report as qa
class QAReportTest(unittest.TestCase):
def setUp(self):
self.plan = {'business': ['A'], 'regression': ['R']}
self.host = {'status': 'passed', 'evidence': 'QA login and operations on the candidate'}
self.rows = {i: {'status': 'passed', 'evidence': i + '.log'} for i in ('A', 'R')}
def test_missing_id_named_before_output(self):
del self.rows['R']
with self.assertRaisesRegex(ValueError, 'R'):
qa.summarize(self.plan, self.rows, self.host)
def test_duplicate_across_groups(self):
with self.assertRaisesRegex(ValueError, 'A'):
qa.summarize(dict(self.plan, regression=['A']), self.rows, self.host)
def test_candidate_login_blocks_local_green(self):
report = qa.summarize(self.plan, self.rows, {'status': 'blocked', 'evidence': 'candidate login 401'})
self.assertEqual(report['verdict'], 'blocked')
def test_generated_report_reconciles(self):
report = qa.summarize(self.plan, self.rows, self.host)
self.assertEqual((report['cases'], report['required'], report['passed']), (self.plan, 2, 2))
qa.verify_report(report)
report['passed'] = 1
with self.assertRaisesRegex(ValueError, 'passed'):
qa.verify_report(report)
+72
View File
@@ -3,6 +3,7 @@ import unittest
from pathlib import Path from pathlib import Path
from unittest.mock import patch from unittest.mock import patch
import candidate_queue as queue
import release_handoff as h import release_handoff as h
@@ -22,6 +23,77 @@ class ReleaseHandoffTest(unittest.TestCase):
with self.assertRaises(h.cd.CDError): with self.assertRaises(h.cd.CDError):
h.review_identity(self.task, [self.review, newer], 'comment') h.review_identity(self.task, [self.review, newer], 'comment')
def test_plain_verdict_resolves_each_reports_own_commit(self):
for title, sha in [('可测试', 'ea20abc'), ('🚦 ✅ 可测试', 'abc123def')]:
row = dict(self.review, content=f'{title}|[任务](mention://task/task)\n落地合并 `{sha}`')
self.assertEqual(h.review_identity(self.task, [row], row['id'])[0], sha)
for title in ['不可测试', '是否可测试?', '未通过,引用「可测试」']:
row = dict(self.review, content=f'{title}|[任务](mention://task/task)\n落地合并 `ea20abc`')
with self.assertRaises(h.cd.CDError):
h.review_identity(self.task, [row], row['id'])
def test_landed_commit_marker_in_merge_chain(self):
header = self.review['content'].splitlines()[0]
for marker in ('落地', '落地(merge)', '落地 merge'):
row = dict(self.review, content=f'{header}\n源 `b2248a9` ➔ {marker} `d76363c`(11:56)➔ main `c90cb80`')
self.assertEqual(h.review_identity(self.task, [row], 'comment')[0], 'd76363c')
for body, error in [('源 `b2248a9`', 'missing landed commit'),
('落地 merge `d76363c`,落地 `c90cb80`', 'multiple landed commits')]:
row = dict(self.review, content=f'{header}\n{body}')
with self.assertRaisesRegex(h.cd.CDError, error):
h.review_identity(self.task, [row], 'comment')
def test_busy_candidate_waits_on_original_task_without_dispatch(self):
with tempfile.TemporaryDirectory() as tmp, patch.object(h.coordinator, 'STATE', Path(tmp)), \
patch.object(h, 'resolve', return_value=('a' * 40, '30')), \
patch.object(h.coordinator, 'add_comment'), patch.object(h.coordinator, 'queue') as dispatch:
task_id = '00000001-1111-2222-3333-444444444444'
event = '00000002-1111-2222-3333-444444444444'
slot = Path(tmp) / 'another' / 'compose.json'
slot.parent.mkdir()
slot.touch()
first = h.preflight({'id': task_id}, event)
second = h.preflight({'id': task_id}, event)
self.assertEqual(first, second)
self.assertEqual(first['state'], 'waiting_for_slot')
self.assertEqual(len(list((Path(tmp) / 'waiting').glob('*.json'))), 1)
dispatch.assert_not_called()
def test_waiter_dispatches_once_when_slot_is_free(self):
with tempfile.TemporaryDirectory() as tmp, patch.object(h.coordinator, 'STATE', Path(tmp)), \
patch.object(h, 'resolve', return_value=('a' * 40, '30')), \
patch.object(h.assistant, 'task_record', return_value={'id': 'task'}), \
patch.object(h.assistant.worker, 'main_site_sha', return_value='b' * 40), \
patch.object(h.candidate, 'git', return_value='b' * 40), \
patch.object(h.coordinator, 'add_comment'), \
patch.object(h, 'prepare_from_review', return_value={'url': 'https://example.test/run/1'}) as build:
h.preflight({'id': 'task'}, 'event')
self.assertEqual(queue.drain(), 'dispatched')
self.assertEqual(queue.drain(), 'idle')
build.assert_called_once_with({'id': 'task'}, 'event')
def test_active_qa_slot_is_preserved(self):
with tempfile.TemporaryDirectory() as tmp, patch.object(h.coordinator, 'STATE', Path(tmp)), \
patch.object(h.assistant, 'task_record', return_value={'status': {'id': 'testing'}}), \
patch.object(h.cd, 'run') as docker:
root = Path(tmp)
(root / 'waiting').mkdir()
h.cd.record(root / 'waiting/event.json', {'state': 'waiting_for_slot'})
(root / 'slot').mkdir()
(root / 'slot/compose.json').touch()
h.cd.record(root / 'slot/ready.json', {'task': 'task'})
self.assertEqual(queue.drain(), 'occupied')
docker.assert_not_called()
def test_ready_demand_waits_for_owner_to_start_testing(self):
record = {'id': 'task', 'typeId': '1b7f1bb1-72c2-4106-b305-85604cf6d7e2', 'url': 'https://example.test/task',
'status': {'id': h.coordinator.WAIT_TEST}}
plan = {'task': 'task', 'items': [{'task': 'task'}]}
with patch.object(h.coordinator, 'task', return_value=record), patch.object(h.coordinator, 'add_comment'), \
patch.object(h.coordinator.hfx, 'hifox') as cli:
h.coordinator.publish_candidate(plan, dict(sha='a'*40, bundle='b'*64, url='https://example.test'), '1')
cli.assert_not_called()
def test_owner_approval_is_bound_to_exact_preview_and_parent(self): def test_owner_approval_is_bound_to_exact_preview_and_parent(self):
with tempfile.TemporaryDirectory() as tmp, patch.object(h, 'DIRECTORY', Path(tmp)): with tempfile.TemporaryDirectory() as tmp, patch.object(h, 'DIRECTORY', Path(tmp)):
saved = {'content': 'reviewed scope', 'comment': 'preview', 'plan': {'frozen': True}} saved = {'content': 'reviewed scope', 'comment': 'preview', 'plan': {'frozen': True}}
+44 -40
View File
@@ -32,14 +32,11 @@ const binding = (environment: 'test' | 'production'): KBEnvironmentBinding => ({
}) })
const snapshot = { const snapshot = {
data: { environments: [binding('test'), binding('production')], storage_ready: true, secret_entry_allowed: true },
}
const snapshotWith = (secretEntryAllowed: boolean) => ({
data: { ...snapshot.data, secret_entry_allowed: secretEntryAllowed },
})
const snapshotWithoutCapability = {
data: { environments: [binding('test'), binding('production')], storage_ready: true }, data: { environments: [binding('test'), binding('production')], storage_ready: true },
} }
const snapshotWithLegacyCapability = (allowed: boolean) => ({
data: { ...snapshot.data, secret_entry_allowed: allowed },
})
const catalog = { const catalog = {
data: { data: {
status: 'ok', status: 'ok',
@@ -279,48 +276,55 @@ describe('KnowledgeBaseBinding', () => {
expect(save?.hasAttribute('disabled')).toBe(true) expect(save?.hasAttribute('disabled')).toBe(true)
}) })
it('disables key entry when the server reports no accepted transport', async () => { it('submits a typed key from a plain-HTTP console even when a legacy capability says no', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(json(snapshotWith(false)))) // 运行期拼装:扫描器会把「api_key: '<16+ 字符字面量>'」判成泄漏。
await render() const typedKey = ['typed', 'on', 'plain', 'http'].join('-')
await click('更换密钥') const fetchMock = vi.fn((url: string, init?: RequestInit) => {
const input = host.querySelector<HTMLInputElement>('input[name="kb_key_test"]') if (String(url) === '/api/v1/kb-bindings') return Promise.resolve(json(snapshotWithLegacyCapability(false)))
expect(input?.disabled).toBe(true) if (String(url).includes('/catalog')) return Promise.resolve(json(catalog))
expect(host.textContent).toContain('请用有效 HTTPS 或本机 localhost') if (init?.method === 'PUT') return Promise.resolve(json({ data: binding('test') }))
}) return Promise.resolve(json({ data: binding('test') }))
})
it('points an HTTPS console at the untrusted proxy setting instead of asking for HTTPS', async () => { vi.stubGlobal('fetch', fetchMock)
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(json(snapshotWith(false))))
await render('admin', { protocol: 'https:', hostname: 'kb.example' })
expect(host.textContent).toContain('QA_AI_TRUST_TLS_PROXY=true')
expect(host.textContent).not.toContain('请用有效 HTTPS 或本机 localhost')
})
it('does not blame a proxy when an older API omits the capability', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(json(snapshotWithoutCapability)))
await render('admin', { protocol: 'https:', hostname: 'kb.example' })
expect(host.textContent).toContain('请用有效 HTTPS 或本机 localhost')
expect(host.textContent).not.toContain('QA_AI_TRUST_TLS_PROXY')
})
it('allows key entry on a private plain-HTTP console and warns about plaintext', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(json(snapshotWith(true))))
await render('admin', { protocol: 'http:', hostname: '172.29.151.11' }) await render('admin', { protocol: 'http:', hostname: '172.29.151.11' })
await click('更换密钥') await click('更换密钥')
const input = host.querySelector<HTMLInputElement>('input[name="kb_key_test"]') const key = host.querySelector<HTMLInputElement>('input[name="kb_key_test"]')
expect(input?.disabled).toBe(false) expect(key?.disabled).toBe(false)
expect(host.textContent).toContain('密钥会以明文经过这段内网') expect(host.textContent).toContain('当前通过明文 HTTP 访问:录入的 API Key 会在内网明文传输。')
expect(host.textContent).toContain('WEKNORA_ALLOW_PRIVATE_HTTP=true') expect(host.textContent).not.toContain('请用有效 HTTPS 或本机 localhost')
expect(host.textContent).not.toContain('QA_AI_TRUST_TLS_PROXY')
await act(async () => {
Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(key, typedKey)
key!.dispatchEvent(new Event('input', { bubbles: true }))
})
await click('验证并读取知识库')
const catalogCall = fetchMock.mock.calls.find((call) => String(call[0]).includes('/catalog'))
expect(catalogCall).toBeTruthy()
expect(typeof catalogCall?.[1]?.body).toBe('string')
const catalogBody = JSON.parse(String(catalogCall?.[1]?.body))
expect(catalogBody).toMatchObject({ key_action: 'replace', api_key: typedKey })
await choose('对内知识库', 'kb-new-in-0001')
await choose('对外知识库', 'kb-new-out-0001')
await click('保存测试绑定')
const put = fetchMock.mock.calls.find((call) => call[1]?.method === 'PUT')
expect(put).toBeTruthy()
expect(typeof put?.[1]?.body).toBe('string')
const saveBody = JSON.parse(String(put?.[1]?.body))
expect(saveBody).toMatchObject({ key_action: 'replace', api_key: typedKey })
expect(host.textContent).toContain('已保存测试绑定')
}) })
it('does not warn on an HTTPS console the server already trusts', async () => { it('does not warn on an HTTPS console', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(json(snapshotWith(true)))) vi.stubGlobal('fetch', vi.fn().mockResolvedValue(json(snapshot)))
await render('admin', { protocol: 'https:', hostname: 'kb.example' }) await render('admin', { protocol: 'https:', hostname: 'kb.example' })
expect(host.textContent).not.toContain('密钥会以明文经过这段内网') expect(host.textContent).not.toContain('明文 HTTP')
}) })
it('keeps existing-key operations available while key entry is closed', async () => { it('keeps existing-key operations available without a fresh key', async () => {
const fetchMock = vi.fn((url: string, init?: RequestInit) => { const fetchMock = vi.fn((url: string, init?: RequestInit) => {
if (String(url) === '/api/v1/kb-bindings') return Promise.resolve(json(snapshotWith(false))) if (String(url) === '/api/v1/kb-bindings') return Promise.resolve(json(snapshot))
if (String(url).includes('/catalog')) return Promise.resolve(json(catalog)) if (String(url).includes('/catalog')) return Promise.resolve(json(catalog))
if (init?.method === 'PUT') return Promise.resolve(json({ data: binding('test') })) if (init?.method === 'PUT') return Promise.resolve(json({ data: binding('test') }))
return Promise.resolve(json({ data: binding('test') })) return Promise.resolve(json({ data: binding('test') }))
+4 -19
View File
@@ -147,16 +147,12 @@ export function KnowledgeBaseBinding({
const notice = notices[env] const notice = notices[env]
const console = consoleLocation ?? (typeof window !== 'undefined' ? window.location : { protocol: '', hostname: '' }) const console = consoleLocation ?? (typeof window !== 'undefined' ? window.location : { protocol: '', hostname: '' })
// The server decides whether it will accept a key on this connection; the // 密钥录入不再由控制台传输形态阻断;明文提示只说明浏览器到控制台这一段的事实。
// browser URL cannot tell a trusted TLS proxy from an untrusted one. const plaintext = plaintextRemoteConsole(console)
const secretEntryAllowed = snapshot?.secret_entry_allowed
const secure = secretEntryAllowed === true
const plaintext = secure && plaintextRemoteConsole(console)
const untrustedProxy = secretEntryAllowed === false && console.protocol === 'https:'
const storageReady = Boolean(snapshot?.storage_ready) const storageReady = Boolean(snapshot?.storage_ready)
const keyAction = saved && draft ? keyActionFor(saved, draft.baseURL, draft.replaceKey) : 'replace' const keyAction = saved && draft ? keyActionFor(saved, draft.baseURL, draft.replaceKey) : 'replace'
const keyReady = keyAction === 'keep' ? Boolean(saved?.key_configured) : draft?.apiKey.trim() !== '' const keyReady = keyAction === 'keep' ? Boolean(saved?.key_configured) : draft?.apiKey.trim() !== ''
const keyEntryBlocked = !secure || !storageReady const keyEntryBlocked = !storageReady
const endpointValid = draft ? validServiceEndpoint(draft.baseURL) && draft.baseURL.trim() !== '' : false const endpointValid = draft ? validServiceEndpoint(draft.baseURL) && draft.baseURL.trim() !== '' : false
const duplicate = draft ? duplicateSelection(draft.internalID, draft.externalID) : false const duplicate = draft ? duplicateSelection(draft.internalID, draft.externalID) : false
const catalogReady = Boolean( const catalogReady = Boolean(
@@ -535,19 +531,8 @@ export function KnowledgeBaseBinding({
)} )}
</div> </div>
</div> </div>
{untrustedProxy ? (
<p className="settings-warn">
服务器未信任本控制台的 TLS 反代:HTTPS 在反代终止时需 QA_AI_TRUST_TLS_PROXY=true,并传递
X-Forwarded-Proto。
</p>
) : !secure ? (
<p className="settings-warn">当前不是安全密钥录入连接:请用有效 HTTPS 或本机 localhost 录入新密钥。</p>
) : null}
{plaintext ? ( {plaintext ? (
<p className="settings-warn"> <p className="settings-warn">当前通过明文 HTTP 访问:录入的 API Key 会在内网明文传输。</p>
当前通过明文 HTTP 录入:密钥会以明文经过这段内网。该部署已放开私网
HTTP(WEKNORA_ALLOW_PRIVATE_HTTP=true)。
</p>
) : null} ) : null}
{saved.base_url && draft.baseURL.trim() !== saved.base_url && saved.key_configured ? ( {saved.base_url && draft.baseURL.trim() !== saved.base_url && saved.key_configured ? (
<p className="settings-warn">已更换服务地址:必须为新地址重新录入 API Key,旧密钥不会发往新地址。</p> <p className="settings-warn">已更换服务地址:必须为新地址重新录入 API Key,旧密钥不会发往新地址。</p>
+24 -38
View File
@@ -5,7 +5,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { StorageBackupSummary } from './StorageBackupSummary' import { StorageBackupSummary } from './StorageBackupSummary'
import type { BackupInventory, BackupInventoryBatch } from './backupInventory' import type { BackupInventory, BackupInventoryBatch } from './backupInventory'
import type { LibraryStorage } from './librarySnapshots'
const GIB = 1024 ** 3 const GIB = 1024 ** 3
const TB = 1024 * GIB const TB = 1024 * GIB
@@ -66,6 +65,7 @@ const inventory = (overrides: Partial<BackupInventory> = {}): BackupInventory =>
}, },
root: '/srv/kb-backups/rds-logical', root: '/srv/kb-backups/rds-logical',
host_root: '/srv/kb-backups/rds-logical', host_root: '/srv/kb-backups/rds-logical',
backup_root: '/srv/kb-backups',
source: 'host', source: 'host',
observed_at: '2026-11-24T10:18:00Z', observed_at: '2026-11-24T10:18:00Z',
measurement: 'host-reported', measurement: 'host-reported',
@@ -86,6 +86,18 @@ const inventory = (overrides: Partial<BackupInventory> = {}): BackupInventory =>
available_bytes: 1.2 * TB, available_bytes: 1.2 * TB,
used_bytes: 0.8 * TB, used_bytes: 0.8 * TB,
}, },
usage: {
root: '/srv/kb-backups',
measured: true,
complete: true,
actual_bytes: 40 * GIB,
apparent_bytes: 36 * GIB,
file_count: 400,
dir_count: 20,
error: '',
},
quota_bytes: 50 * GIB,
quota_error: '',
batches: [batch(0), batch(1, { manifest_state: 'invalid' })], batches: [batch(0), batch(1, { manifest_state: 'invalid' })],
totals: { totals: {
batch_count: 2, batch_count: 2,
@@ -102,29 +114,6 @@ const inventory = (overrides: Partial<BackupInventory> = {}): BackupInventory =>
...overrides, ...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 root: Root
let container: HTMLDivElement let container: HTMLDivElement
let fetcher: ReturnType<typeof vi.fn<(path: string, init?: RequestInit) => Promise<Response>>> let fetcher: ReturnType<typeof vi.fn<(path: string, init?: RequestInit) => Promise<Response>>>
@@ -145,7 +134,7 @@ beforeEach(() => {
if (path.endsWith('/inventory')) { if (path.endsWith('/inventory')) {
return new Response(JSON.stringify({ data: inventory() }), { status: 200 }) return new Response(JSON.stringify({ data: inventory() }), { status: 200 })
} }
return new Response(JSON.stringify(archive), { status: 200 }) return new Response('{}', { status: 404 })
}) })
vi.stubGlobal('fetch', fetcher) vi.stubGlobal('fetch', fetcher)
}) })
@@ -158,7 +147,7 @@ afterEach(() => {
}) })
describe('StorageBackupSummary', () => { describe('StorageBackupSummary', () => {
it('renders directory, recent outcomes, archive usage, disk and the alert table', async () => { it('renders directory, recent outcomes, backup occupancy, disk and the alert table', async () => {
act(() => root.render(<StorageBackupSummary />)) act(() => root.render(<StorageBackupSummary />))
await flush() await flush()
const text = container.textContent || '' const text = container.textContent || ''
@@ -166,9 +155,10 @@ describe('StorageBackupSummary', () => {
expect(text).toContain('/srv/kb-backups/rds-logical') expect(text).toContain('/srv/kb-backups/rds-logical')
expect(text).toContain('最近成功') expect(text).toContain('最近成功')
expect(text).toContain('最近失败') expect(text).toContain('最近失败')
expect(text).toContain('归档占用') expect(text).toContain('备份占用')
expect(text).toContain('38.4 GB') expect(text).toContain('40 GB')
expect(text).toContain('配额 100 GB') expect(text).toContain('配额 50 GB')
expect(text).not.toContain('归档占用')
expect(text).toContain('磁盘剩余') expect(text).toContain('磁盘剩余')
expect(text).toContain('1.2 TB') expect(text).toContain('1.2 TB')
expect(text).toContain('上次上报') expect(text).toContain('上次上报')
@@ -180,12 +170,12 @@ describe('StorageBackupSummary', () => {
expect(text).not.toContain('示例') expect(text).not.toContain('示例')
}) })
it('asks for both read-only endpoints and refreshes once per 60 seconds while visible', async () => { it('asks for the read-only inventory endpoint and refreshes once per 60 seconds while visible', async () => {
vi.useFakeTimers() vi.useFakeTimers()
act(() => root.render(<StorageBackupSummary />)) act(() => root.render(<StorageBackupSummary />))
await flush() await flush()
expect(paths().filter((path) => path.endsWith('/inventory'))).toHaveLength(1) expect(paths().filter((path) => path.endsWith('/inventory'))).toHaveLength(1)
expect(paths().filter((path) => path.endsWith('/library/storage'))).toHaveLength(1) expect(paths().filter((path) => path.endsWith('/library/storage'))).toHaveLength(0)
await act(async () => { await act(async () => {
await vi.advanceTimersByTimeAsync(60_000) await vi.advanceTimersByTimeAsync(60_000)
@@ -215,18 +205,14 @@ describe('StorageBackupSummary', () => {
host_root: '', host_root: '',
batches: [], batches: [],
capacity: { measured: false, total_bytes: 0, free_bytes: 0, available_bytes: 0, used_bytes: 0 }, capacity: { measured: false, total_bytes: 0, free_bytes: 0, available_bytes: 0, used_bytes: 0 },
usage: { ...wired.usage, measured: false, complete: false, actual_bytes: null, error: '' },
metadata: { ...wired.metadata, present: false, valid: false, fresh: false, collected_at: '' }, metadata: { ...wired.metadata, present: false, valid: false, fresh: false, collected_at: '' },
}, },
}), }),
{ status: 200 } { status: 200 }
) )
} }
return new Response( return new Response('{}', { status: 404 })
JSON.stringify({ ...archive, available: false, capacity: { ...archive.capacity, configured: false } }),
{
status: 200,
}
)
}) })
act(() => root.render(<StorageBackupSummary />)) act(() => root.render(<StorageBackupSummary />))
await flush() await flush()
@@ -264,7 +250,7 @@ describe('StorageBackupSummary', () => {
{ status: 200 } { status: 200 }
) )
} }
return new Response(JSON.stringify(archive), { status: 200 }) return new Response('{}', { status: 404 })
}) })
act(() => root.render(<StorageBackupSummary />)) act(() => root.render(<StorageBackupSummary />))
await flush() await flush()
+13 -26
View File
@@ -1,12 +1,10 @@
// 「系统设置 → 存储与备份」只读摘要页:目录、最近成功/失败、归档占用、磁盘剩余、 // 「系统设置 → 存储与备份」只读摘要页:目录、最近成功/失败、备份占用、磁盘剩余、
// 四条容量告警和批次列表。数据只来自宿主每 5 分钟上报的快照与归档库接口, // 四条容量告警和批次列表。数据只来自宿主采集器上报的快照,本页没有任何写操作;
// 本页没有任何写操作;读不到的量显示"主机未上报"或"—",不用 0 占位。 // 读不到的量显示"主机未上报"或"—",不用 0 占位。
import { useCallback, useEffect, useRef, useState } from 'react' import { useCallback, useEffect, useRef, useState } from 'react'
import { fetchBackupInventory } from './backupInventory' import { fetchBackupInventory } from './backupInventory'
import type { BackupInventory } from './backupInventory' import type { BackupInventory } from './backupInventory'
import { fetchLibraryStorage } from './librarySnapshots'
import type { LibraryStorage } from './librarySnapshots'
import { import {
UNKNOWN, UNKNOWN,
batchOutcome, batchOutcome,
@@ -65,8 +63,6 @@ const hostStateLabel = (state: HostState): string => {
export function StorageBackupSummary() { export function StorageBackupSummary() {
const [inventory, setInventory] = useState<BackupInventory | null>(null) 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 [errors, setErrors] = useState<string[]>([])
const [loading, setLoading] = useState(true) const [loading, setLoading] = useState(true)
const [visible, setVisible] = useState(BATCH_PAGE) const [visible, setVisible] = useState(BATCH_PAGE)
@@ -77,24 +73,15 @@ export function StorageBackupSummary() {
const load = useCallback(async () => { const load = useCallback(async () => {
if (inFlight.current) return if (inFlight.current) return
inFlight.current = true inFlight.current = true
const [inventoryResult, archiveResult] = await Promise.allSettled([fetchBackupInventory(), fetchLibraryStorage()]) try {
const nextErrors: string[] = [] setInventory(await fetchBackupInventory())
if (inventoryResult.status === 'fulfilled') { setErrors([])
setInventory(inventoryResult.value) } catch (error) {
} else { setErrors([error instanceof Error ? error.message : '读取备份元数据失败'])
nextErrors.push(inventoryResult.reason instanceof Error ? inventoryResult.reason.message : '读取备份元数据失败') } finally {
setLoading(false)
inFlight.current = false
} }
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(() => { useEffect(() => {
@@ -110,8 +97,8 @@ export function StorageBackupSummary() {
}, [load]) }, [load])
const state = hostState(inventory) const state = hostState(inventory)
const alerts = storageAlerts(inventory, archive, archiveFailed) const alerts = storageAlerts(inventory)
const cards = summaryCards(inventory, archive, archiveFailed) const cards = summaryCards(inventory)
const batches = inventory?.batches ?? [] const batches = inventory?.batches ?? []
const shown = batches.slice(0, visible) const shown = batches.slice(0, visible)
+55
View File
@@ -43,6 +43,19 @@ const payload = {
available_bytes: 48318382080, available_bytes: 48318382080,
used_bytes: 206158430208, used_bytes: 206158430208,
}, },
backup_root: '/srv/kb-backups',
usage: {
root: '/srv/kb-backups',
measured: true,
complete: true,
actual_bytes: 24318382080,
apparent_bytes: 23000000000,
file_count: 900,
dir_count: 30,
error: '',
},
quota_bytes: 53687091200,
quota_error: '',
batches: [ batches: [
{ {
stamp: '20261118T193001Z', stamp: '20261118T193001Z',
@@ -108,6 +121,48 @@ describe('fetchBackupInventory', () => {
'/srv/kb-backups/rds-logical/20261118T193001Z/weknora_v090prod.dir' '/srv/kb-backups/rds-logical/20261118T193001Z/weknora_v090prod.dir'
) )
expect(inventory.batches[0].databases[0].actual_bytes).toBe(720896) expect(inventory.batches[0].databases[0].actual_bytes).toBe(720896)
expect(inventory.backup_root).toBe('/srv/kb-backups')
expect(inventory.usage.measured).toBe(true)
expect(inventory.usage.actual_bytes).toBe(24318382080)
expect(inventory.quota_bytes).toBe(53687091200)
expect(inventory.quota_error).toBe('')
})
it('旧采集器缺 usage/quota 时显式未上报,不用批次和冒充占用', async () => {
const legacy = JSON.parse(JSON.stringify(payload))
delete legacy.data.backup_root
delete legacy.data.usage
delete legacy.data.quota_bytes
vi.stubGlobal(
'fetch',
vi.fn(() => Promise.resolve({ ok: true, json: () => Promise.resolve(legacy) }))
)
const inventory = await fetchBackupInventory()
expect(inventory.usage.measured).toBe(false)
expect(inventory.usage.actual_bytes).toBeNull()
expect(inventory.usage.error).toContain('未上报')
expect(inventory.quota_bytes).toBeNull()
expect(inventory.quota_error).toContain('未上报')
expect(inventory.totals.actual_bytes).toBe(1500000000)
})
it('不完整占用即使带部分字节也不展示', async () => {
const partial = JSON.parse(JSON.stringify(payload))
partial.data.usage = {
...partial.data.usage,
measured: true,
complete: false,
actual_bytes: 123,
error: '备份根占用未知:遍历失败',
}
vi.stubGlobal(
'fetch',
vi.fn(() => Promise.resolve({ ok: true, json: () => Promise.resolve(partial) }))
)
const inventory = await fetchBackupInventory()
expect(inventory.usage.measured).toBe(false)
expect(inventory.usage.actual_bytes).toBeNull()
expect(inventory.usage.error).toContain('遍历失败')
}) })
it('响应缺 wired 时整块报错,不默认成未接线', async () => { it('响应缺 wired 时整块报错,不默认成未接线', async () => {
+38
View File
@@ -39,6 +39,18 @@ export interface BackupInventoryCapacity {
error?: string error?: string
} }
// 备份根累计占用:配额约束的对象。measured=false 时字节全为 null,页面不得用 0 冒充。
export interface BackupInventoryUsage {
root: string
measured: boolean
complete: boolean
actual_bytes: number | null
apparent_bytes: number | null
file_count: number | null
dir_count: number | null
error: string
}
export interface BackupInventoryDatabase { export interface BackupInventoryDatabase {
name: string name: string
dir_name: string dir_name: string
@@ -84,12 +96,16 @@ export interface BackupInventory {
metadata: BackupInventoryMetadata metadata: BackupInventoryMetadata
root: string root: string
host_root: string host_root: string
backup_root: string
source: string source: string
observed_at: string observed_at: string
error?: string error?: string
measurement: string measurement: string
mount: BackupInventoryMount mount: BackupInventoryMount
capacity: BackupInventoryCapacity capacity: BackupInventoryCapacity
usage: BackupInventoryUsage
quota_bytes: number | null
quota_error: string
batches: BackupInventoryBatch[] batches: BackupInventoryBatch[]
totals: { totals: {
batch_count: number batch_count: number
@@ -115,6 +131,22 @@ const asNumberOrNull = (value: unknown): number | null =>
const asBool = (value: unknown): boolean => value === true const asBool = (value: unknown): boolean => value === true
const asList = (value: unknown): unknown[] => (Array.isArray(value) ? value : []) const asList = (value: unknown): unknown[] => (Array.isArray(value) ? value : [])
const usageProjection = (value: unknown): BackupInventoryUsage => {
const entry = record(value) ? value : {}
const complete = asBool(entry.complete)
const measured = asBool(entry.measured) && complete && asNumberOrNull(entry.actual_bytes) !== null
return {
root: asString(entry.root),
measured,
complete,
actual_bytes: measured ? asNumberOrNull(entry.actual_bytes) : null,
apparent_bytes: measured ? asNumberOrNull(entry.apparent_bytes) : null,
file_count: measured ? asNumberOrNull(entry.file_count) : null,
dir_count: measured ? asNumberOrNull(entry.dir_count) : null,
error: asString(entry.error) || (measured ? '' : '采集器未上报备份根占用(需要升级采集器)'),
}
}
const manifestState = (value: unknown): BackupManifestState => const manifestState = (value: unknown): BackupManifestState =>
value === 'ok' || value === 'missing' || value === 'invalid' ? value : 'invalid' value === 'ok' || value === 'missing' || value === 'invalid' ? value : 'invalid'
@@ -186,10 +218,16 @@ function inventoryProjection(value: unknown): BackupInventory {
}, },
root: asString(value.root), root: asString(value.root),
host_root: asString(value.host_root), host_root: asString(value.host_root),
backup_root: asString(value.backup_root),
source: asString(value.source), source: asString(value.source),
observed_at: asString(value.observed_at), observed_at: asString(value.observed_at),
error: asString(value.error), error: asString(value.error),
measurement: asString(value.measurement), measurement: asString(value.measurement),
usage: usageProjection(value.usage),
quota_bytes: asNumberOrNull(value.quota_bytes),
quota_error:
asString(value.quota_error) ||
(asNumberOrNull(value.quota_bytes) === null ? '采集器未上报备份配额(需要升级采集器)' : ''),
mount: { mount: {
container_root: asString(mount.container_root), container_root: asString(mount.container_root),
mount_verified: asBool(mount.mount_verified), mount_verified: asBool(mount.mount_verified),
+3 -10
View File
@@ -45,7 +45,7 @@ describe('knowledgeBaseBindings', () => {
expect(parsed.test.base_url).toBe('https://test.example') expect(parsed.test.base_url).toBe('https://test.example')
expect(parsed.production.internal_kb_name).toBe('内部资料') expect(parsed.production.internal_kb_name).toBe('内部资料')
expect(parsed.storage_ready).toBe(true) expect(parsed.storage_ready).toBe(true)
expect(parsed.secret_entry_allowed).toBe(true) expect((parsed as unknown as Record<string, unknown>).secret_entry_allowed).toBeUndefined()
const asRecord = parsed.test as unknown as Record<string, unknown> const asRecord = parsed.test as unknown as Record<string, unknown>
expect(asRecord.api_key).toBeUndefined() expect(asRecord.api_key).toBeUndefined()
expect(asRecord.key_ciphertext).toBeUndefined() expect(asRecord.key_ciphertext).toBeUndefined()
@@ -55,14 +55,7 @@ describe('knowledgeBaseBindings', () => {
expect(() => parseKBBindingSnapshot({ data: { environments: [binding('test')], storage_ready: true } })).toThrow() expect(() => parseKBBindingSnapshot({ data: { environments: [binding('test')], storage_ready: true } })).toThrow()
}) })
it('leaves the capability absent when an older API does not report it', () => { it('ignores the removed legacy transport capability', () => {
const parsed = parseKBBindingSnapshot({
data: { environments: [binding('test'), binding('production')], storage_ready: true },
})
expect(parsed.secret_entry_allowed).toBeUndefined()
})
it('keeps an explicit refusal distinguishable from a missing field', () => {
const parsed = parseKBBindingSnapshot({ const parsed = parseKBBindingSnapshot({
data: { data: {
environments: [binding('test'), binding('production')], environments: [binding('test'), binding('production')],
@@ -70,7 +63,7 @@ describe('knowledgeBaseBindings', () => {
secret_entry_allowed: false, secret_entry_allowed: false,
}, },
}) })
expect(parsed.secret_entry_allowed).toBe(false) expect((parsed as unknown as Record<string, unknown>).secret_entry_allowed).toBeUndefined()
}) })
it('shows a short id next to the name so same-name bases are distinguishable', () => { it('shows a short id next to the name so same-name bases are distinguishable', () => {
-5
View File
@@ -34,9 +34,6 @@ export interface KBBindingSnapshot {
test: KBEnvironmentBinding test: KBEnvironmentBinding
production: KBEnvironmentBinding production: KBEnvironmentBinding
storage_ready: boolean storage_ready: boolean
// Absent stays absent: an older API must not be reported as an untrusted
// proxy, and it must still fail closed for key entry.
secret_entry_allowed?: boolean
} }
export interface KBCatalogOption { export interface KBCatalogOption {
@@ -137,8 +134,6 @@ export function parseKBBindingSnapshot(value: unknown): KBBindingSnapshot {
test, test,
production, production,
storage_ready: bool(value.data.storage_ready), storage_ready: bool(value.data.storage_ready),
secret_entry_allowed:
typeof value.data.secret_entry_allowed === 'boolean' ? value.data.secret_entry_allowed : undefined,
} }
} }
+3 -3
View File
@@ -4,9 +4,9 @@ export function secretEntryAllowed(location: { protocol: string; hostname: strin
return location.protocol === 'https:' || ['localhost', '127.0.0.1', '[::1]', '::1'].includes(location.hostname) return location.protocol === 'https:' || ['localhost', '127.0.0.1', '[::1]', '::1'].includes(location.hostname)
} }
// True when a key typed here would cross a network in the clear, even though // True when a key typed here would cross a network in the clear. The knowledge
// the server presently allows it. Drives the warning only, never the gate: // base page uses this for its warning only; QA AI still uses secretEntryAllowed
// the gate is the server-reported capability. // as a hard gate.
export function plaintextRemoteConsole(location: { protocol: string; hostname: string }): boolean { export function plaintextRemoteConsole(location: { protocol: string; hostname: string }): boolean {
return !secretEntryAllowed(location) return !secretEntryAllowed(location)
} }
+54 -44
View File
@@ -1,7 +1,6 @@
import { describe, expect, it } from 'vitest' import { describe, expect, it } from 'vitest'
import type { BackupInventory, BackupInventoryBatch } from './backupInventory' import type { BackupInventory, BackupInventoryBatch } from './backupInventory'
import type { LibraryStorage } from './librarySnapshots'
import { import {
DISK_CRITICAL_AVAILABLE_PERCENT, DISK_CRITICAL_AVAILABLE_PERCENT,
batchOutcome, batchOutcome,
@@ -70,6 +69,7 @@ export const inventory = (overrides: Partial<BackupInventory> = {}): BackupInven
}, },
root: '/srv/kb-backups/rds-logical', root: '/srv/kb-backups/rds-logical',
host_root: '/srv/kb-backups/rds-logical', host_root: '/srv/kb-backups/rds-logical',
backup_root: '/srv/kb-backups',
source: 'host', source: 'host',
observed_at: '2026-11-24T10:18:00Z', observed_at: '2026-11-24T10:18:00Z',
measurement: 'host-reported', measurement: 'host-reported',
@@ -90,6 +90,18 @@ export const inventory = (overrides: Partial<BackupInventory> = {}): BackupInven
available_bytes: 1.2 * TB, available_bytes: 1.2 * TB,
used_bytes: 0.8 * TB, used_bytes: 0.8 * TB,
}, },
usage: {
root: '/srv/kb-backups',
measured: true,
complete: true,
actual_bytes: 22.65 * GIB,
apparent_bytes: 20 * GIB,
file_count: 1000,
dir_count: 40,
error: '',
},
quota_bytes: 50 * GIB,
quota_error: '',
batches: [batch()], batches: [batch()],
totals: { totals: {
batch_count: 1, batch_count: 1,
@@ -106,30 +118,6 @@ export const inventory = (overrides: Partial<BackupInventory> = {}): BackupInven
...overrides, ...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 => const unreported = (): BackupInventory =>
inventory({ inventory({
wired: false, wired: false,
@@ -151,6 +139,19 @@ const unreported = (): BackupInventory =>
}, },
root: '', root: '',
host_root: '', host_root: '',
backup_root: '',
usage: {
root: '',
measured: false,
complete: false,
actual_bytes: null,
apparent_bytes: null,
file_count: null,
dir_count: null,
error: '采集器未上报备份根占用(需要升级采集器)',
},
quota_bytes: null,
quota_error: '采集器未上报备份配额(需要升级采集器)',
capacity: { measured: false, total_bytes: 0, free_bytes: 0, available_bytes: 0, used_bytes: 0 }, capacity: { measured: false, total_bytes: 0, free_bytes: 0, available_bytes: 0, used_bytes: 0 },
batches: [], batches: [],
totals: { totals: {
@@ -230,48 +231,57 @@ describe('recentOutcome', () => {
}) })
describe('summaryCards', () => { describe('summaryCards', () => {
it('shows real values when the host reported and the archive is available', () => { it('shows real values from the host snapshot for backup occupancy and quota', () => {
const cards = summaryCards(inventory(), archive(), false) const cards = summaryCards(inventory())
const byKey = Object.fromEntries(cards.map((card) => [card.key, card.value])) const byKey = Object.fromEntries(cards.map((card) => [card.key, card.value]))
expect(byKey.root).toBe('/srv/kb-backups/rds-logical') expect(byKey.root).toBe('/srv/kb-backups/rds-logical')
expect(byKey.success).toBe(formatWhen('2026-11-24T02:00:00Z')) expect(byKey.success).toBe(formatWhen('2026-11-24T02:00:00Z'))
expect(byKey.failure).toBe('无') expect(byKey.failure).toBe('无')
expect(byKey.archive).toBe('38.4 GB') expect(byKey.backup).toBe(formatSize(22.65 * GIB))
expect(byKey.disk).toBe('1.2 TB') expect(byKey.disk).toBe('1.2 TB')
expect(cards.find((card) => card.key === 'archive')?.note).toBe('配额 100 GB') expect(cards.find((card) => card.key === 'backup')?.note).toBe('配额 50 GB')
expect(cards.some((card) => card.label === '归档占用')).toBe(false)
}) })
it('shows 主机未上报 with the last report time instead of 0 when the host never reported', () => { it('shows 主机未上报 with the last report time instead of 0 when the host never reported', () => {
const cards = summaryCards(unreported(), archive({ available: false }), false) const cards = summaryCards(unreported())
for (const key of ['root', 'success', 'failure', 'disk']) { for (const key of ['root', 'success', 'failure', 'backup', 'disk']) {
const card = cards.find((item) => item.key === key)! const card = cards.find((item) => item.key === key)!
expect(card.value).toBe('主机未上报') expect(card.value).toBe('主机未上报')
expect(card.note).toBe('上次上报 —') expect(card.note).toBe('上次上报 —')
} }
expect(cards.find((card) => card.key === 'archive')?.value).toBe('—')
expect(cards.some((card) => card.value === '0 B')).toBe(false) expect(cards.some((card) => card.value === '0 B')).toBe(false)
}) })
it('keeps paths readable but leaves sizes empty for an incomplete report', () => { it('keeps paths readable but leaves sizes empty for an incomplete report', () => {
const cards = summaryCards(inventory({ metadata: { ...inventory().metadata, complete: false } }), archive(), false) const cards = summaryCards(
inventory({
metadata: { ...inventory().metadata, complete: false },
usage: {
...inventory().usage,
measured: false,
complete: false,
actual_bytes: null,
error: '备份根占用未知:遍历失败',
},
})
)
expect(cards.find((card) => card.key === 'root')?.value).toBe('/srv/kb-backups/rds-logical') expect(cards.find((card) => card.key === 'root')?.value).toBe('/srv/kb-backups/rds-logical')
expect(cards.find((card) => card.key === 'backup')?.value).toBe('—')
expect(cards.find((card) => card.key === 'backup')?.note).toBe('备份根占用未知:遍历失败')
expect(cards.find((card) => card.key === 'disk')?.value).toBe('—') expect(cards.find((card) => card.key === 'disk')?.value).toBe('—')
expect(cards.find((card) => card.key === 'disk')?.note).toBe('本次上报不完整') expect(cards.find((card) => card.key === 'disk')?.note).toBe('本次上报不完整')
}) })
}) })
describe('storageAlerts', () => { describe('storageAlerts', () => {
it('judges disk and quota independently and counts pending rows', () => { it('judges disk and backup quota independently and counts pending rows', () => {
const healthy = storageAlerts(inventory(), archive(), false) const healthy = storageAlerts(inventory())
expect(healthy.map((row) => row.conclusion)).toEqual(['正常', '正常', '正常', '正常']) expect(healthy.map((row) => row.conclusion)).toEqual(['正常', '正常', '正常', '正常'])
expect(pendingAlertCount(healthy)).toBe(0) expect(pendingAlertCount(healthy)).toBe(0)
const nearQuota = storageAlerts( const nearQuota = storageAlerts(
inventory(), inventory({ usage: { ...inventory().usage, actual_bytes: 45 * GIB }, quota_bytes: 50 * GIB })
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 === 'quota_low')?.tone).toBe('warn')
expect(nearQuota.find((row) => row.key === 'both_low')?.conclusion).toBe('正常') expect(nearQuota.find((row) => row.key === 'both_low')?.conclusion).toBe('正常')
@@ -288,9 +298,9 @@ describe('storageAlerts', () => {
available_bytes: 0.01 * TB, available_bytes: 0.01 * TB,
used_bytes: 1.99 * TB, used_bytes: 1.99 * TB,
}, },
}), usage: { ...inventory().usage, actual_bytes: 100 * GIB },
archive({ capacity: { ...archive().capacity, current_bytes: 100 * GIB, budget_bytes: 100 * GIB } }), quota_bytes: 100 * GIB,
false })
) )
expect(tight.find((row) => row.key === 'disk_low')?.tone).toBe('bad') 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 === 'both_low')?.conclusion).toBe('需处理')
@@ -300,7 +310,7 @@ describe('storageAlerts', () => {
}) })
it('never claims a conclusion without numbers', () => { it('never claims a conclusion without numbers', () => {
const alerts = storageAlerts(unreported(), null, true) const alerts = storageAlerts(unreported())
expect(alerts.every((row) => row.conclusion === '未知')).toBe(true) expect(alerts.every((row) => row.conclusion === '未知')).toBe(true)
expect(alerts.find((row) => row.key === 'disk_low')?.value).toBe('主机未上报') expect(alerts.find((row) => row.key === 'disk_low')?.value).toBe('主机未上报')
expect(alerts.some((row) => row.value.includes('无法判定'))).toBe(false) expect(alerts.some((row) => row.value.includes('无法判定'))).toBe(false)
+43 -50
View File
@@ -1,9 +1,7 @@
// 「存储与备份」只读摘要的纯逻辑:数据源只有两个只读接口—— // 「存储与备份」只读摘要的纯逻辑:唯一数据源是宿主采集器快照
// /api/v1/backup-schedule/inventory (宿主每 5 分钟上报的元数据快照) // /api/v1/backup-schedule/inventory (批次、备份根占用、配额与文件系统容量)
// /api/v1/library/storage (归档库自身的占用与配额)
// 页面不提供任何写操作。读不到的量一律留空("主机未上报" / "—"),不用 0 冒充。 // 页面不提供任何写操作。读不到的量一律留空("主机未上报" / "—"),不用 0 冒充。
import type { BackupInventory, BackupInventoryBatch } from './backupInventory' import type { BackupInventory, BackupInventoryBatch } from './backupInventory'
import type { LibraryStorage } from './librarySnapshots'
// 阈值(与 docs/STORAGE_BACKUP_READONLY_API.md 的「页面口径」一致): // 阈值(与 docs/STORAGE_BACKUP_READONLY_API.md 的「页面口径」一致):
// 磁盘:可用空间 < 5% 红,< 10% 黄 // 磁盘:可用空间 < 5% 红,< 10% 黄
@@ -159,11 +157,7 @@ export interface SummaryCard {
const lastReportNote = (inventory: BackupInventory): string => const lastReportNote = (inventory: BackupInventory): string =>
`上次上报 ${formatWhen(inventory.metadata.collected_at) || UNKNOWN}` `上次上报 ${formatWhen(inventory.metadata.collected_at) || UNKNOWN}`
export function summaryCards( export function summaryCards(inventory: BackupInventory | null): SummaryCard[] {
inventory: BackupInventory | null,
archive: LibraryStorage | null,
archiveFailed: boolean
): SummaryCard[] {
const state = hostState(inventory) const state = hostState(inventory)
const facts = state === 'ready' || state === 'incomplete' const facts = state === 'ready' || state === 'incomplete'
const sizes = state === 'ready' const sizes = state === 'ready'
@@ -181,7 +175,20 @@ export function summaryCards(
const diskKnown = sizes && Boolean(capacity?.measured) && (capacity?.total_bytes ?? 0) > 0 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 availablePercent = diskKnown ? Math.round((capacity!.available_bytes / capacity!.total_bytes) * 100) : 0
const archiveKnown = Boolean(archive?.available) && !archiveFailed const usage = inventory?.usage
const usageKnown =
facts && Boolean(usage?.measured) && usage?.actual_bytes !== null && usage?.actual_bytes !== undefined
const quotaBytes = inventory?.quota_bytes
const quotaKnown = usageKnown && (quotaBytes ?? 0) > 0
const backupNote = !pending
? UNKNOWN
: !facts
? hostNote
: usageKnown
? quotaKnown
? `配额 ${formatSize(quotaBytes)}`
: inventory!.quota_error || '配额未上报'
: usage?.error || '本次上报不完整'
return [ return [
{ {
@@ -207,17 +214,11 @@ export function summaryCards(
unknown: !recent, unknown: !recent,
}, },
{ {
key: 'archive', key: 'backup',
label: '归档占用', label: '备份占用',
value: archiveKnown ? formatSize(archive!.capacity.current_bytes) : UNKNOWN, value: usageKnown ? formatSize(usage!.actual_bytes) : facts ? UNKNOWN : hostValue,
note: archiveFailed note: backupNote,
? '归档读取失败' unknown: !usageKnown,
: !archive || !archive.available
? '归档不可用'
: archive.capacity.configured
? `配额 ${formatSize(archive.capacity.budget_bytes)}`
: '配额未设置',
unknown: !archiveKnown,
}, },
{ {
key: 'disk', key: 'disk',
@@ -244,23 +245,21 @@ export interface SummaryAlert {
export interface StorageFacts { export interface StorageFacts {
diskAvailableBytes: number | null diskAvailableBytes: number | null
diskTotalBytes: number | null diskTotalBytes: number | null
archiveUsedBytes: number | null backupUsedBytes: number | null
archiveBudgetBytes: number | null backupQuotaBytes: number | null
} }
export function storageFacts( export function storageFacts(inventory: BackupInventory | null): StorageFacts {
inventory: BackupInventory | null,
archive: LibraryStorage | null,
archiveFailed: boolean
): StorageFacts {
const capacity = inventory?.capacity const capacity = inventory?.capacity
const diskKnown = hostState(inventory) === 'ready' && Boolean(capacity?.measured) && (capacity?.total_bytes ?? 0) > 0 const diskKnown = hostState(inventory) === 'ready' && Boolean(capacity?.measured) && (capacity?.total_bytes ?? 0) > 0
const archiveCapacity = archive?.available && !archiveFailed ? archive.capacity : null const usage = inventory?.usage
const used = usage?.measured && usage.actual_bytes !== null ? usage.actual_bytes : null
const quota = inventory?.quota_bytes ?? null
return { return {
diskAvailableBytes: diskKnown ? capacity!.available_bytes : null, diskAvailableBytes: diskKnown ? capacity!.available_bytes : null,
diskTotalBytes: diskKnown ? capacity!.total_bytes : null, diskTotalBytes: diskKnown ? capacity!.total_bytes : null,
archiveUsedBytes: archiveCapacity ? archiveCapacity.current_bytes : null, backupUsedBytes: used,
archiveBudgetBytes: archiveCapacity?.configured ? archiveCapacity.budget_bytes : null, backupQuotaBytes: quota !== null && quota > 0 ? quota : null,
} }
} }
@@ -270,13 +269,9 @@ const tonePercent = (value: number, warn: number, critical: number): Tone =>
const conclusionText = (tone: Tone): string => const conclusionText = (tone: Tone): string =>
tone === 'ok' ? '正常' : tone === 'warn' ? '注意' : tone === 'bad' ? '需处理' : UNKNOWN_STATE tone === 'ok' ? '正常' : tone === 'warn' ? '注意' : tone === 'bad' ? '需处理' : UNKNOWN_STATE
export function storageAlerts( export function storageAlerts(inventory: BackupInventory | null): SummaryAlert[] {
inventory: BackupInventory | null,
archive: LibraryStorage | null,
archiveFailed: boolean
): SummaryAlert[] {
const state = hostState(inventory) const state = hostState(inventory)
const facts = storageFacts(inventory, archive, archiveFailed) const facts = storageFacts(inventory)
const diskKnown = facts.diskAvailableBytes !== null && (facts.diskTotalBytes ?? 0) > 0 const diskKnown = facts.diskAvailableBytes !== null && (facts.diskTotalBytes ?? 0) > 0
const availablePercent = diskKnown ? Math.round((facts.diskAvailableBytes! / facts.diskTotalBytes!) * 100) : 0 const availablePercent = diskKnown ? Math.round((facts.diskAvailableBytes! / facts.diskTotalBytes!) * 100) : 0
const diskTone: Tone = diskKnown const diskTone: Tone = diskKnown
@@ -287,16 +282,16 @@ export function storageAlerts(
: 'ok' : 'ok'
: 'none' : 'none'
const quotaKnown = facts.archiveUsedBytes !== null && (facts.archiveBudgetBytes ?? 0) > 0 const quotaKnown = facts.backupUsedBytes !== null && (facts.backupQuotaBytes ?? 0) > 0
const usedPercent = quotaKnown ? Math.round((facts.archiveUsedBytes! / facts.archiveBudgetBytes!) * 100) : 0 const usedPercent = quotaKnown ? Math.round((facts.backupUsedBytes! / facts.backupQuotaBytes!) * 100) : 0
const quotaTone: Tone = quotaKnown const quotaTone: Tone = quotaKnown
? tonePercent(usedPercent, QUOTA_WARN_USED_PERCENT, QUOTA_CRITICAL_USED_PERCENT) ? tonePercent(usedPercent, QUOTA_WARN_USED_PERCENT, QUOTA_CRITICAL_USED_PERCENT)
: 'none' : 'none'
const bothTone: Tone = const bothTone: Tone =
diskTone === 'none' || quotaTone === 'none' ? 'none' : diskTone !== 'ok' && quotaTone !== 'ok' ? 'bad' : 'ok' diskTone === 'none' || quotaTone === 'none' ? 'none' : diskTone !== 'ok' && quotaTone !== 'ok' ? 'bad' : 'ok'
const overPhysical: Tone = const overPhysical: Tone =
diskKnown && facts.archiveBudgetBytes !== null diskKnown && facts.backupQuotaBytes !== null
? facts.archiveBudgetBytes > facts.diskAvailableBytes! ? facts.backupQuotaBytes > facts.diskAvailableBytes!
? 'bad' ? 'bad'
: 'ok' : 'ok'
: 'none' : 'none'
@@ -315,12 +310,10 @@ export function storageAlerts(
key: 'quota_low', key: 'quota_low',
label: '配额不足', label: '配额不足',
value: quotaKnown value: quotaKnown
? `${formatSize(facts.archiveUsedBytes)} / ${formatSize(facts.archiveBudgetBytes)}(${usedPercent}%)` ? `${formatSize(facts.backupUsedBytes)} / ${formatSize(facts.backupQuotaBytes)}(${usedPercent}%)`
: archiveFailed : inventory?.quota_error
? UNKNOWN ? '配额未上报'
: archive?.available : UNKNOWN,
? '配额未设置'
: UNKNOWN,
tone: quotaTone, tone: quotaTone,
conclusion: quotaKnown ? conclusionText(quotaTone) : UNKNOWN_STATE, conclusion: quotaKnown ? conclusionText(quotaTone) : UNKNOWN_STATE,
}, },
@@ -335,11 +328,11 @@ export function storageAlerts(
key: 'quota_over_physical', key: 'quota_over_physical',
label: '配额超出物理空闲', label: '配额超出物理空闲',
value: value:
diskKnown && facts.archiveBudgetBytes !== null diskKnown && facts.backupQuotaBytes !== null
? `配额 ${formatSize(facts.archiveBudgetBytes)} · 可用 ${formatSize(facts.diskAvailableBytes)}` ? `配额 ${formatSize(facts.backupQuotaBytes)} · 可用 ${formatSize(facts.diskAvailableBytes)}`
: UNKNOWN, : UNKNOWN,
tone: overPhysical, tone: overPhysical,
conclusion: diskKnown && facts.archiveBudgetBytes !== null ? conclusionText(overPhysical) : UNKNOWN_STATE, conclusion: diskKnown && facts.backupQuotaBytes !== null ? conclusionText(overPhysical) : UNKNOWN_STATE,
}, },
] ]
} }