Compare commits
12 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 6539a6b77c | |||
| 424a75d516 | |||
| 144b49cb53 | |||
| 65476750b0 | |||
| b59ec66387 | |||
| 7801c163e4 | |||
| 15dbc2469b | |||
| da568dfa2c | |||
| 7b4ec1f89d | |||
| 6a6fa7129a | |||
| c12152529c | |||
| 4d73aa999b |
@@ -80,3 +80,39 @@ jobs:
|
||||
KG_CD_SSH_HOST: ${{ vars.KG_CD_SSH_HOST }}
|
||||
KG_CD_SSH_PORT: ${{ vars.KG_CD_SSH_PORT }}
|
||||
run: python3 scripts/production_cd.py send --event "$GITHUB_EVENT_PATH"
|
||||
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 "上报结束(通知失败不改变发布结论)"
|
||||
|
||||
@@ -1,5 +1,50 @@
|
||||
# Changelog
|
||||
|
||||
## 开发快照 0.1.424(存储与备份:删批次前预检,失败零删除)
|
||||
|
||||
### Fixed
|
||||
|
||||
- **配额清理会把旧批次删一半再失败**:`shutil.rmtree` 先删子项、最后删目录,批次根只读时
|
||||
失败发生在内容已清空之后,调用方只看到非 0 退出却打印「旧备份未被删除」。现在删除分三段:
|
||||
逐目录可写性检查 + 同父目录改名探针(不动内容)→ 全部改名成 `.prune-<pid>-<戳>` 隔离
|
||||
(原子、不进批次候选)→ 才真删。任一预检或改名失败整体回滚、**零删除**(新退出码 `5`);
|
||||
真删阶段才失败时报隔离路径(`rc=4`),`logical-backup.sh` 按 `rc` 区分提示,不再误报。
|
||||
|
||||
### Changed
|
||||
|
||||
- 轮转(`KEEP_DAILY`/`KEEP_MONTHS`)改由 `scripts/prune_backup_batches.py --rotate` 实现,
|
||||
与配额清理共用同一套预检/隔离/回滚,删掉 `logical-backup.sh` 里的第二份内联 `rmtree`。
|
||||
self-test 增加预检零删除、改名失败回滚、只读批次根、轮转与遗留隔离目录用例。
|
||||
|
||||
## 开发快照 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
|
||||
|
||||
+1
-1
@@ -1978,7 +1978,7 @@
|
||||
"Settings"
|
||||
],
|
||||
"operationId": "getBackupScheduleInventory",
|
||||
"summary": "读取宿主元数据快照:批次、子库完整路径、实际占盘与文件系统容量(陈旧/不完整一律未知)",
|
||||
"summary": "读取宿主元数据快照:批次、子库完整路径、备份根累计占用、配额与文件系统容量(陈旧/不完整一律未知)",
|
||||
"responses": {
|
||||
"200": {
|
||||
"$ref": "#/components/responses/Envelope"
|
||||
|
||||
@@ -349,6 +349,7 @@ func run(ctx context.Context, getenv func(string) string) error {
|
||||
BackupInventory: backupinventory.New(backupinventory.Config{
|
||||
MetadataPath: config.BackupHostMetadataPath,
|
||||
HostRoot: config.BackupHostReadonlyHostPath,
|
||||
BackupRoot: config.BackupHostRoot,
|
||||
Source: backupInventorySource(config),
|
||||
MaxAge: config.BackupHostMetadataMaxAge,
|
||||
}),
|
||||
|
||||
@@ -34,6 +34,20 @@
|
||||
|
||||
执行 `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 和归档部署并回写。部署后回写失败时使用现有回执重试回写。
|
||||
|
||||
## 执行器配置
|
||||
|
||||
@@ -96,6 +96,25 @@ python3 scripts/restore_drill.py --snapshot-dir $KB_BACKUP_ROOT/target-kb-snapsh
|
||||
写操作按角色网关(`classifyRole`)限管理员——这份计划会落到数据面主机的 cron 上。
|
||||
- 主机侧:`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/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` 永不删。
|
||||
- **删除分三段(预检 → 改名隔离 → 真删)**:`rmtree` 会先删内容、最后删目录,父目录只读时
|
||||
失败发生在内容已清空之后,调用方只看得到非 0 退出。所以先逐目录检查可写性并对每个计划内
|
||||
批次做同父目录改名探针(只验证父目录可写,不动内容),再全部改名成 `.prune-<pid>-<戳>`
|
||||
(原子、不进批次候选),最后才真删。任一预检失败或改名失败 ⇒ **零删除**;真删阶段才失败时
|
||||
报隔离路径(`mv` 回原名即可恢复剩余内容)。
|
||||
- 轮转(`KEEP_DAILY`/`KEEP_MONTHS`)与配额清理走同一份实现(`--rotate`),不再有第二份内联
|
||||
`rmtree`。
|
||||
- 退出码:`0` 已满足(可能删过)、`2` du/路径错误、`3` 空间仍不够、`4` 真删阶段失败、
|
||||
`5` 预检未通过(零删除)。
|
||||
- 现场对账:`du -sB1 -- $KB_BACKUP_ROOT` 与页面「备份占用」应一致(≤1%);
|
||||
`bash scripts/install_backup_schedule.sh --show` 也会打印根占用/配额。
|
||||
- 凭据:容器内只读挂载 `secrets/backup-host/{ssh_config,id_ed25519,known_hosts}`(0600),
|
||||
环境变量 `BACKUP_HOST_SSH_CONFIG / BACKUP_HOST_TARGET / BACKUP_HOST_SCRIPT_DIR / BACKUP_HOST_ROOT`;
|
||||
**三项缺任一即"未接线"**,页面降级提示而不是报错。只读盘点另用宿主采集器
|
||||
|
||||
@@ -19,11 +19,15 @@
|
||||
```sh
|
||||
python3 collect_backup_metadata.py \
|
||||
--root /srv/kb-backups/rds-logical \
|
||||
--usage-root /srv/kb-backups \
|
||||
--output /var/lib/knowledge-governance/backup-metadata/metadata.json \
|
||||
--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`;
|
||||
**不打开任何 `.dat/.gz` 数据文件**。
|
||||
- 不跟随符号链接;`*.incomplete` 只计数不进入批次;单次最多 100 批(可调)。
|
||||
@@ -47,6 +51,8 @@ python3 collect_backup_metadata.py \
|
||||
```
|
||||
|
||||
目录 `0755`、文件 `0644`,只包含路径/清单摘要/计数,不含数据库内容。
|
||||
采集器自己读 `/etc/knowledge-governance/backup.env` 拿 `KB_BACKUP_ROOT`/`KB_BACKUP_QUOTA_BYTES`,
|
||||
所以配额调整不需要改 cron;只想临时覆盖时再加 `--usage-root`/`--quota-bytes`。
|
||||
|
||||
### 快照 schema(version 1)
|
||||
|
||||
@@ -58,6 +64,10 @@ python3 collect_backup_metadata.py \
|
||||
| `collected_at` | UTC RFC3339;超过 `BACKUP_HOST_METADATA_MAX_AGE` 即陈旧 |
|
||||
| `generation` | 每次采集唯一 ID,便于核对读到的是哪一次原子快照 |
|
||||
| `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 |
|
||||
| `filesystem` | `mount_point/mount_source/fs_type/read_only/total/free/available` |
|
||||
| `batches[].complete` | 该批遍历完整;false 时字节必须为 null |
|
||||
@@ -87,8 +97,16 @@ python3 collect_backup_metadata.py \
|
||||
},
|
||||
"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",
|
||||
"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_verified": true, "read_only": false,
|
||||
"mount_point": "/srv/kb-backups", "device": "/dev/sdb1", "fs_type": "ext4",
|
||||
@@ -135,8 +153,11 @@ python3 collect_backup_metadata.py \
|
||||
| `wired=false` | `metadata.error=未接线`,批次空 | 显示未接线与安装方式,不显示空表当“没备份” |
|
||||
| 快照文件缺失/不可读 | `present=false`、`valid=false` | 显示缺失;不使用 SSH 最近一次补历史 |
|
||||
| `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`,整块拒绝 | 显示校验失败,不展示可疑路径 |
|
||||
|
||||
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`。
|
||||
- 最近批 `databases` 含 `weknora_v090prod`、`present=true`,`host_path` 指向
|
||||
`/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. 还需单独确认的后端写能力
|
||||
|
||||
1. 配额 / 磁盘预留的持久化与执行(当前无字段)。
|
||||
1. 配额 / 磁盘预留的持久化:配额已按部署配置(`backup.env`)执行并上报;**平台页面编辑/下发**仍未实现(需 DB 字段与写接口)。
|
||||
2. 旧批次保留/删除与删除前审计、可恢复窗口。
|
||||
3. 备份目录迁移/切换。
|
||||
4. 单库备份/单库恢复(现有 run 是整批)。
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -31,6 +31,9 @@ type Config struct {
|
||||
MetadataPath string
|
||||
// HostRoot 是宿主上的 rds-logical 绝对路径,用于校验快照里的 root/批次路径。
|
||||
HostRoot string
|
||||
// BackupRoot 是宿主上的备份根(KB_BACKUP_ROOT),用于校验快照里的根占用范围。
|
||||
// 它必须与 BACKUP_HOST_ROOT 同源;不同源时占用不可信,整份快照拒绝。
|
||||
BackupRoot string
|
||||
// Source 是展示来源;快照里的 source 非空时以快照为准。
|
||||
Source string
|
||||
// MaxAge 超过即视为陈旧,旧快照的批次与容量一律不使用。
|
||||
@@ -85,6 +88,19 @@ type Capacity struct {
|
||||
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 {
|
||||
Name string `json:"name"`
|
||||
DirName string `json:"dir_name"`
|
||||
@@ -138,12 +154,16 @@ type Snapshot struct {
|
||||
Metadata MetadataInfo `json:"metadata"`
|
||||
Root string `json:"root"`
|
||||
HostRoot string `json:"host_root"`
|
||||
BackupRoot string `json:"backup_root"`
|
||||
Source string `json:"source"`
|
||||
ObservedAt string `json:"observed_at"`
|
||||
Error string `json:"error,omitempty"`
|
||||
Measurement string `json:"measurement"`
|
||||
Mount MountInfo `json:"mount"`
|
||||
Capacity Capacity `json:"capacity"`
|
||||
Usage Usage `json:"usage"`
|
||||
QuotaBytes *int64 `json:"quota_bytes"`
|
||||
QuotaError string `json:"quota_error,omitempty"`
|
||||
Batches []Batch `json:"batches"`
|
||||
Totals Totals `json:"totals"`
|
||||
IncompleteCount int `json:"incomplete_count"`
|
||||
@@ -181,6 +201,10 @@ type metadata struct {
|
||||
Host string `json:"host"`
|
||||
Source string `json:"source"`
|
||||
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"`
|
||||
Errors []string `json:"errors"`
|
||||
Filesystem metadataFilesystem `json:"filesystem"`
|
||||
@@ -190,6 +214,16 @@ type metadata struct {
|
||||
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 {
|
||||
MountPoint string `json:"mount_point"`
|
||||
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))
|
||||
}
|
||||
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 {
|
||||
return invalid(snapshot, err.Error())
|
||||
}
|
||||
@@ -366,6 +408,66 @@ func (r *Reader) observedAt() string {
|
||||
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 {
|
||||
snapshot.Metadata.Valid = false
|
||||
snapshot.Metadata.Complete = false
|
||||
@@ -374,6 +476,8 @@ func invalid(snapshot Snapshot, reason string) Snapshot {
|
||||
snapshot.Batches = []Batch{}
|
||||
snapshot.Capacity = Capacity{Error: reason}
|
||||
snapshot.Totals = Totals{}
|
||||
snapshot.Usage = Usage{Error: reason}
|
||||
snapshot.QuotaBytes = nil
|
||||
return snapshot
|
||||
}
|
||||
|
||||
|
||||
@@ -28,8 +28,14 @@ func validMetadata() metadata {
|
||||
Host: "weknora-test",
|
||||
Source: "weknora-test:" + hostRoot,
|
||||
Root: hostRoot,
|
||||
Complete: true,
|
||||
Errors: []string{},
|
||||
BackupRoot: "/srv/kb-backups",
|
||||
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{
|
||||
MountPoint: "/srv/kb-backups",
|
||||
MountSource: "/dev/sdb1",
|
||||
@@ -108,7 +114,7 @@ func writeMetadata(t *testing.T, value metadata) string {
|
||||
}
|
||||
|
||||
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 }
|
||||
return reader
|
||||
}
|
||||
@@ -156,7 +162,82 @@ func TestSnapshotReadsHostMetadataAndPaths(t *testing.T) {
|
||||
t.Fatalf("汇总不对: %+v", snapshot.Totals)
|
||||
}
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -24,11 +24,16 @@ func TestBackupInventoryProjectionPassesRealFields(t *testing.T) {
|
||||
actual := int64(1024)
|
||||
databaseActual := int64(512)
|
||||
config := Config{BackupInventory: fakeBackupInventory{snapshot: backupinventory.Snapshot{
|
||||
Wired: true,
|
||||
Root: "/srv/kb-backups/rds-logical",
|
||||
HostRoot: "/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},
|
||||
Wired: true,
|
||||
Root: "/srv/kb-backups/rds-logical",
|
||||
HostRoot: "/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},
|
||||
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{
|
||||
MountVerified: 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 {
|
||||
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) {
|
||||
|
||||
@@ -22,10 +22,22 @@ set -euo pipefail
|
||||
KB_BACKUP_ROOT="${KB_BACKUP_ROOT:-/srv/kb-backups}"
|
||||
CONFIG_FILE="${CONFIG_FILE:-/etc/knowledge-governance/backup.env}"
|
||||
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
|
||||
[ "${1:-}" = "--print" ] && PRINT_ONLY=1
|
||||
|
||||
echo "备份根目录: $KB_BACKUP_ROOT"
|
||||
echo "备份配额 : $QUOTA_BYTES 字节"
|
||||
echo "配置文件 : $CONFIG_FILE"
|
||||
echo "子目录 :"
|
||||
total_bytes=0
|
||||
@@ -52,6 +64,8 @@ mkdir -p "$(dirname "$CONFIG_FILE")"
|
||||
cat >"$CONFIG_FILE" <<EOF
|
||||
# 由 scripts/backup_layout.sh 生成:备份目录契约(换主机时只改这里)
|
||||
KB_BACKUP_ROOT=$KB_BACKUP_ROOT
|
||||
# 备份根累计占用硬上限(字节):采集器上报、logical-backup.sh 执行同一条线。
|
||||
KB_BACKUP_QUOTA_BYTES=$QUOTA_BYTES
|
||||
EOF
|
||||
echo "已写入 $CONFIG_FILE"
|
||||
echo
|
||||
|
||||
@@ -8,6 +8,7 @@ import re
|
||||
import sys
|
||||
from urllib.error import HTTPError
|
||||
|
||||
import qa_report
|
||||
import candidate_release as candidate
|
||||
import candidate_runtime as runtime
|
||||
import hifox_release_trigger as hfx
|
||||
@@ -118,6 +119,8 @@ def publish_candidate(plan, receipt, run):
|
||||
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']
|
||||
add_comment(plan['task'], key, body)
|
||||
for item in plan['items']:
|
||||
@@ -161,6 +164,27 @@ def summon_qa(plan, target, body):
|
||||
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):
|
||||
plan = owner_plan(task_id)
|
||||
directory = STATE / cd.acceptance_digest(plan)
|
||||
@@ -185,6 +209,13 @@ def register(task_id):
|
||||
row = reports[item_id][0]
|
||||
cd.require(cd.matches(cd.UUID, row.get('id')) and obj.get('url', '').startswith('https://app.hifox.com/'),
|
||||
'invalid QA evidence link')
|
||||
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)
|
||||
fresh = owner_plan(task_id)
|
||||
cd.require(fresh == plan, 'release plan changed during registration')
|
||||
@@ -193,7 +224,7 @@ def register(task_id):
|
||||
'register QA before the owner moves the release task to 待发布')
|
||||
sha, bundle = receipt['sha'], receipt['bundle']
|
||||
links = '\n'.join(f'- {task(item)["url"]}#comment-{reports[item][0]["id"]}' for item in tasks)
|
||||
body = f'批次验收通过\n\n提交 `{sha}`\n\n归档 `{bundle}`\n\n需求验收与批次回归报告\n{links}'
|
||||
body = acceptance_body(sha, bundle, tasks, reports, lambda item: task(item)['url'], links)
|
||||
comment = add_comment(task_id, 'acceptance ' + bundle, body)
|
||||
acceptance = {'verdict': 'passed', 'sha': sha, 'bundle': bundle, 'evidence': rel['url'] + '#comment-' + comment}
|
||||
if cd.metadata(task(task_id), 'cd_acceptance') != acceptance:
|
||||
|
||||
@@ -15,6 +15,8 @@ from urllib.parse import quote
|
||||
import production_cd as cd
|
||||
import qa_env
|
||||
|
||||
STATE = Path.home() / '.local/state/kg-candidate-release'
|
||||
|
||||
|
||||
def isolated_subnet(exclude=()):
|
||||
nets = cd.run(['docker', 'network', 'ls', '-q'], 'list Docker networks').decode().split()
|
||||
@@ -55,6 +57,23 @@ def qa_process_command(role):
|
||||
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):
|
||||
bundle = bundle.resolve()
|
||||
manifest = cd.read_json(bundle / 'release.json')
|
||||
@@ -88,6 +107,9 @@ def ready(directory, bundle, test_database=None):
|
||||
url, cert = qa_database(test_database)
|
||||
env['DATA' + 'BASE_URL'] = url
|
||||
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'
|
||||
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}
|
||||
@@ -96,10 +118,12 @@ def ready(directory, bundle, test_database=None):
|
||||
cd.verify_archive(archive, item['id'])
|
||||
cd.run(['docker', 'load', '-i', str(archive)], 'load sealed candidate image', timeout=150)
|
||||
services[role] = {'image': item['id'], 'container_name': names[role]}
|
||||
key = qa_binding_key(manifest['images']['api']['id']) if test_database is not None else None
|
||||
for role in ('api', 'worker'):
|
||||
services[role]['env_file'] = [str(app_env)]
|
||||
if test_database is not None:
|
||||
services[role]['volumes'] = [f'{directory / "rds-ca.pem"}:/run/qa/rds-ca.pem:ro']
|
||||
services[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'],
|
||||
'interval': '2s', 'timeout': '3s', 'retries': 45}
|
||||
if test_database is None:
|
||||
|
||||
@@ -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())
|
||||
@@ -37,12 +37,71 @@ COLLECTOR_VERSION = "backup-metadata/1"
|
||||
MAX_MANIFEST_BYTES = 8 << 20
|
||||
MAX_ERRORS = 50
|
||||
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):
|
||||
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:
|
||||
if isinstance(error, OSError) and 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(
|
||||
root: str,
|
||||
source: str = "",
|
||||
@@ -219,8 +300,12 @@ def collect(
|
||||
max_batches: int = 100,
|
||||
scan: Callable[[str], Iterable[Any]] = os.scandir,
|
||||
now: dt.datetime | None = None,
|
||||
backup_root: str = "",
|
||||
quota_bytes: int | None = None,
|
||||
quota_error: str = "",
|
||||
) -> dict[str, Any]:
|
||||
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)
|
||||
snapshot: dict[str, Any] = {
|
||||
"schema_version": SCHEMA_VERSION,
|
||||
@@ -230,6 +315,10 @@ def collect(
|
||||
"host": host or socket.gethostname(),
|
||||
"source": source,
|
||||
"root": root,
|
||||
"backup_root": backup_root,
|
||||
"usage": {},
|
||||
"quota_bytes": quota_bytes,
|
||||
"quota_error": quota_error,
|
||||
"complete": True,
|
||||
"errors": [],
|
||||
"filesystem": {},
|
||||
@@ -239,6 +328,9 @@ def collect(
|
||||
"batches": [],
|
||||
}
|
||||
errors: list[str] = snapshot["errors"]
|
||||
# 根占用与批次完整性**分开**:某个保护目录读不到时,占用可以说「未知」,
|
||||
# 但批次表/磁盘容量仍然有效;把两者绑在一起会把「占用未知」扩大成「全部未知」。
|
||||
snapshot["usage"] = project_usage(backup_root, measure_tree(backup_root, scan))
|
||||
try:
|
||||
if not os.path.isdir(root):
|
||||
raise CollectError(f"备份根不是目录:{root}")
|
||||
@@ -529,6 +621,61 @@ def _self_test() -> None:
|
||||
assert ignored["incomplete_count"] == 1
|
||||
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")
|
||||
write_snapshot(output, ignored)
|
||||
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("--host", default="", help="采集主机名(默认当前主机)")
|
||||
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")
|
||||
args = parser.parse_args(argv)
|
||||
if args.self_test:
|
||||
@@ -556,11 +706,17 @@ def main(argv: list[str] | None = None) -> int:
|
||||
if not args.root or not args.output:
|
||||
parser.error("--root and --output are required unless --self-test")
|
||||
try:
|
||||
backup_root, quota_bytes, quota_error = resolve_backup_settings(
|
||||
args.root, args.usage_root or None, args.quota_bytes, args.config
|
||||
)
|
||||
snapshot = collect(
|
||||
args.root,
|
||||
source=args.source,
|
||||
host=args.host or None,
|
||||
max_batches=max(1, args.max_batches),
|
||||
backup_root=backup_root,
|
||||
quota_bytes=quota_bytes,
|
||||
quota_error=quota_error,
|
||||
)
|
||||
write_snapshot(args.output, snapshot)
|
||||
except (CollectError, OSError) as error:
|
||||
@@ -570,11 +726,17 @@ def main(argv: list[str] | None = None) -> int:
|
||||
"complete": snapshot["complete"],
|
||||
"batches": len(snapshot["batches"]),
|
||||
"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"],
|
||||
"output": args.output,
|
||||
}
|
||||
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__":
|
||||
|
||||
@@ -54,7 +54,10 @@ show_state() {
|
||||
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)"
|
||||
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
|
||||
|
||||
+71
-23
@@ -21,6 +21,7 @@
|
||||
# JOBS 并行度(默认 4)
|
||||
# KEEP_DAILY 保留最近几份每日备份(默认 7)
|
||||
# KEEP_MONTHS 额外保留最近几个自然月各一份(默认 3)
|
||||
# KB_BACKUP_QUOTA_BYTES 备份根累计占用硬上限(默认 53687091200 = 50 GiB,来自 backup.env)
|
||||
# EXCLUDE_DBS 逗号分隔的跳过列表(默认 rdsadmin:RDS 管理库,普通账号导不出来)
|
||||
set -euo pipefail
|
||||
|
||||
@@ -31,7 +32,28 @@ if [ -z "${KB_BACKUP_ROOT:-}" ] && [ -f /etc/knowledge-governance/backup.env ];
|
||||
. /etc/knowledge-governance/backup.env
|
||||
fi
|
||||
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}"
|
||||
# 配额约束的是备份根(含 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}"
|
||||
PG_IMAGE="${PG_IMAGE:-postgres:17.9-alpine}"
|
||||
JOBS="${JOBS:-4}"
|
||||
@@ -49,6 +71,26 @@ DRY_RUN="${DRY_RUN:-0}"
|
||||
DBS="${DBS:-}"
|
||||
EXCLUDE_DBS="${EXCLUDE_DBS:-rdsadmin}"
|
||||
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() {
|
||||
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
|
||||
if [ -z "$DBS" ]; then echo "没有可备份的库" >&2; exit 1; fi
|
||||
|
||||
TARGET="$BACKUP_ROOT/$STAMP"
|
||||
|
||||
# 失败或被中断(含被 head/管道 SIGPIPE 杀掉):把目录显式标记为半成品,
|
||||
# 这样"最近一次备份"的选择器与人都不会把它误当成功结果。
|
||||
mark_incomplete() {
|
||||
@@ -97,7 +137,18 @@ echo "备份目标: $TARGET"
|
||||
echo "库列表 : $DBS"
|
||||
echo "镜像 : $PG_IMAGE (并行 $JOBS)"
|
||||
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=$?
|
||||
# rc=4 说明批次已改名隔离、真删阶段才失败,内容可能被部分删除 —— 不能再说「旧备份未被删除」。
|
||||
case "$rc" in
|
||||
4) echo "配额预检的删除阶段失败(rc=4):已隔离的批次可能已被部分删除(见上面的隔离路径),本次备份取消" >&2 ;;
|
||||
*) echo "配额预检未通过(rc=$rc):本次备份取消,旧备份未被删除" >&2 ;;
|
||||
esac
|
||||
exit "$rc"
|
||||
fi
|
||||
|
||||
mkdir -p "$TARGET"
|
||||
STARTED_AT="$(date -u +%Y-%m-%dT%H:%M:%SZ)"
|
||||
@@ -194,26 +245,23 @@ docker run --rm -v "$PWD:/backup" postgres:17.9-alpine \
|
||||
- 这份备份**不能替代按时间点恢复(PITR)**:它只能回到"备份那一刻"。
|
||||
MD
|
||||
|
||||
# 轮转:保留最近 KEEP_DAILY 份,另在最近 KEEP_MONTHS 个自然月各留一份
|
||||
python3 - "$BACKUP_ROOT" "$KEEP_DAILY" "$KEEP_MONTHS" <<'PY'
|
||||
import pathlib, re, shutil, sys
|
||||
root = pathlib.Path(sys.argv[1]); keep_daily = int(sys.argv[2]); keep_months = int(sys.argv[3])
|
||||
stamps = sorted([p for p in root.iterdir() if p.is_dir() and re.fullmatch(r"\d{8}T\d{6}Z", p.name)], reverse=True)
|
||||
keep = {p.name for p in stamps[:keep_daily]}
|
||||
months = []
|
||||
for path in stamps:
|
||||
month = path.name[:6]
|
||||
if month not in months:
|
||||
months.append(month)
|
||||
keep.add(path.name)
|
||||
if len(months) >= keep_months:
|
||||
break
|
||||
for path in stamps:
|
||||
if path.name not in keep:
|
||||
shutil.rmtree(path)
|
||||
print("rotated out:", path.name)
|
||||
print("kept:", len([p for p in stamps if p.name in keep]))
|
||||
PY
|
||||
# 轮转:保留最近 KEEP_DAILY 份,另在最近 KEEP_MONTHS 个自然月各留一份。
|
||||
# 与配额清理共用同一份实现:删除前的 rename 预检、失败零删除回滚、只认完整批次,
|
||||
# 避免这里的内联 rmtree 又变成「先清空内容、再删目录失败」的第二条路径。
|
||||
python3 "$PRUNE_TOOL" \
|
||||
--backup-root "$QUOTA_ROOT" \
|
||||
--batch-root "$BACKUP_ROOT" \
|
||||
--rotate --keep-daily "$KEEP_DAILY" --keep-months "$KEEP_MONTHS" --apply
|
||||
|
||||
# dump 后按实际占用复查:保护本次新批次,旧批次可删;仍超限则保留数据并告警。
|
||||
if run_quota_prune "dump 后复查" --estimate none --protect "$STAMP" --apply; then :; else
|
||||
rc=$?
|
||||
case "$rc" in
|
||||
4) echo "本次备份已完成,但删除阶段失败(rc=4):见上面的隔离路径;新批次保留" >&2 ;;
|
||||
*) echo "本次备份已完成,但配额仍超出(rc=$rc):新批次保留,请扩容或人工清理" >&2 ;;
|
||||
esac
|
||||
exit "$rc"
|
||||
fi
|
||||
|
||||
if [ -n "$FAILED_DBS" ]; then
|
||||
echo "done(有失败的库): $TARGET | failed: $FAILED_DBS" >&2
|
||||
|
||||
Executable
+683
@@ -0,0 +1,683 @@
|
||||
#!/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
|
||||
|
||||
删除为什么要分「预检 → 同父目录改名隔离 → 真删」三段:`shutil.rmtree` 先删子项、最后删
|
||||
目录,父目录只读时失败发生在内容**已经清空之后**,调用方只看得到 rc≠0,旧备份却已经毁了
|
||||
一半。rename 只要求父目录可写,能在删掉任何一个字节之前暴露这类问题;改名是原子的,任一
|
||||
批次改名失败就把已挪动的批次全部挪回去,保证「失败 ⇒ 零删除」。
|
||||
|
||||
退出码:0 已满足配额(可能删了旧批次);2 du/路径错误,未删除;3 空间仍不够,未删除;
|
||||
4 删除阶段失败(已隔离的批次可能被部分删除,报错退出并给出隔离路径);
|
||||
5 删除前预检未通过,**零删除**。
|
||||
"""
|
||||
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$")
|
||||
# 隔离名不以 UTC 戳开头,因此不会被 candidates() 认成批次;同父目录下改名是原子操作。
|
||||
QUARANTINE_PREFIX = ".prune-"
|
||||
|
||||
|
||||
class QuotaError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class PrecheckRefused(QuotaError):
|
||||
"""删除前预检未通过:一个字节都没删。"""
|
||||
|
||||
|
||||
class DeleteFailed(QuotaError):
|
||||
"""配额已提交(批次已改名隔离),但真删阶段失败:可能已有内容被删。"""
|
||||
|
||||
|
||||
@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 _tree_problems(path: str) -> list[str]:
|
||||
"""列出会让 `rmtree` 中途失败的目录(只读、不可执行、挂载点)。
|
||||
|
||||
删一个子项要求它的**父目录**可写可执行,而不是文件本身;所以只看目录。挂载点要单独拒:
|
||||
rmtree 会顺着删到另一个文件系统里去。
|
||||
"""
|
||||
problems: list[str] = []
|
||||
if os.path.ismount(path):
|
||||
return [f"{path} 是挂载点,拒绝删除"]
|
||||
if not os.access(path, os.W_OK | os.X_OK):
|
||||
return [f"{path} 不可写(rmtree 会先删完内容再删目录失败)"]
|
||||
for current, _dirs, _files in os.walk(path, onerror=lambda err: problems.append(str(err))):
|
||||
if os.path.ismount(current):
|
||||
problems.append(f"{current} 是挂载点,拒绝删除")
|
||||
elif not os.access(current, os.W_OK | os.X_OK):
|
||||
problems.append(f"{current} 不可写")
|
||||
return problems
|
||||
|
||||
|
||||
def _rename_probe(path: str) -> None:
|
||||
"""在同一个父目录里把批次改名再改回:验证「父目录可写」而不动任何内容。"""
|
||||
batch_root = os.path.dirname(path)
|
||||
probe = os.path.join(batch_root, f"{QUARANTINE_PREFIX}probe-{os.getpid()}-{os.path.basename(path)}")
|
||||
os.rename(path, probe)
|
||||
try:
|
||||
os.rename(probe, path)
|
||||
except OSError as error:
|
||||
raise QuotaError(
|
||||
f"批次 {os.path.basename(path)} 已改名为 {probe} 且改回失败(内容未删);"
|
||||
f"请人工 mv 回原名:{error}"
|
||||
) from error
|
||||
|
||||
|
||||
def delete_batches(
|
||||
batch_root: str,
|
||||
planned: list[Candidate],
|
||||
tree_check=_tree_problems,
|
||||
probe=_rename_probe,
|
||||
rename=os.rename,
|
||||
) -> list[str]:
|
||||
"""预检通过才删;返回真正删掉的批次名。
|
||||
|
||||
预检覆盖两类失败:批次根不可写(改名探针)与批次内部有不可删目录(逐目录检查)。
|
||||
提交点是「全部改名成功」——之后才真删,所以中途失败不会出现「一半删掉、一半还在」
|
||||
的可见状态;改名失败则整体回滚,零删除。
|
||||
"""
|
||||
if not planned:
|
||||
return []
|
||||
problems: list[str] = []
|
||||
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}")
|
||||
problems.extend(tree_check(target))
|
||||
if not problems:
|
||||
for item in planned:
|
||||
try:
|
||||
probe(item.path)
|
||||
except OSError as error:
|
||||
problems.append(
|
||||
f"{item.path}: 无法在批次根内改名(父目录不可写?未删除任何内容):"
|
||||
f"{error.strerror or error}"
|
||||
)
|
||||
break
|
||||
if problems:
|
||||
raise PrecheckRefused("删除前预检未通过,未删除任何批次:" + ";".join(problems))
|
||||
|
||||
quarantined: list[tuple[Candidate, str]] = []
|
||||
try:
|
||||
for item in planned:
|
||||
target = os.path.join(batch_root, f"{QUARANTINE_PREFIX}{os.getpid()}-{item.name}")
|
||||
if os.path.lexists(target):
|
||||
raise OSError(f"隔离路径已存在:{target}")
|
||||
rename(item.path, target)
|
||||
quarantined.append((item, target))
|
||||
except OSError as error:
|
||||
for item, target in reversed(quarantined):
|
||||
try:
|
||||
rename(target, item.path)
|
||||
except OSError as undo_error:
|
||||
raise DeleteFailed(
|
||||
f"回滚失败:批次 {item.name} 停在 {target}(内容未删);请人工 mv 回原名:{undo_error}"
|
||||
) from error
|
||||
raise PrecheckRefused(
|
||||
f"隔离改名失败({error}),已把 {[item.name for item, _ in quarantined]} 改回原名,未删除任何批次"
|
||||
) from error
|
||||
|
||||
deleted: list[str] = []
|
||||
failures: list[str] = []
|
||||
for item, target in quarantined:
|
||||
try:
|
||||
shutil.rmtree(target)
|
||||
except OSError as error:
|
||||
failures.append(f"{item.name}(隔离在 {target},内容可能已被部分删除):{error}")
|
||||
continue
|
||||
deleted.append(item.name)
|
||||
if failures:
|
||||
raise DeleteFailed("删除阶段失败:" + ";".join(failures))
|
||||
return deleted
|
||||
|
||||
|
||||
def plan_rotation(
|
||||
candidates_oldest_first: list[Candidate], keep_daily: int, keep_months: int
|
||||
) -> list[Candidate]:
|
||||
"""保留最近 keep_daily 份 + 最近 keep_months 个自然月各一份,其余待删。"""
|
||||
newest_first = list(reversed(candidates_oldest_first))
|
||||
keep = {item.name for item in newest_first[: max(keep_daily, 0)]}
|
||||
months: list[str] = []
|
||||
for item in newest_first:
|
||||
month = item.name[:6]
|
||||
if month not in months:
|
||||
months.append(month)
|
||||
keep.add(item.name)
|
||||
if len(months) >= keep_months:
|
||||
break
|
||||
return [item for item in candidates_oldest_first if item.name not in keep]
|
||||
|
||||
|
||||
def stale_quarantine(batch_root: str) -> list[str]:
|
||||
"""上次删到一半留下的隔离目录:不认成批次,但要报出来让人决定恢复还是清掉。"""
|
||||
try:
|
||||
entries = list(os.scandir(batch_root))
|
||||
except OSError:
|
||||
return []
|
||||
return sorted(
|
||||
entry.name
|
||||
for entry in entries
|
||||
if entry.name.startswith(QUARANTINE_PREFIX) and entry.is_dir(follow_symlinks=False)
|
||||
)
|
||||
|
||||
|
||||
def rotate(
|
||||
backup_root: str,
|
||||
batch_root: str,
|
||||
keep_daily: int,
|
||||
keep_months: int,
|
||||
apply: bool,
|
||||
measure_bytes=measure,
|
||||
) -> dict:
|
||||
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)
|
||||
planned = plan_rotation(found, keep_daily, keep_months)
|
||||
result = {
|
||||
"mode": "rotate",
|
||||
"backup_root": backup_root,
|
||||
"batch_root": batch_root,
|
||||
"keep_daily": keep_daily,
|
||||
"keep_months": keep_months,
|
||||
"kept": len(found) - len(planned),
|
||||
"plan": [item.name for item in planned],
|
||||
"deleted": [],
|
||||
"stale_quarantine": stale_quarantine(batch_root),
|
||||
"applied": False,
|
||||
}
|
||||
if apply:
|
||||
result["deleted"] = delete_batches(batch_root, planned)
|
||||
result["applied"] = True
|
||||
return result
|
||||
|
||||
|
||||
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,
|
||||
"deleted": [],
|
||||
"stale_quarantine": stale_quarantine(batch_root),
|
||||
"applied": False,
|
||||
}
|
||||
if insufficient:
|
||||
return result
|
||||
if not apply:
|
||||
return result
|
||||
result["deleted"] = delete_batches(batch_root, planned)
|
||||
result["applied"] = True
|
||||
result["usage_after_bytes"] = measure_bytes(backup_root)
|
||||
return result
|
||||
|
||||
|
||||
def _self_test_quota() -> 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 _self_test_delete_safety() -> None:
|
||||
"""删除安全网:预检拒绝零删除、改名失败整体回滚、轮转、隔离目录不进候选。"""
|
||||
import contextlib
|
||||
import io
|
||||
|
||||
base = tempfile.mkdtemp(prefix="backup-quota-delete-test-")
|
||||
try:
|
||||
root = os.path.join(base, "kb-backups")
|
||||
batch_root = os.path.join(root, "rds-logical")
|
||||
os.makedirs(batch_root)
|
||||
|
||||
def make_batch(stamp: str, kib: int) -> str:
|
||||
path = os.path.join(batch_root, stamp)
|
||||
os.makedirs(os.path.join(path, "weknora.dir"))
|
||||
with open(os.path.join(path, "weknora.dir", "180000.dat.gz"), "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 = ["20261201T030000Z", "20261215T030000Z", "20270101T030000Z", "20270115T030000Z"]
|
||||
paths = [make_batch(stamp, 128) for stamp in stamps]
|
||||
found = candidates(batch_root)
|
||||
|
||||
def sizes() -> dict[str, int]:
|
||||
return {path: measure(path) for path in paths}
|
||||
|
||||
before = sizes()
|
||||
# 1) 预检报告问题时一个都不删(旧实现会先 rmtree 掉第一批再失败)。
|
||||
for inject in ({"tree_check": lambda _path: ["注入:目录不可写"]},
|
||||
{"probe": _refuse_probe}):
|
||||
try:
|
||||
delete_batches(batch_root, found[:2], **inject)
|
||||
except PrecheckRefused:
|
||||
pass
|
||||
else:
|
||||
raise AssertionError("预检拒绝时不得删除")
|
||||
assert sizes() == before, (inject, sizes())
|
||||
assert all(os.path.exists(path) for path in paths)
|
||||
|
||||
# 2) 改名提交阶段失败:已挪动的批次必须改回原名,零删除。
|
||||
calls = {"n": 0}
|
||||
real_rename = os.rename
|
||||
|
||||
def flaky_rename(src, dst):
|
||||
calls["n"] += 1
|
||||
if calls["n"] == 2:
|
||||
raise OSError("注入:改名失败")
|
||||
return real_rename(src, dst)
|
||||
|
||||
try:
|
||||
delete_batches(batch_root, found[:2], rename=flaky_rename)
|
||||
except PrecheckRefused:
|
||||
pass
|
||||
else:
|
||||
raise AssertionError("改名失败必须整体回滚")
|
||||
assert sorted(os.listdir(batch_root)) == stamps, os.listdir(batch_root)
|
||||
assert sizes() == before
|
||||
|
||||
# 3) 真删只在预检通过后发生,并且只删计划内批次。
|
||||
deleted = delete_batches(batch_root, found[:2])
|
||||
assert deleted == [stamps[0], stamps[1]], deleted
|
||||
assert sorted(os.listdir(batch_root)) == stamps[2:], os.listdir(batch_root)
|
||||
assert os.path.isdir(paths[2]) and os.path.isdir(paths[3])
|
||||
|
||||
# 4) 只读批次根(root 下 os.access 恒为真,跳过)。
|
||||
if os.geteuid() != 0:
|
||||
quota = measure(root) - measure(paths[2])
|
||||
os.chmod(batch_root, 0o555)
|
||||
try:
|
||||
buffer = io.StringIO()
|
||||
with contextlib.redirect_stderr(buffer):
|
||||
code = main([
|
||||
"--backup-root", root, "--batch-root", batch_root,
|
||||
"--quota-bytes", str(quota), "--estimate", "none", "--apply",
|
||||
])
|
||||
assert code == 5, (code, buffer.getvalue())
|
||||
assert "预检未通过" in buffer.getvalue(), buffer.getvalue()
|
||||
finally:
|
||||
os.chmod(batch_root, 0o755)
|
||||
assert sorted(os.listdir(batch_root)) == stamps[2:], os.listdir(batch_root)
|
||||
assert measure(paths[2]) > 0 and measure(paths[3]) > 0
|
||||
|
||||
# 5) 轮转:保留最近 keep_daily 份 + 最近 keep_months 个自然月各一份。
|
||||
for stamp in ["20270201T030000Z", "20270215T030000Z"]:
|
||||
make_batch(stamp, 128)
|
||||
rotated = rotate(root, batch_root, keep_daily=2, keep_months=2, apply=False)
|
||||
assert rotated["plan"] == ["20270101T030000Z"], rotated
|
||||
assert rotated["kept"] == 3, rotated
|
||||
rotated = rotate(root, batch_root, keep_daily=2, keep_months=2, apply=True)
|
||||
assert rotated["deleted"] == ["20270101T030000Z"], rotated
|
||||
assert sorted(os.listdir(batch_root)) == ["20270115T030000Z", "20270201T030000Z", "20270215T030000Z"], os.listdir(batch_root)
|
||||
|
||||
# 6) 上次失败留下的隔离目录:不算批次、不被当垃圾清掉、要报出来。
|
||||
stale = os.path.join(batch_root, f"{QUARANTINE_PREFIX}999-20270101T030000Z")
|
||||
os.makedirs(os.path.join(stale, "weknora.dir"))
|
||||
with open(os.path.join(stale, "MANIFEST.json"), "w", encoding="utf-8") as handle:
|
||||
handle.write("{}")
|
||||
assert [item.name for item in candidates(batch_root)] == [
|
||||
"20270115T030000Z", "20270201T030000Z", "20270215T030000Z"
|
||||
]
|
||||
result = rotate(root, batch_root, keep_daily=2, keep_months=2, apply=True)
|
||||
assert result["stale_quarantine"] == [os.path.basename(stale)], result
|
||||
assert os.path.isdir(stale), "隔离目录不能自动删"
|
||||
|
||||
print("prune delete-safety self-test ok")
|
||||
finally:
|
||||
for current, dirs, _files in os.walk(base):
|
||||
for name in dirs:
|
||||
os.chmod(os.path.join(current, name), 0o755)
|
||||
shutil.rmtree(base, ignore_errors=True)
|
||||
|
||||
|
||||
def _refuse_probe(_path: str) -> None:
|
||||
raise OSError("注入:改名预检失败")
|
||||
|
||||
|
||||
def _self_test() -> None:
|
||||
_self_test_quota()
|
||||
_self_test_delete_safety()
|
||||
|
||||
|
||||
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("--rotate", action="store_true", help="按份数/月份轮转(忽略配额)")
|
||||
parser.add_argument("--keep-daily", type=int, default=7, help="轮转:保留最近几份")
|
||||
parser.add_argument("--keep-months", type=int, default=3, 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")
|
||||
if args.rotate:
|
||||
result = rotate(
|
||||
backup_root,
|
||||
batch_root,
|
||||
args.keep_daily,
|
||||
args.keep_months,
|
||||
args.apply,
|
||||
)
|
||||
else:
|
||||
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 PrecheckRefused as error:
|
||||
print(f"quota prune refused: {error}", file=sys.stderr)
|
||||
return 5
|
||||
except DeleteFailed as error:
|
||||
print(f"quota prune failed: {error}", file=sys.stderr)
|
||||
return 4
|
||||
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))
|
||||
elif args.rotate:
|
||||
print(f"保留 {result['kept']} 份(每日 {result['keep_daily']} / 每月 {result['keep_months']})")
|
||||
if result["applied"]:
|
||||
for name in result["deleted"]:
|
||||
print("rotated out:", name)
|
||||
else:
|
||||
print("待删:" + ("、".join(result["plan"]) if result["plan"] else "无"))
|
||||
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['deleted'])} 个批次,占用 {result['usage_after_bytes']}")
|
||||
if result.get("stale_quarantine"):
|
||||
print(
|
||||
"注意:发现上次删除失败留下的隔离目录(内容可能不完整,未计入批次):"
|
||||
+ "、".join(result["stale_quarantine"]),
|
||||
file=sys.stderr,
|
||||
)
|
||||
if result.get("insufficient"):
|
||||
return 3
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -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}')
|
||||
@@ -30,14 +30,21 @@ def author(row):
|
||||
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):
|
||||
reviews = sorted((r for r in rows if author(r) == WHITE and r.get('taskId') == task['id']
|
||||
and r['content'].startswith('🚦')), key=lambda r: r['createdAt'], reverse=True)
|
||||
reviews = reviewer_comments(task, rows)
|
||||
cd.require(reviews and (event is None or event == reviews[0]['id']), 'require latest preflight from 白小浅')
|
||||
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')
|
||||
hashes = set(re.findall(r'落地[^\S\r\n]*(?:(merge)|merge)?[^\S\r\n]*`([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(hashes, 'preflight missing landed commit marker')
|
||||
cd.require(len(hashes) == 1, 'preflight contains multiple landed commits')
|
||||
short = hashes.pop()
|
||||
@@ -93,9 +100,10 @@ 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 = [r for r in comments(task['id']) if author(r) == WHITE and r['content'].startswith('🚦')]
|
||||
event = max(reviews, key=lambda r: r['createdAt'])['id']
|
||||
review_identity(task, reviews, event)
|
||||
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')
|
||||
|
||||
@@ -33,6 +33,31 @@ class CandidateReleaseTest(unittest.TestCase):
|
||||
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])
|
||||
|
||||
@@ -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)
|
||||
@@ -23,6 +23,15 @@ class ReleaseHandoffTest(unittest.TestCase):
|
||||
with self.assertRaises(h.cd.CDError):
|
||||
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'):
|
||||
|
||||
@@ -5,7 +5,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import { StorageBackupSummary } from './StorageBackupSummary'
|
||||
import type { BackupInventory, BackupInventoryBatch } from './backupInventory'
|
||||
import type { LibraryStorage } from './librarySnapshots'
|
||||
|
||||
const GIB = 1024 ** 3
|
||||
const TB = 1024 * GIB
|
||||
@@ -66,6 +65,7 @@ const inventory = (overrides: Partial<BackupInventory> = {}): BackupInventory =>
|
||||
},
|
||||
root: '/srv/kb-backups/rds-logical',
|
||||
host_root: '/srv/kb-backups/rds-logical',
|
||||
backup_root: '/srv/kb-backups',
|
||||
source: 'host',
|
||||
observed_at: '2026-11-24T10:18:00Z',
|
||||
measurement: 'host-reported',
|
||||
@@ -86,6 +86,18 @@ const inventory = (overrides: Partial<BackupInventory> = {}): BackupInventory =>
|
||||
available_bytes: 1.2 * 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' })],
|
||||
totals: {
|
||||
batch_count: 2,
|
||||
@@ -102,29 +114,6 @@ const inventory = (overrides: Partial<BackupInventory> = {}): BackupInventory =>
|
||||
...overrides,
|
||||
})
|
||||
|
||||
const archive: LibraryStorage = {
|
||||
available: true,
|
||||
archive_root: '/var/lib/knowledge-governance/library',
|
||||
versions: [],
|
||||
content_bytes: 41_231_686_042,
|
||||
blob_file_bytes: 0,
|
||||
blob_allocated_bytes: 0,
|
||||
unreferenced_blobs: 0,
|
||||
unreferenced_bytes: 0,
|
||||
manifest_file_bytes: 0,
|
||||
policy: { keep_versions: 0, keep_days: 0 },
|
||||
capacity: {
|
||||
budget_bytes: 100 * GIB,
|
||||
current_bytes: 41_231_686_042,
|
||||
required_bytes: 0,
|
||||
projected_bytes: 41_231_686_042,
|
||||
configured: true,
|
||||
ok: true,
|
||||
},
|
||||
automatic_cleanup: false,
|
||||
notes: [],
|
||||
}
|
||||
|
||||
let root: Root
|
||||
let container: HTMLDivElement
|
||||
let fetcher: ReturnType<typeof vi.fn<(path: string, init?: RequestInit) => Promise<Response>>>
|
||||
@@ -145,7 +134,7 @@ beforeEach(() => {
|
||||
if (path.endsWith('/inventory')) {
|
||||
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)
|
||||
})
|
||||
@@ -158,7 +147,7 @@ afterEach(() => {
|
||||
})
|
||||
|
||||
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 />))
|
||||
await flush()
|
||||
const text = container.textContent || ''
|
||||
@@ -166,9 +155,10 @@ describe('StorageBackupSummary', () => {
|
||||
expect(text).toContain('/srv/kb-backups/rds-logical')
|
||||
expect(text).toContain('最近成功')
|
||||
expect(text).toContain('最近失败')
|
||||
expect(text).toContain('归档占用')
|
||||
expect(text).toContain('38.4 GB')
|
||||
expect(text).toContain('配额 100 GB')
|
||||
expect(text).toContain('备份占用')
|
||||
expect(text).toContain('40 GB')
|
||||
expect(text).toContain('配额 50 GB')
|
||||
expect(text).not.toContain('归档占用')
|
||||
expect(text).toContain('磁盘剩余')
|
||||
expect(text).toContain('1.2 TB')
|
||||
expect(text).toContain('上次上报')
|
||||
@@ -180,12 +170,12 @@ describe('StorageBackupSummary', () => {
|
||||
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()
|
||||
act(() => root.render(<StorageBackupSummary />))
|
||||
await flush()
|
||||
expect(paths().filter((path) => path.endsWith('/inventory'))).toHaveLength(1)
|
||||
expect(paths().filter((path) => path.endsWith('/library/storage'))).toHaveLength(1)
|
||||
expect(paths().filter((path) => path.endsWith('/library/storage'))).toHaveLength(0)
|
||||
|
||||
await act(async () => {
|
||||
await vi.advanceTimersByTimeAsync(60_000)
|
||||
@@ -215,18 +205,14 @@ describe('StorageBackupSummary', () => {
|
||||
host_root: '',
|
||||
batches: [],
|
||||
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: '' },
|
||||
},
|
||||
}),
|
||||
{ status: 200 }
|
||||
)
|
||||
}
|
||||
return new Response(
|
||||
JSON.stringify({ ...archive, available: false, capacity: { ...archive.capacity, configured: false } }),
|
||||
{
|
||||
status: 200,
|
||||
}
|
||||
)
|
||||
return new Response('{}', { status: 404 })
|
||||
})
|
||||
act(() => root.render(<StorageBackupSummary />))
|
||||
await flush()
|
||||
@@ -264,7 +250,7 @@ describe('StorageBackupSummary', () => {
|
||||
{ status: 200 }
|
||||
)
|
||||
}
|
||||
return new Response(JSON.stringify(archive), { status: 200 })
|
||||
return new Response('{}', { status: 404 })
|
||||
})
|
||||
act(() => root.render(<StorageBackupSummary />))
|
||||
await flush()
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
// 「系统设置 → 存储与备份」只读摘要页:目录、最近成功/失败、归档占用、磁盘剩余、
|
||||
// 四条容量告警和批次列表。数据只来自宿主每 5 分钟上报的快照与归档库接口,
|
||||
// 本页没有任何写操作;读不到的量显示"主机未上报"或"—",不用 0 占位。
|
||||
// 「系统设置 → 存储与备份」只读摘要页:目录、最近成功/失败、备份占用、磁盘剩余、
|
||||
// 四条容量告警和批次列表。数据只来自宿主采集器上报的快照,本页没有任何写操作;
|
||||
// 读不到的量显示"主机未上报"或"—",不用 0 占位。
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
|
||||
import { fetchBackupInventory } from './backupInventory'
|
||||
import type { BackupInventory } from './backupInventory'
|
||||
import { fetchLibraryStorage } from './librarySnapshots'
|
||||
import type { LibraryStorage } from './librarySnapshots'
|
||||
import {
|
||||
UNKNOWN,
|
||||
batchOutcome,
|
||||
@@ -65,8 +63,6 @@ const hostStateLabel = (state: HostState): string => {
|
||||
|
||||
export function StorageBackupSummary() {
|
||||
const [inventory, setInventory] = useState<BackupInventory | null>(null)
|
||||
const [archive, setArchive] = useState<LibraryStorage | null>(null)
|
||||
const [archiveFailed, setArchiveFailed] = useState(false)
|
||||
const [errors, setErrors] = useState<string[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [visible, setVisible] = useState(BATCH_PAGE)
|
||||
@@ -77,24 +73,15 @@ export function StorageBackupSummary() {
|
||||
const load = useCallback(async () => {
|
||||
if (inFlight.current) return
|
||||
inFlight.current = true
|
||||
const [inventoryResult, archiveResult] = await Promise.allSettled([fetchBackupInventory(), fetchLibraryStorage()])
|
||||
const nextErrors: string[] = []
|
||||
if (inventoryResult.status === 'fulfilled') {
|
||||
setInventory(inventoryResult.value)
|
||||
} else {
|
||||
nextErrors.push(inventoryResult.reason instanceof Error ? inventoryResult.reason.message : '读取备份元数据失败')
|
||||
try {
|
||||
setInventory(await fetchBackupInventory())
|
||||
setErrors([])
|
||||
} catch (error) {
|
||||
setErrors([error instanceof Error ? error.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(() => {
|
||||
@@ -110,8 +97,8 @@ export function StorageBackupSummary() {
|
||||
}, [load])
|
||||
|
||||
const state = hostState(inventory)
|
||||
const alerts = storageAlerts(inventory, archive, archiveFailed)
|
||||
const cards = summaryCards(inventory, archive, archiveFailed)
|
||||
const alerts = storageAlerts(inventory)
|
||||
const cards = summaryCards(inventory)
|
||||
const batches = inventory?.batches ?? []
|
||||
const shown = batches.slice(0, visible)
|
||||
|
||||
|
||||
@@ -43,6 +43,19 @@ const payload = {
|
||||
available_bytes: 48318382080,
|
||||
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: [
|
||||
{
|
||||
stamp: '20261118T193001Z',
|
||||
@@ -108,6 +121,48 @@ describe('fetchBackupInventory', () => {
|
||||
'/srv/kb-backups/rds-logical/20261118T193001Z/weknora_v090prod.dir'
|
||||
)
|
||||
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 () => {
|
||||
|
||||
@@ -39,6 +39,18 @@ export interface BackupInventoryCapacity {
|
||||
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 {
|
||||
name: string
|
||||
dir_name: string
|
||||
@@ -84,12 +96,16 @@ export interface BackupInventory {
|
||||
metadata: BackupInventoryMetadata
|
||||
root: string
|
||||
host_root: string
|
||||
backup_root: string
|
||||
source: string
|
||||
observed_at: string
|
||||
error?: string
|
||||
measurement: string
|
||||
mount: BackupInventoryMount
|
||||
capacity: BackupInventoryCapacity
|
||||
usage: BackupInventoryUsage
|
||||
quota_bytes: number | null
|
||||
quota_error: string
|
||||
batches: BackupInventoryBatch[]
|
||||
totals: {
|
||||
batch_count: number
|
||||
@@ -115,6 +131,22 @@ const asNumberOrNull = (value: unknown): number | null =>
|
||||
const asBool = (value: unknown): boolean => value === true
|
||||
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 =>
|
||||
value === 'ok' || value === 'missing' || value === 'invalid' ? value : 'invalid'
|
||||
|
||||
@@ -186,10 +218,16 @@ function inventoryProjection(value: unknown): BackupInventory {
|
||||
},
|
||||
root: asString(value.root),
|
||||
host_root: asString(value.host_root),
|
||||
backup_root: asString(value.backup_root),
|
||||
source: asString(value.source),
|
||||
observed_at: asString(value.observed_at),
|
||||
error: asString(value.error),
|
||||
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: {
|
||||
container_root: asString(mount.container_root),
|
||||
mount_verified: asBool(mount.mount_verified),
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import type { BackupInventory, BackupInventoryBatch } from './backupInventory'
|
||||
import type { LibraryStorage } from './librarySnapshots'
|
||||
import {
|
||||
DISK_CRITICAL_AVAILABLE_PERCENT,
|
||||
batchOutcome,
|
||||
@@ -70,6 +69,7 @@ export const inventory = (overrides: Partial<BackupInventory> = {}): BackupInven
|
||||
},
|
||||
root: '/srv/kb-backups/rds-logical',
|
||||
host_root: '/srv/kb-backups/rds-logical',
|
||||
backup_root: '/srv/kb-backups',
|
||||
source: 'host',
|
||||
observed_at: '2026-11-24T10:18:00Z',
|
||||
measurement: 'host-reported',
|
||||
@@ -90,6 +90,18 @@ export const inventory = (overrides: Partial<BackupInventory> = {}): BackupInven
|
||||
available_bytes: 1.2 * 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()],
|
||||
totals: {
|
||||
batch_count: 1,
|
||||
@@ -106,30 +118,6 @@ export const inventory = (overrides: Partial<BackupInventory> = {}): BackupInven
|
||||
...overrides,
|
||||
})
|
||||
|
||||
export const archive = (overrides: Partial<LibraryStorage> = {}): LibraryStorage => ({
|
||||
available: true,
|
||||
archive_root: '/var/lib/knowledge-governance/library',
|
||||
versions: [],
|
||||
content_bytes: 41_231_686_042,
|
||||
blob_file_bytes: 0,
|
||||
blob_allocated_bytes: 0,
|
||||
unreferenced_blobs: 0,
|
||||
unreferenced_bytes: 0,
|
||||
manifest_file_bytes: 0,
|
||||
policy: { keep_versions: 0, keep_days: 0 },
|
||||
capacity: {
|
||||
budget_bytes: 100 * GIB,
|
||||
current_bytes: 41_231_686_042,
|
||||
required_bytes: 0,
|
||||
projected_bytes: 41_231_686_042,
|
||||
configured: true,
|
||||
ok: true,
|
||||
},
|
||||
automatic_cleanup: false,
|
||||
notes: [],
|
||||
...overrides,
|
||||
})
|
||||
|
||||
const unreported = (): BackupInventory =>
|
||||
inventory({
|
||||
wired: false,
|
||||
@@ -151,6 +139,19 @@ const unreported = (): BackupInventory =>
|
||||
},
|
||||
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 },
|
||||
batches: [],
|
||||
totals: {
|
||||
@@ -230,48 +231,57 @@ describe('recentOutcome', () => {
|
||||
})
|
||||
|
||||
describe('summaryCards', () => {
|
||||
it('shows real values when the host reported and the archive is available', () => {
|
||||
const cards = summaryCards(inventory(), archive(), false)
|
||||
it('shows real values from the host snapshot for backup occupancy and quota', () => {
|
||||
const cards = summaryCards(inventory())
|
||||
const byKey = Object.fromEntries(cards.map((card) => [card.key, card.value]))
|
||||
expect(byKey.root).toBe('/srv/kb-backups/rds-logical')
|
||||
expect(byKey.success).toBe(formatWhen('2026-11-24T02:00:00Z'))
|
||||
expect(byKey.failure).toBe('无')
|
||||
expect(byKey.archive).toBe('38.4 GB')
|
||||
expect(byKey.backup).toBe(formatSize(22.65 * GIB))
|
||||
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', () => {
|
||||
const cards = summaryCards(unreported(), archive({ available: false }), false)
|
||||
for (const key of ['root', 'success', 'failure', 'disk']) {
|
||||
const cards = summaryCards(unreported())
|
||||
for (const key of ['root', 'success', 'failure', 'backup', 'disk']) {
|
||||
const card = cards.find((item) => item.key === key)!
|
||||
expect(card.value).toBe('主机未上报')
|
||||
expect(card.note).toBe('上次上报 —')
|
||||
}
|
||||
expect(cards.find((card) => card.key === 'archive')?.value).toBe('—')
|
||||
expect(cards.some((card) => card.value === '0 B')).toBe(false)
|
||||
})
|
||||
|
||||
it('keeps paths readable but leaves sizes empty for an incomplete report', () => {
|
||||
const cards = summaryCards(inventory({ metadata: { ...inventory().metadata, complete: false } }), archive(), false)
|
||||
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 === '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')?.note).toBe('本次上报不完整')
|
||||
})
|
||||
})
|
||||
|
||||
describe('storageAlerts', () => {
|
||||
it('judges disk and quota independently and counts pending rows', () => {
|
||||
const healthy = storageAlerts(inventory(), archive(), false)
|
||||
it('judges disk and backup quota independently and counts pending rows', () => {
|
||||
const healthy = storageAlerts(inventory())
|
||||
expect(healthy.map((row) => row.conclusion)).toEqual(['正常', '正常', '正常', '正常'])
|
||||
expect(pendingAlertCount(healthy)).toBe(0)
|
||||
|
||||
const nearQuota = storageAlerts(
|
||||
inventory(),
|
||||
archive({
|
||||
capacity: { ...archive().capacity, current_bytes: 95 * GIB, budget_bytes: 100 * GIB },
|
||||
}),
|
||||
false
|
||||
inventory({ usage: { ...inventory().usage, actual_bytes: 45 * GIB }, quota_bytes: 50 * GIB })
|
||||
)
|
||||
expect(nearQuota.find((row) => row.key === 'quota_low')?.tone).toBe('warn')
|
||||
expect(nearQuota.find((row) => row.key === 'both_low')?.conclusion).toBe('正常')
|
||||
@@ -288,9 +298,9 @@ describe('storageAlerts', () => {
|
||||
available_bytes: 0.01 * TB,
|
||||
used_bytes: 1.99 * TB,
|
||||
},
|
||||
}),
|
||||
archive({ capacity: { ...archive().capacity, current_bytes: 100 * GIB, budget_bytes: 100 * GIB } }),
|
||||
false
|
||||
usage: { ...inventory().usage, actual_bytes: 100 * GIB },
|
||||
quota_bytes: 100 * GIB,
|
||||
})
|
||||
)
|
||||
expect(tight.find((row) => row.key === 'disk_low')?.tone).toBe('bad')
|
||||
expect(tight.find((row) => row.key === 'both_low')?.conclusion).toBe('需处理')
|
||||
@@ -300,7 +310,7 @@ describe('storageAlerts', () => {
|
||||
})
|
||||
|
||||
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.find((row) => row.key === 'disk_low')?.value).toBe('主机未上报')
|
||||
expect(alerts.some((row) => row.value.includes('无法判定'))).toBe(false)
|
||||
|
||||
+43
-50
@@ -1,9 +1,7 @@
|
||||
// 「存储与备份」只读摘要的纯逻辑:数据源只有两个只读接口——
|
||||
// /api/v1/backup-schedule/inventory (宿主每 5 分钟上报的元数据快照)
|
||||
// /api/v1/library/storage (归档库自身的占用与配额)
|
||||
// 「存储与备份」只读摘要的纯逻辑:唯一数据源是宿主采集器快照
|
||||
// /api/v1/backup-schedule/inventory (批次、备份根占用、配额与文件系统容量)
|
||||
// 页面不提供任何写操作。读不到的量一律留空("主机未上报" / "—"),不用 0 冒充。
|
||||
import type { BackupInventory, BackupInventoryBatch } from './backupInventory'
|
||||
import type { LibraryStorage } from './librarySnapshots'
|
||||
|
||||
// 阈值(与 docs/STORAGE_BACKUP_READONLY_API.md 的「页面口径」一致):
|
||||
// 磁盘:可用空间 < 5% 红,< 10% 黄
|
||||
@@ -159,11 +157,7 @@ export interface SummaryCard {
|
||||
const lastReportNote = (inventory: BackupInventory): string =>
|
||||
`上次上报 ${formatWhen(inventory.metadata.collected_at) || UNKNOWN}`
|
||||
|
||||
export function summaryCards(
|
||||
inventory: BackupInventory | null,
|
||||
archive: LibraryStorage | null,
|
||||
archiveFailed: boolean
|
||||
): SummaryCard[] {
|
||||
export function summaryCards(inventory: BackupInventory | null): SummaryCard[] {
|
||||
const state = hostState(inventory)
|
||||
const facts = state === 'ready' || state === 'incomplete'
|
||||
const sizes = state === 'ready'
|
||||
@@ -181,7 +175,20 @@ export function summaryCards(
|
||||
const diskKnown = sizes && Boolean(capacity?.measured) && (capacity?.total_bytes ?? 0) > 0
|
||||
const availablePercent = diskKnown ? Math.round((capacity!.available_bytes / capacity!.total_bytes) * 100) : 0
|
||||
|
||||
const archiveKnown = Boolean(archive?.available) && !archiveFailed
|
||||
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 [
|
||||
{
|
||||
@@ -207,17 +214,11 @@ export function summaryCards(
|
||||
unknown: !recent,
|
||||
},
|
||||
{
|
||||
key: 'archive',
|
||||
label: '归档占用',
|
||||
value: archiveKnown ? formatSize(archive!.capacity.current_bytes) : UNKNOWN,
|
||||
note: archiveFailed
|
||||
? '归档读取失败'
|
||||
: !archive || !archive.available
|
||||
? '归档不可用'
|
||||
: archive.capacity.configured
|
||||
? `配额 ${formatSize(archive.capacity.budget_bytes)}`
|
||||
: '配额未设置',
|
||||
unknown: !archiveKnown,
|
||||
key: 'backup',
|
||||
label: '备份占用',
|
||||
value: usageKnown ? formatSize(usage!.actual_bytes) : facts ? UNKNOWN : hostValue,
|
||||
note: backupNote,
|
||||
unknown: !usageKnown,
|
||||
},
|
||||
{
|
||||
key: 'disk',
|
||||
@@ -244,23 +245,21 @@ export interface SummaryAlert {
|
||||
export interface StorageFacts {
|
||||
diskAvailableBytes: number | null
|
||||
diskTotalBytes: number | null
|
||||
archiveUsedBytes: number | null
|
||||
archiveBudgetBytes: number | null
|
||||
backupUsedBytes: number | null
|
||||
backupQuotaBytes: number | null
|
||||
}
|
||||
|
||||
export function storageFacts(
|
||||
inventory: BackupInventory | null,
|
||||
archive: LibraryStorage | null,
|
||||
archiveFailed: boolean
|
||||
): StorageFacts {
|
||||
export function storageFacts(inventory: BackupInventory | null): StorageFacts {
|
||||
const capacity = inventory?.capacity
|
||||
const diskKnown = hostState(inventory) === 'ready' && Boolean(capacity?.measured) && (capacity?.total_bytes ?? 0) > 0
|
||||
const archiveCapacity = archive?.available && !archiveFailed ? archive.capacity : null
|
||||
const usage = inventory?.usage
|
||||
const used = usage?.measured && usage.actual_bytes !== null ? usage.actual_bytes : null
|
||||
const quota = inventory?.quota_bytes ?? null
|
||||
return {
|
||||
diskAvailableBytes: diskKnown ? capacity!.available_bytes : null,
|
||||
diskTotalBytes: diskKnown ? capacity!.total_bytes : null,
|
||||
archiveUsedBytes: archiveCapacity ? archiveCapacity.current_bytes : null,
|
||||
archiveBudgetBytes: archiveCapacity?.configured ? archiveCapacity.budget_bytes : null,
|
||||
backupUsedBytes: used,
|
||||
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 =>
|
||||
tone === 'ok' ? '正常' : tone === 'warn' ? '注意' : tone === 'bad' ? '需处理' : UNKNOWN_STATE
|
||||
|
||||
export function storageAlerts(
|
||||
inventory: BackupInventory | null,
|
||||
archive: LibraryStorage | null,
|
||||
archiveFailed: boolean
|
||||
): SummaryAlert[] {
|
||||
export function storageAlerts(inventory: BackupInventory | null): SummaryAlert[] {
|
||||
const state = hostState(inventory)
|
||||
const facts = storageFacts(inventory, archive, archiveFailed)
|
||||
const facts = storageFacts(inventory)
|
||||
const diskKnown = facts.diskAvailableBytes !== null && (facts.diskTotalBytes ?? 0) > 0
|
||||
const availablePercent = diskKnown ? Math.round((facts.diskAvailableBytes! / facts.diskTotalBytes!) * 100) : 0
|
||||
const diskTone: Tone = diskKnown
|
||||
@@ -287,16 +282,16 @@ export function storageAlerts(
|
||||
: 'ok'
|
||||
: 'none'
|
||||
|
||||
const quotaKnown = facts.archiveUsedBytes !== null && (facts.archiveBudgetBytes ?? 0) > 0
|
||||
const usedPercent = quotaKnown ? Math.round((facts.archiveUsedBytes! / facts.archiveBudgetBytes!) * 100) : 0
|
||||
const quotaKnown = facts.backupUsedBytes !== null && (facts.backupQuotaBytes ?? 0) > 0
|
||||
const usedPercent = quotaKnown ? Math.round((facts.backupUsedBytes! / facts.backupQuotaBytes!) * 100) : 0
|
||||
const quotaTone: Tone = quotaKnown
|
||||
? tonePercent(usedPercent, QUOTA_WARN_USED_PERCENT, QUOTA_CRITICAL_USED_PERCENT)
|
||||
: 'none'
|
||||
const bothTone: Tone =
|
||||
diskTone === 'none' || quotaTone === 'none' ? 'none' : diskTone !== 'ok' && quotaTone !== 'ok' ? 'bad' : 'ok'
|
||||
const overPhysical: Tone =
|
||||
diskKnown && facts.archiveBudgetBytes !== null
|
||||
? facts.archiveBudgetBytes > facts.diskAvailableBytes!
|
||||
diskKnown && facts.backupQuotaBytes !== null
|
||||
? facts.backupQuotaBytes > facts.diskAvailableBytes!
|
||||
? 'bad'
|
||||
: 'ok'
|
||||
: 'none'
|
||||
@@ -315,12 +310,10 @@ export function storageAlerts(
|
||||
key: 'quota_low',
|
||||
label: '配额不足',
|
||||
value: quotaKnown
|
||||
? `${formatSize(facts.archiveUsedBytes)} / ${formatSize(facts.archiveBudgetBytes)}(${usedPercent}%)`
|
||||
: archiveFailed
|
||||
? UNKNOWN
|
||||
: archive?.available
|
||||
? '配额未设置'
|
||||
: UNKNOWN,
|
||||
? `${formatSize(facts.backupUsedBytes)} / ${formatSize(facts.backupQuotaBytes)}(${usedPercent}%)`
|
||||
: inventory?.quota_error
|
||||
? '配额未上报'
|
||||
: UNKNOWN,
|
||||
tone: quotaTone,
|
||||
conclusion: quotaKnown ? conclusionText(quotaTone) : UNKNOWN_STATE,
|
||||
},
|
||||
@@ -335,11 +328,11 @@ export function storageAlerts(
|
||||
key: 'quota_over_physical',
|
||||
label: '配额超出物理空闲',
|
||||
value:
|
||||
diskKnown && facts.archiveBudgetBytes !== null
|
||||
? `配额 ${formatSize(facts.archiveBudgetBytes)} · 可用 ${formatSize(facts.diskAvailableBytes)}`
|
||||
diskKnown && facts.backupQuotaBytes !== null
|
||||
? `配额 ${formatSize(facts.backupQuotaBytes)} · 可用 ${formatSize(facts.diskAvailableBytes)}`
|
||||
: UNKNOWN,
|
||||
tone: overPhysical,
|
||||
conclusion: diskKnown && facts.archiveBudgetBytes !== null ? conclusionText(overPhysical) : UNKNOWN_STATE,
|
||||
conclusion: diskKnown && facts.backupQuotaBytes !== null ? conclusionText(overPhysical) : UNKNOWN_STATE,
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user