From 63984dbfbeab77765bb098bf13e222764009be33 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=E5=A7=9A=E7=AB=A0=E6=B5=A9?=
Date: Fri, 20 Nov 2026 01:41:28 +0800
Subject: [PATCH] =?UTF-8?q?fix(backup):=20=E5=AE=BF=E4=B8=BB=E9=87=87?=
=?UTF-8?q?=E9=9B=86=E5=99=A8=E6=8C=89=20du=20=E5=8F=A3=E5=BE=84=E5=8E=BB?=
=?UTF-8?q?=E9=87=8D=E7=A1=AC=E9=93=BE=E6=8E=A5=E5=B9=B6=E6=8B=92=E7=BB=9D?=
=?UTF-8?q?=E6=B8=85=E5=8D=95=E7=AC=A6=E5=8F=B7=E9=93=BE=E6=8E=A5?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
备份目录 root:root 0700,API 不再遍历;宿主采集器只读 stat/du,原子写快照。统计包含目录自身、树内 (dev,ino) 硬链接去重,单库与整批各自独立与 du -sB1 对齐;MANIFEST 仅接受目录内常规非符号链接文件并 O_NOFOLLOW 打开。快照缺失/陈旧/不完整时批次与子库字节为 null,页面不画容量图、不使用部分字节。
---
CHANGELOG.md | 22 +
api/openapi.yaml | 2 +-
cmd/api/main.go | 9 +-
compose.release-sim.yaml | 8 +-
docs/PRODUCTION_BACKUP_RECOVERY.md | 9 +-
docs/STORAGE_BACKUP_READONLY_API.md | 289 ++++---
internal/appconfig/config.go | 29 +-
internal/appconfig/config_test.go | 27 +-
internal/backupinventory/inventory.go | 914 ++++++++++-----------
internal/backupinventory/inventory_test.go | 373 +++++----
internal/httpapi/backup_inventory.go | 8 +-
internal/httpapi/backup_inventory_test.go | 15 +-
scripts/collect_backup_metadata.py | 581 +++++++++++++
web/src/BackupScheduleSection.test.tsx | 121 ++-
web/src/BackupScheduleSection.tsx | 205 +++--
web/src/backupInventory.test.ts | 29 +-
web/src/backupInventory.ts | 94 ++-
17 files changed, 1798 insertions(+), 937 deletions(-)
create mode 100755 scripts/collect_backup_metadata.py
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 96db63f..8968507 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,27 @@
# Changelog
+## 开发快照 0.1.408(备份盘点改宿主采集器:权限失败不再产出部分字节)
+
+### Fixed
+
+- 修复 API 以 uid 1000 遍历 root:root 0700 备份目录时 `sizes_complete=false` 但
+ `Database.ActualBytes` 仍保留部分计数的问题:API 不再遍历备份目录,只读宿主快照;
+ 快照不完整/陈旧/缺失时批次与子库字节全部为 `null`,页面不画容量图、不使用部分字节。
+- 容量图与任何可写预测只在“快照新鲜 + 完整 + 路径校验通过 + 容量实测”时出现;
+ 权限失败回归覆盖采集器注入 `PermissionError` 与 API 拒绝部分字段。
+- 单库 `696320` 只作现场核对值,代码与测试不写死。
+
+### Added
+
+- `scripts/collect_backup_metadata.py`:宿主单次只读采集器,stat/du + MANIFEST,
+ 原子写 `metadata.json`,不读数据库内容、不跟随符号链接、权限失败置空字节。
+ 统计口径与 `du -sB1` 对齐:目录自身计入、树内硬链接按 `(dev,ino)` 去重、
+ 单库与整批各自独立测量;MANIFEST 只接受批次目录内常规非符号链接文件,
+ 打开带 `O_NOFOLLOW`。
+- `GET /api/v1/backup-schedule/inventory` 读取并校验快照:schema、root、批次/子库路径、
+ 采集时效、完整性;批次/子库字节可空。
+- 文档改为 28189 快照挂载、采集器安装/定时、可验证字段与写能力清单。
+
## 开发快照 0.1.407(备份盘点:只读挂载读真实批次与容量)
### Added
diff --git a/api/openapi.yaml b/api/openapi.yaml
index 021979a..1891144 100644
--- a/api/openapi.yaml
+++ b/api/openapi.yaml
@@ -1978,7 +1978,7 @@
"Settings"
],
"operationId": "getBackupScheduleInventory",
- "summary": "只读盘点备份批次、子库完整路径与实际占盘、挂载文件系统实测容量",
+ "summary": "读取宿主元数据快照:批次、子库完整路径、实际占盘与文件系统容量(陈旧/不完整一律未知)",
"responses": {
"200": {
"$ref": "#/components/responses/Envelope"
diff --git a/cmd/api/main.go b/cmd/api/main.go
index 70cdd02..c072cb0 100644
--- a/cmd/api/main.go
+++ b/cmd/api/main.go
@@ -57,7 +57,7 @@ func (dingtalkSourceLister) ValidateDingtalkDocument(ctx context.Context, node s
return dingtalkdiscovery.ValidateDocument(ctx, dingtalkdiscovery.ExecRunner{}, node)
}
-// 只读盘点的展示路径必须与挂载来源同一份:容器内挂载点不可给操作者复制,
+// 宿主快照的展示路径必须与采集 root 同一份:容器内快照路径不可给操作者复制,
// 复制出去要在主机上能直接 cd/pg_restore。来源没配时用 target + 主机根拼。
func backupInventoryHostRoot(config appconfig.Config) string {
if config.BackupHostReadonlyHostPath != "" {
@@ -340,9 +340,10 @@ func run(ctx context.Context, getenv func(string) string) error {
Root: config.BackupHostRoot,
}),
BackupInventory: backupinventory.New(backupinventory.Config{
- Root: config.BackupHostReadonlyRoot,
- HostRoot: backupInventoryHostRoot(config),
- Source: backupInventorySource(config),
+ MetadataPath: config.BackupHostMetadataPath,
+ HostRoot: config.BackupHostReadonlyHostPath,
+ Source: backupInventorySource(config),
+ MaxAge: config.BackupHostMetadataMaxAge,
}),
Auth: &httpapi.AuthConfig{Store: authStore, SessionTTL: 12 * time.Hour},
})
diff --git a/compose.release-sim.yaml b/compose.release-sim.yaml
index bf4728b..f2a321d 100644
--- a/compose.release-sim.yaml
+++ b/compose.release-sim.yaml
@@ -17,14 +17,16 @@ services:
BACKUP_HOST_SCRIPT_DIR: /opt/weknora-test
BACKUP_HOST_ROOT: /srv/kb-backups
# 只读盘点(批次/子库路径/实测容量)与上面的 SSH 计划读回独立。
- # 候选 28189 部署时按 docs/STORAGE_BACKUP_READONLY_API.md 打开,并要求宿主目录只读挂载:
- # BACKUP_HOST_READONLY_ROOT: /var/lib/knowledge-governance/backup-host/rds-logical
+ # 候选 28189 部署时按 docs/STORAGE_BACKUP_READONLY_API.md 打开:
+ # 宿主采集器原子写 metadata.json,API 只读挂载输出目录(不挂备份目录):
+ # BACKUP_HOST_METADATA_PATH: /var/lib/knowledge-governance/backup-host/metadata.json
+ # BACKUP_HOST_METADATA_MAX_AGE: 15m
# BACKUP_HOST_READONLY_HOST_PATH: /srv/kb-backups/rds-logical
# BACKUP_HOST_READONLY_SOURCE: weknora-test:/srv/kb-backups/rds-logical
volumes:
- ./secrets/release-sim:/run/release-secrets:ro
- ./secrets/backup-host:/run/backup-host:ro
- # - /srv/kb-backups/rds-logical:/var/lib/knowledge-governance/backup-host/rds-logical:ro
+ # - /var/lib/knowledge-governance/backup-metadata:/var/lib/knowledge-governance/backup-host:ro
release-worker:
environment:
diff --git a/docs/PRODUCTION_BACKUP_RECOVERY.md b/docs/PRODUCTION_BACKUP_RECOVERY.md
index 9915f4d..d31425d 100644
--- a/docs/PRODUCTION_BACKUP_RECOVERY.md
+++ b/docs/PRODUCTION_BACKUP_RECOVERY.md
@@ -91,16 +91,17 @@ python3 scripts/restore_drill.py --snapshot-dir $KB_BACKUP_ROOT/target-kb-snapsh
- 页面:系统设置 → 存储与备份(管理员可改;保存 = 写入库并立刻下发;另有"重新下发当前设置"与"立即备份一次")。
- 接口:`GET /api/v1/backup-schedule`(不探测主机,首屏快)、`GET …/host`(SSH 读回主机 cron 与最近一次结果)、
- `GET …/inventory`(只读挂载盘点全部批次/子库路径/实测容量,见 `docs/STORAGE_BACKUP_READONLY_API.md`)、
+ `GET …/inventory`(宿主采集器快照读全部批次/子库路径/实测容量,见 `docs/STORAGE_BACKUP_READONLY_API.md`)、
`PUT`(校验时间 `HH:MM` 与 1~365 天 / 0~24 月,非法值直接 400 且不落库不下发)、`POST …/apply`、`POST …/run`。
写操作按角色网关(`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` 可覆盖)。
- 凭据:容器内只读挂载 `secrets/backup-host/{ssh_config,id_ed25519,known_hosts}`(0600),
环境变量 `BACKUP_HOST_SSH_CONFIG / BACKUP_HOST_TARGET / BACKUP_HOST_SCRIPT_DIR / BACKUP_HOST_ROOT`;
- **三项缺任一即"未接线"**,页面降级提示而不是报错。只读盘点另用
- `BACKUP_HOST_READONLY_ROOT / BACKUP_HOST_READONLY_HOST_PATH / BACKUP_HOST_READONLY_SOURCE`,
- 要求 `:ro` 挂载,见 `docs/STORAGE_BACKUP_READONLY_API.md`。
+ **三项缺任一即"未接线"**,页面降级提示而不是报错。只读盘点另用宿主采集器
+ `scripts/collect_backup_metadata.py` 原子写 `metadata.json`,API 用
+ `BACKUP_HOST_METADATA_PATH / BACKUP_HOST_READONLY_HOST_PATH` 只读快照,见
+ `docs/STORAGE_BACKUP_READONLY_API.md`。
- 主机状态读取只认**有 `MANIFEST.json` 的完整目录**:被中断的运行会被脚本改名 `*.incomplete`,
所以"最近一次备份"永远不会显示一份半成品。
- 依赖两个运行前提:运行镜像里有 `openssh-client`,且容器用户的 uid 在 `/etc/passwd` 有名字
diff --git a/docs/STORAGE_BACKUP_READONLY_API.md b/docs/STORAGE_BACKUP_READONLY_API.md
index f1c23a1..577c694 100644
--- a/docs/STORAGE_BACKUP_READONLY_API.md
+++ b/docs/STORAGE_BACKUP_READONLY_API.md
@@ -1,166 +1,209 @@
-# 存储与备份:只读盘点接口与 28189 候选接线
+# 存储与备份:宿主元数据采集器、只读接口与 28189 接线
-本页的「备份记录 / 整盘占用」只读**备份执行主机**上的 `rds-logical` 目录。接口不执行
-SSH 文件命令,也不写备份目录;它只读一个**只读挂载**进来的目录,并用 `statfs` 与
-`st_blocks` 给出实测容量和实际占盘。主机 cron 计划的读回仍是另一条 SSH 通道,两者独立。
+「备份记录 / 整盘占用」不遍历备份目录。备份目录通常是 `root:root 0700`,API 容器
+用户 `uid 1000` 进不去;容器里遍历只会得到 permission denied 的部分字节。真实闭环是:
-## 1. 接口契约
+1. 备份主机上由**有读权限的宿主进程**运行 `scripts/collect_backup_metadata.py` 单次采集;
+ 只做 `stat`/`du` 元数据和读 `MANIFEST.json`,不读数据库内容文件。
+2. 采集器用同目录临时文件 + `fsync` + `os.replace` **原子写出** `metadata.json`。
+3. API 只读挂载这个 JSON,校验 schema、批次/子库路径、主机根、时效、完整性。
+4. 快照陈旧/缺失/不完整时,批次字节为 `null`,页面显示未知,不画容量图、不做可写预测。
+
+主机 cron 计划读回仍是原来的 SSH 通道(`/host`),与快照完全独立;API 不借用 SSH
+读文件,也不获得备份目录的容器权限。
+
+## 1. 采集器(宿主运行)
+
+脚本:`scripts/collect_backup_metadata.py`(Python 3 标准库,无第三方依赖)
+
+```sh
+python3 collect_backup_metadata.py \
+ --root /srv/kb-backups/rds-logical \
+ --output /var/lib/knowledge-governance/backup-metadata/metadata.json \
+ --source weknora-test:/srv/kb-backups/rds-logical
+```
+
+- 退出码:`0` 完整;`2` 已写快照但采集不完整/有错误;`1` 连快照都没写成。
+- 只读取:目录项 `lstat`、`statvfs`、`/proc/self/mountinfo`、`MANIFEST.json`;
+ **不打开任何 `.dat/.gz` 数据文件**。
+- 不跟随符号链接;`*.incomplete` 只计数不进入批次;单次最多 100 批(可调)。
+- 口径与 `du -sB1` 对齐:目录自身块计入;遍历整棵子树而非只求和文件;
+ 常规文件硬链接按 `(st_dev, st_ino)` 只算一次;**每个子库与整批各自独立测量**,
+ 所以单库字节与该子库自己的 `du` 一致、整批与整批 `du` 一致(不会把整批去重结果
+ 摊回单库)。
+- `MANIFEST.json` 只接受批次目录内的常规非符号链接文件;`lstat` + `O_NOFOLLOW`
+ 打开,符号链接/非普通文件一律 `invalid`,不会被跟随到别处。
+- 权限失败会写入 `batch.errors` 并把 `actual_bytes/apparent_bytes/file_count` 置 `null`;
+ 绝不把已数到的部分字节当占盘。
+
+建议由宿主定时器每 5 分钟跑一次(root 或备份目录所有者;不改任何备份权限):
+
+```cron
+*/5 * * * * /usr/bin/python3 /opt/knowledge-governance/collect_backup_metadata.py \
+ --root /srv/kb-backups/rds-logical \
+ --output /var/lib/knowledge-governance/backup-metadata/metadata.json \
+ --source weknora-test:/srv/kb-backups/rds-logical \
+ >> /var/log/knowledge-governance-backup-metadata.log 2>&1
+```
+
+目录 `0755`、文件 `0644`,只包含路径/清单摘要/计数,不含数据库内容。
+
+### 快照 schema(version 1)
+
+关键字段:
+
+| 字段 | 含义 |
+| --- | --- |
+| `schema_version` | `1`;API 不认识就整块拒绝 |
+| `collected_at` | UTC RFC3339;超过 `BACKUP_HOST_METADATA_MAX_AGE` 即陈旧 |
+| `generation` | 每次采集唯一 ID,便于核对读到的是哪一次原子快照 |
+| `root` | 宿主上的 `rds-logical` 绝对路径;API 要求与配置完全一致 |
+| `complete` | 全局完整;权限失败/截断/有错误时为 false |
+| `filesystem` | `mount_point/mount_source/fs_type/read_only/total/free/available` |
+| `batches[].complete` | 该批遍历完整;false 时字节必须为 null |
+| `batches[].actual_bytes` | `st_blocks×512` 实际分配,仅完整批有值 |
+| `batches[].databases[].path` | 子库完整宿主路径,必须等于 `/.dir` |
+| `batches[].manifest_state` | `ok` / `missing` / `invalid`(清单是元数据,不影响权限统计) |
+
+## 2. 接口契约
`GET /api/v1/backup-schedule/inventory`(读者角色可看;不写任何东西)
-响应始终是 200 + `data`,未接线/目录不可读/清单损坏都写在字段里,页面据此区分原因。
-只有请求本身失败(如代理 502)才是非 200。
+始终 200 + `data`;未接线/快照缺失/陈旧/不完整/路径不一致都写在字段里。
```json
{
"data": {
"wired": true,
- "root": "/var/lib/knowledge-governance/backup-host/rds-logical",
+ "metadata": {
+ "configured": true, "present": true, "valid": true,
+ "fresh": true, "complete": true,
+ "path": "/var/lib/knowledge-governance/backup-host/metadata.json",
+ "collected_at": "2026-11-20T01:00:00Z",
+ "age_seconds": 10, "max_age_seconds": 900,
+ "schema_version": 1, "generation": "20261120T010000Z-abc123",
+ "host": "weknora-test", "collector_version": "backup-metadata/1",
+ "error": ""
+ },
+ "root": "/srv/kb-backups/rds-logical",
"host_root": "/srv/kb-backups/rds-logical",
"source": "weknora-test:/srv/kb-backups/rds-logical",
- "observed_at": "2026-11-19T03:30:10Z",
- "error": "",
+ "measurement": "host_collector",
"mount": {
- "container_root": "/",
- "mount_verified": true,
- "lives_on_container_root": false,
- "read_only": true,
- "evidence": "挂载设备 20 与容器根盘 10 不同:容量按挂载文件系统计量"
+ "mount_verified": true, "read_only": false,
+ "mount_point": "/srv/kb-backups", "device": "/dev/sdb1", "fs_type": "ext4",
+ "evidence": "宿主采集器:/dev/sdb1 挂在 /srv/kb-backups(ext4),API 不遍历备份目录"
},
"capacity": {
- "measured": true,
- "total_bytes": 257698037760,
- "free_bytes": 51539607552,
- "available_bytes": 48318382080,
- "used_bytes": 206158430208
+ "measured": true, "total_bytes": 1000, "free_bytes": 400,
+ "available_bytes": 350, "used_bytes": 600
},
- "batches": [
- {
- "stamp": "20261118T193001Z",
- "path": "/var/lib/knowledge-governance/backup-host/rds-logical/20261118T193001Z",
- "host_path": "/srv/kb-backups/rds-logical/20261118T193001Z",
- "manifest_state": "ok",
- "manifest_path": "…/20261118T193001Z/MANIFEST.json",
- "manifest_error": "",
- "kind": "rds-logical-backup",
- "created_at": "20261118T193001Z",
- "duration_seconds": 53,
- "manifest_total_bytes": 1393646469,
- "apparent_bytes": 1393646469,
- "actual_bytes": 1500000000,
- "file_count": 214,
- "sizes_complete": true,
- "databases": [
- {
- "name": "weknora_v090prod",
- "dir_name": "weknora_v090prod.dir",
- "path": "…/20261118T193001Z/weknora_v090prod.dir",
- "host_path": "/srv/kb-backups/rds-logical/20261118T193001Z/weknora_v090prod.dir",
- "present": true,
- "failed": false,
- "in_manifest": true,
- "apparent_bytes": 696320,
- "actual_bytes": 720896,
- "file_count": 12
- }
- ]
- }
- ],
+ "batches": [{
+ "stamp": "20261118T193001Z",
+ "path": "/srv/kb-backups/rds-logical/20261118T193001Z",
+ "host_path": "/srv/kb-backups/rds-logical/20261118T193001Z",
+ "manifest_state": "ok",
+ "actual_bytes": 4096, "apparent_bytes": 300, "file_count": 3,
+ "sizes_complete": true,
+ "databases": [{
+ "name": "weknora_v090prod",
+ "path": "/srv/kb-backups/rds-logical/20261118T193001Z/weknora_v090prod.dir",
+ "host_path": "/srv/kb-backups/rds-logical/20261118T193001Z/weknora_v090prod.dir",
+ "present": true, "failed": false, "in_manifest": true,
+ "actual_bytes": 4096, "apparent_bytes": 250, "file_count": 2
+ }]
+ }],
"totals": {
- "batch_count": 8,
- "database_count": 0,
- "apparent_bytes": 11141651752,
- "actual_bytes": 12000000000,
- "latest_stamp": "20261118T193001Z",
- "latest_actual_bytes": 1500000000
+ "batch_count": 8, "database_count": 0,
+ "actual_bytes": 12000000000, "apparent_bytes": 11141651752,
+ "latest_stamp": "20261118T193001Z", "latest_actual_bytes": 1500000000,
+ "complete": true
},
- "incomplete_count": 0,
- "skipped": [],
- "truncated": false
+ "incomplete_count": 0, "skipped": [], "truncated": false
}
}
```
-> 示例中的容量、字节与库数只说明字段形状,**不是现场读数**;现场值必须由接口实测。
-> 候选现场已核实的事实只有:8 批、最近 `20261118T193001Z`、含 `weknora_v090prod.dir`。
+> 示例中的容量/字节只说明字段形状,**不是现场读数**;候选现场已核实的事实只有:
+> 8 批、最近 `20261118T193001Z`、含 `weknora_v090prod.dir`。单库 `696320` 是现场核对值,
+> 代码与测试都不写死。
-### 字段语义(页面可逐项核对)
+### 语义与页面行为
-| 字段 | 含义 | 页面行为 |
+| 条件 | API | 页面 |
| --- | --- | --- |
-| `wired` | `BACKUP_HOST_READONLY_ROOT` 已配置 | false 显示“只读盘点未接线”,不显示空批次当“没有备份” |
-| `error` | 目录不存在/不可读 | 显示原因;批次区不伪造数据 |
-| `mount.mount_verified` | 挂载根与容器根盘设备号不同 | false 时容量只作排障,不当主机容量、不判磁盘告警 |
-| `mount.lives_on_container_root` | 与容器根盘同设备 | true 时页面明确“容器根盘·不代表主机磁盘” |
-| `mount.read_only` | `statfs` 标志含 `ST_RDONLY` | false 时提示部署需改 `:ro` |
-| `capacity.*` | 挂载文件系统的实测字节 | 只在 `mount_verified && measured` 时画色带 |
-| `batches[].manifest_state` | `ok` / `missing` / `invalid` | 逐批标注;损坏批仍按目录列子库与占盘 |
-| `batches[].actual_bytes` | 目录内文件 `st_blocks × 512` 合计 | 实际占盘(不是 MANIFEST 表观值) |
-| `databases[].host_path` | 主机上可复制的完整子库目录 | 复制按钮可用;不拼造路径 |
-| `databases[].present` | `.dir` 目录是否真的存在 | false 显示“目录缺失” |
-| `incomplete_count` | `*.incomplete` 目录数 | 仅提示,不计入批次 |
-| `skipped` | 符号链接/非法项/超限 | 显示跳过原因 |
-| `truncated` | 批次或文件数超扫描上限 | 明确“部分结果” |
+| `wired=false` | `metadata.error=未接线`,批次空 | 显示未接线与安装方式,不显示空表当“没备份” |
+| 快照文件缺失/不可读 | `present=false`、`valid=false` | 显示缺失;不使用 SSH 最近一次补历史 |
+| `collected_at` 超过 max age | `fresh=false`、`valid=false`、批次空、容量未测 | 显示陈旧;容量图/占盘未知 |
+| 任一批不完整/权限失败/截断 | `valid=true`、`complete=false`;所有 `*_bytes=null` | 列出路径与清单状态;占盘/容量“未知”,不画色带 |
+| 完整且新鲜 | 批次/子库字节与容量按快照 | 色带、批次、子库路径复制可用 |
+| 批次路径/子库路径与 root 不一致 | `valid=false`,整块拒绝 | 显示校验失败,不展示可疑路径 |
-`apparent_bytes` 优先取 MANIFEST 的 `total_bytes`;没有/损坏清单时退回目录 `st_size` 合计。
-`actual_bytes` 永远是文件系统实际分配,不用表观字节冒充占盘。
+API 的路径校验要求批次路径精确等于 `/`、子库精确等于
+`/.dir`;重复、分隔符、`..`、`.incomplete` 一律拒绝。
-## 2. 28189 候选 API 的最小接线
+## 3. 28189 候选 API 的最小接线
-28189 是 `weknora-test` 上的候选 API(本机通过 SSH 隧道访问)。API 容器增加三项环境变量
-和一条**只读** bind mount;不新增 SSH 权限,也不把备份目录挂成可写:
+API 只挂**采集器输出目录**,不挂备份目录:
```yaml
services:
api:
environment:
- BACKUP_HOST_READONLY_ROOT: /var/lib/knowledge-governance/backup-host/rds-logical
+ BACKUP_HOST_METADATA_PATH: /var/lib/knowledge-governance/backup-host/metadata.json
+ BACKUP_HOST_METADATA_MAX_AGE: 15m
BACKUP_HOST_READONLY_HOST_PATH: /srv/kb-backups/rds-logical
BACKUP_HOST_READONLY_SOURCE: weknora-test:/srv/kb-backups/rds-logical
volumes:
- - /srv/kb-backups/rds-logical:/var/lib/knowledge-governance/backup-host/rds-logical:ro
+ - /var/lib/knowledge-governance/backup-metadata:/var/lib/knowledge-governance/backup-host:ro
```
-要求:
+- `BACKUP_HOST_METADATA_PATH` 与 `BACKUP_HOST_READONLY_HOST_PATH` 必填;`SOURCE` 可省略
+ (用 target + host path 拼)。缺任一拒绝启动,避免“看起来接线”或复制猜的路径。
+- 只挂元数据目录,`uid 1000` 只需要读 `metadata.json`,**不需要**进入 root:root 0700 的备份目录。
+- 采集器由宿主 root/备份所有者运行;不新增 API SSH 权限,不改备份目录权限。
+- 主机 cron 计划仍走 `BACKUP_HOST_SSH_CONFIG/TARGET/SCRIPT_DIR`;与快照独立。
-- 挂载必须带 `:ro`。宿主目录本身不要改成 777;用 ACL/附加组给 API 运行用户(镜像内
- `uid 1000`)只读遍历权限,例如由有权限的运维执行 `setfacl -R -m u:1000:rX /srv/kb-backups/rds-logical`
- (属主机变更,需单独批准;本次未执行)。
-- 只挂 `rds-logical`,不要挂整个 `/srv/kb-backups`,减少可读面。
-- `BACKUP_HOST_READONLY_ROOT` 与 `BACKUP_HOST_READONLY_HOST_PATH` 必填;`SOURCE` 可省略
- (省略时用 `BACKUP_HOST_TARGET + 主机路径` 拼展示来源)。缺 `ROOT` 或 `HOST_PATH` 会拒绝启动,
- 避免“看起来接线”或复制出猜的路径。
-- 主机 cron 计划仍走原有 `BACKUP_HOST_SSH_CONFIG/TARGET/SCRIPT_DIR`;本接口不依赖 SSH。
+### 部署后核验
-### 部署后 30 秒核验(在 API 容器内)
+宿主:
```sh
-ROOT=/var/lib/knowledge-governance/backup-host/rds-logical
-findmnt -T "$ROOT" -o TARGET,SOURCE,FSTYPE,OPTIONS
-stat -c '%d %n' "$ROOT" /
-df -B1 "$ROOT"
-ls -1 "$ROOT" | tail
+ls -l /var/lib/knowledge-governance/backup-metadata/metadata.json
+python3 - <<'PY'
+import json
+d=json.load(open('/var/lib/knowledge-governance/backup-metadata/metadata.json'))
+print(d['schema_version'], d['collected_at'], d['complete'], d['root'], len(d['batches']))
+print(d['batches'][0]['stamp'], [x['name'] for x in d['batches'][0]['databases']][:5])
+PY
```
-期望:`findmnt` 的 SOURCE 是宿主备份盘、OPTIONS 含 `ro`;`stat` 的设备号与 `/` 不同
-(对应 `mount.mount_verified=true`);`df` 与 `capacity` 接近;`ls` 能看到
-`20261118T193001Z`。
+API 容器:
-字段核对:`totals.batch_count=8`、`totals.latest_stamp=20261118T193001Z`、最近批的
-`databases` 含 `weknora_v090prod` 且 `present=true`、`host_path` 以
-`/srv/kb-backups/rds-logical/20261118T193001Z/weknora_v090prod.dir` 结尾。
+```sh
+cat /var/lib/knowledge-governance/backup-host/metadata.json >/dev/null && echo readable
+curl -s http://127.0.0.1:28189/api/v1/backup-schedule/inventory | head -c 400
+```
-若 `wired=false` 或 `error` 提示不可读:先查挂载与读权限,不要用 SSH 的“最近一次”补历史。
+字段核对(以现场为准,示例值不写死):
-## 3. 与主机计划读回的关系
+- `metadata.valid=true`、`fresh=true`;`complete=true` 才允许看占盘与容量。
+- `totals.batch_count=8`;`totals.latest_stamp=20261118T193001Z`。
+- 最近批 `databases` 含 `weknora_v090prod`、`present=true`,`host_path` 指向
+ `/srv/kb-backups/rds-logical/20261118T193001Z/weknora_v090prod.dir`。
+- `capacity.measured=true` 且与宿主 `df -B1 /srv/kb-backups` 一致。
+- 若 `complete=false`:先看 `metadata.error` 里的 permission/遍历错误;**不要**用
+ `latest_actual_bytes` 或部分 `databases[].actual_bytes` 做容量判断(它们应为 null)。
-- `GET /api/v1/backup-schedule/host`:SSH 读 cron/脚本/计划 + MANIFEST 的最近一次摘要。
-- `GET /api/v1/backup-schedule/inventory`:只读挂载读全部批次、子库路径、实际占盘、容量。
+## 4. 与主机计划读回的关系
-前端分别加载,互不掩盖失败:盘点不可读时计划区仍显示读回结果;SSH 连不上时历史区仍可
-展示文件事实。历史批次与子库路径以盘点为准,SSH 的“最近一次”只作历史参考。
+- `/host`:SSH 读 cron/脚本/计划 + MANIFEST 最近一次摘要。
+- `/inventory`:宿主快照读全部批次、子库路径、实际占盘、容量。
-## 4. 现有写路径(本次未改)
+前端分别加载:快照不可用时计划区仍可显示;SSH 连不上时历史区仍可用快照。历史与子库
+路径以快照为准,SSH 的“最近一次”只作历史参考。
+
+## 5. 现有写路径(本次未改)
| 路径 | 写什么 | 权限 |
| --- | --- | --- |
@@ -171,17 +214,15 @@ ls -1 "$ROOT" | tail
| `MarkBackupScheduleApplied` | 下发摘要回写 | 服务内部 |
| `backuphost.Apply / RunNow` | 远端脚本执行 | 服务内部 |
-本接口没有任何写备份目录、删批次、改 cron 的代码路径。
+本接口与采集器没有写备份目录、删批次、改 cron 的代码路径。
-## 5. 还需单独确认的后端写能力
+## 6. 还需单独确认的后端写能力
-以下均**未实现**,需要单独评审与授权,不能在本次只读闭环里顺手打开:
-
-1. 配额 / 磁盘预留的持久化与执行(当前无字段;页面保留占位并标未知)。
-2. 旧批次保留/删除(按天/按月轮转)与删除前审计、可恢复窗口。
-3. 备份目录迁移/切换(涉及主机 cron 参数与历史文件位置)。
-4. 单库备份/单库恢复(现有 `run` 是整批;单库范围需先证明)。
+1. 配额 / 磁盘预留的持久化与执行(当前无字段)。
+2. 旧批次保留/删除与删除前审计、可恢复窗口。
+3. 备份目录迁移/切换。
+4. 单库备份/单库恢复(现有 run 是整批)。
5. 恢复验证执行(`pg_restore` 演练、校验和、结果留档)。
-6. MANIFEST 修复/重建(当前只如实报 missing/invalid)。
-7. 远程挂载/权限变更的自动化(属部署与主机权限,必须人工批准)。
-8. 写操作的角色细分(目前写路径统一管理员;若要“备份操作员”需另立角色)。
\ No newline at end of file
+6. MANIFEST 修复/重建。
+7. 采集器安装/权限变更自动化(属部署与主机权限,必须人工批准)。
+8. 写操作角色细分(目前统一管理员)。
\ No newline at end of file
diff --git a/internal/appconfig/config.go b/internal/appconfig/config.go
index 91e8afb..6bc09bb 100644
--- a/internal/appconfig/config.go
+++ b/internal/appconfig/config.go
@@ -68,9 +68,10 @@ type Config struct {
BackupHostTarget string
BackupHostScriptDir string
BackupHostRoot string
- // BackupHostReadonlyRoot 是容器内只读挂载的 rds-logical 目录(批次/子库/实测容量)。
+ // BackupHostMetadataPath 是容器内挂载的宿主 metadata.json(单次采集器的原子快照)。
// 留空即"未接线";它与上面的 SSH 计划读回是两条独立通道。
- BackupHostReadonlyRoot string
+ BackupHostMetadataPath string
+ BackupHostMetadataMaxAge time.Duration
BackupHostReadonlyHostPath string
BackupHostReadonlySource string
// 版本记录(「版本记录」页):**匿名只读**远端仓库的提交与 tag。来源留空即"未接线"
@@ -189,6 +190,10 @@ func Load(getenv func(string) string) (Config, error) {
return Config{}, errors.New("LIBRARY_EMBEDDING_DIMENSION must be a positive integer")
}
embeddingDimension := int(embeddingDimension64)
+ metadataMaxAge, err := durationOrDefault(strings.TrimSpace(getenv("BACKUP_HOST_METADATA_MAX_AGE")), 15*time.Minute)
+ if err != nil {
+ return Config{}, errors.New("BACKUP_HOST_METADATA_MAX_AGE must be a positive duration")
+ }
config := Config{
DatabaseURL: getenv("DATABASE_URL"),
AppAddr: valueOrDefault(getenv("APP_ADDR"), ":8080"),
@@ -228,7 +233,8 @@ func Load(getenv func(string) string) (Config, error) {
BackupHostTarget: strings.TrimSpace(getenv("BACKUP_HOST_TARGET")),
BackupHostScriptDir: valueOrDefault(strings.TrimSpace(getenv("BACKUP_HOST_SCRIPT_DIR")), "/opt/weknora-test"),
BackupHostRoot: valueOrDefault(strings.TrimSpace(getenv("BACKUP_HOST_ROOT")), "/srv/kb-backups"),
- BackupHostReadonlyRoot: strings.TrimSpace(getenv("BACKUP_HOST_READONLY_ROOT")),
+ BackupHostMetadataPath: strings.TrimSpace(getenv("BACKUP_HOST_METADATA_PATH")),
+ BackupHostMetadataMaxAge: metadataMaxAge,
BackupHostReadonlyHostPath: strings.TrimSpace(getenv("BACKUP_HOST_READONLY_HOST_PATH")),
BackupHostReadonlySource: strings.TrimSpace(getenv("BACKUP_HOST_READONLY_SOURCE")),
VersionHistoryGiteaBaseURL: strings.TrimSpace(getenv("VERSION_HISTORY_GITEA_BASE_URL")),
@@ -526,19 +532,22 @@ func Load(getenv func(string) string) (Config, error) {
return Config{}, errors.New("TEST_AUTO_REVIEW_POLICY must be one of off, internal, all")
}
config.TestAutoReviewPolicy = string(normalizedPolicy)
- // 只读盘点接线与生产发布开关无关:测试栈也可能要先读通历史批次。
- if config.BackupHostReadonlyRoot != "" && !filepath.IsAbs(config.BackupHostReadonlyRoot) {
- return Config{}, errors.New("BACKUP_HOST_READONLY_ROOT must be an absolute path")
+ // 宿主采集器快照接线与生产发布开关无关:测试栈也要先读通历史批次。
+ if config.BackupHostMetadataPath != "" && !filepath.IsAbs(config.BackupHostMetadataPath) {
+ return Config{}, errors.New("BACKUP_HOST_METADATA_PATH must be an absolute path")
}
if config.BackupHostReadonlyHostPath != "" && !filepath.IsAbs(config.BackupHostReadonlyHostPath) {
return Config{}, errors.New("BACKUP_HOST_READONLY_HOST_PATH must be an absolute path")
}
- if config.BackupHostReadonlyRoot != "" && config.BackupHostReadonlyHostPath == "" {
- return Config{}, errors.New("BACKUP_HOST_READONLY_HOST_PATH is required when read-only root is set")
+ if config.BackupHostMetadataPath != "" && config.BackupHostReadonlyHostPath == "" {
+ return Config{}, errors.New("BACKUP_HOST_READONLY_HOST_PATH is required when metadata path is set")
}
- if config.BackupHostReadonlyRoot == "" &&
+ if config.BackupHostMetadataPath == "" &&
(config.BackupHostReadonlyHostPath != "" || config.BackupHostReadonlySource != "") {
- return Config{}, errors.New("BACKUP_HOST_READONLY_ROOT is required when host path/source is set")
+ return Config{}, errors.New("BACKUP_HOST_METADATA_PATH is required when host path/source is set")
+ }
+ if config.BackupHostMetadataMaxAge <= 0 || config.BackupHostMetadataMaxAge > 24*time.Hour {
+ return Config{}, errors.New("BACKUP_HOST_METADATA_MAX_AGE must be between 1s and 24h")
}
for _, value := range []string{config.BackupHostReadonlyHostPath, config.BackupHostReadonlySource} {
if strings.ContainsAny(value, "\x00\r\n") {
diff --git a/internal/appconfig/config_test.go b/internal/appconfig/config_test.go
index 9eba702..39ffbc6 100644
--- a/internal/appconfig/config_test.go
+++ b/internal/appconfig/config_test.go
@@ -65,25 +65,34 @@ func TestLoadValidatesBackupInventoryMount(t *testing.T) {
}
return Load(func(key string) string { return values[key] })
}
- if _, err := load(map[string]string{"BACKUP_HOST_READONLY_ROOT": "relative/path"}); err == nil {
- t.Fatal("relative read-only root must be rejected")
+ if _, err := load(map[string]string{"BACKUP_HOST_METADATA_PATH": "relative/path"}); err == nil {
+ t.Fatal("relative metadata path must be rejected")
}
- if _, err := load(map[string]string{"BACKUP_HOST_READONLY_ROOT": "/var/lib/knowledge-governance/backup-host/rds-logical"}); err == nil {
- t.Fatal("read-only root without host path must be rejected (copy paths must not be guessed)")
+ if _, err := load(map[string]string{"BACKUP_HOST_METADATA_PATH": "/var/lib/knowledge-governance/backup-host/metadata.json"}); err == nil {
+ t.Fatal("metadata path without host root must be rejected (paths must not be guessed)")
}
if _, err := load(map[string]string{"BACKUP_HOST_READONLY_HOST_PATH": "/srv/kb-backups/rds-logical"}); err == nil {
- t.Fatal("host path without read-only root must be rejected")
+ t.Fatal("host path without metadata path must be rejected")
+ }
+ if _, err := load(map[string]string{
+ "BACKUP_HOST_METADATA_PATH": "/var/lib/knowledge-governance/backup-host/metadata.json",
+ "BACKUP_HOST_READONLY_HOST_PATH": "/srv/kb-backups/rds-logical",
+ "BACKUP_HOST_METADATA_MAX_AGE": "nope",
+ }); err == nil {
+ t.Fatal("invalid metadata max age must be rejected")
}
config, err := load(map[string]string{
- "BACKUP_HOST_READONLY_ROOT": "/var/lib/knowledge-governance/backup-host/rds-logical",
+ "BACKUP_HOST_METADATA_PATH": "/var/lib/knowledge-governance/backup-host/metadata.json",
"BACKUP_HOST_READONLY_HOST_PATH": "/srv/kb-backups/rds-logical",
"BACKUP_HOST_READONLY_SOURCE": "weknora-test:/srv/kb-backups/rds-logical",
+ "BACKUP_HOST_METADATA_MAX_AGE": "5m",
})
if err != nil {
- t.Fatalf("valid inventory mount rejected: %v", err)
+ t.Fatalf("valid inventory snapshot config rejected: %v", err)
}
- if config.BackupHostReadonlyRoot == "" || config.BackupHostReadonlyHostPath == "" || config.BackupHostReadonlySource == "" {
- t.Fatalf("inventory mount fields lost: %#v", config)
+ if config.BackupHostMetadataPath == "" || config.BackupHostReadonlyHostPath == "" ||
+ config.BackupHostReadonlySource == "" || config.BackupHostMetadataMaxAge != 5*time.Minute {
+ t.Fatalf("inventory snapshot fields lost: %#v", config)
}
}
diff --git a/internal/backupinventory/inventory.go b/internal/backupinventory/inventory.go
index e3c0c99..75563a4 100644
--- a/internal/backupinventory/inventory.go
+++ b/internal/backupinventory/inventory.go
@@ -1,9 +1,9 @@
-// Package backupinventory 只读盘点备份执行主机上的 rds-logical 备份目录。
+// Package backupinventory 读取**宿主采集器**产出的备份元数据快照。
//
-// 为什么不是再开一条 SSH 命令:盘点要列全部历史批次、子库目录和实际占盘,
-// 在主机上跑 find/du/df 既扩大远端命令面,也无法证明"读的是这块盘"。这里
-// 只接受一个**只读挂载**进来的目录,平台侧没有写路径;容量用 statfs 量,
-// 并比较挂载根与容器根的文件系统设备号,避免把容器根盘冒充主机磁盘。
+// 为什么不在 API 里遍历备份目录:备份目录通常是 root:root 0700,API 容器用户
+// 没有进入权限;容器里遍历只能得到 permission denied 的部分字节,绝不能把部分
+// 计数当成实际占盘。这里只读宿主进程原子写出的 metadata.json,并校验 schema、
+// 批次路径、主机根、时效与完整性。API 不接触备份目录,也不借用 SSH/容器特权。
package backupinventory
import (
@@ -11,45 +11,32 @@ import (
"encoding/json"
"errors"
"fmt"
- "io"
- "io/fs"
"os"
"path"
- "path/filepath"
"sort"
"strings"
- "syscall"
"time"
)
const (
- defaultMaxBatches = 100
- defaultMaxFiles = 200_000
- defaultMaxManifestBytes = 8 << 20
-
- // Linux statfs 的 ST_RDONLY;syscall 包没有导出这个名字。
- statReadOnly = 0x1
+ SchemaVersion = 1
+ defaultMaxAge = 15 * time.Minute
+ defaultMaxBytes = 16 << 20
+ futureTolerance = 2 * time.Minute
+ measurementLabel = "host_collector"
)
type Config struct {
- // Root 是容器内只读挂载点(如 /var/lib/knowledge-governance/backup-host/rds-logical)。
- // 留空即未接线;页面显示原因,不返回空表冒充"没有备份"。
- Root string
- // HostRoot 是给操作者复制/在主机上执行的路径(如 /srv/kb-backups/rds-logical)。
+ // MetadataPath 是 API 容器内挂载的 metadata.json(宿主采集器原子写出)。
+ MetadataPath string
+ // HostRoot 是宿主上的 rds-logical 绝对路径,用于校验快照里的 root/批次路径。
HostRoot string
- // Source 是展示用的来源,如 weknora-test:/srv/kb-backups/rds-logical。
+ // Source 是展示来源;快照里的 source 非空时以快照为准。
Source string
- // MaxBatches/MaxFiles/MaxManifestBytes 防止一个异常目录把 API 拖死。
- MaxBatches int
- MaxFiles int
- MaxManifestBytes int64
-}
-
-type statFS struct {
- Total uint64
- Free uint64
- Available uint64
- ReadOnly bool
+ // MaxAge 超过即视为陈旧,旧快照的批次与容量一律不使用。
+ MaxAge time.Duration
+ // MaxBytes 防止异常大文件拖死 API。
+ MaxBytes int64
}
type ManifestState string
@@ -60,12 +47,32 @@ const (
ManifestInvalid ManifestState = "invalid"
)
+type MetadataInfo struct {
+ Configured bool `json:"configured"`
+ Present bool `json:"present"`
+ Valid bool `json:"valid"`
+ Fresh bool `json:"fresh"`
+ Complete bool `json:"complete"`
+ Path string `json:"path"`
+ CollectedAt string `json:"collected_at"`
+ AgeSeconds int64 `json:"age_seconds"`
+ MaxAgeSeconds int64 `json:"max_age_seconds"`
+ SchemaVersion int `json:"schema_version"`
+ Generation string `json:"generation"`
+ Host string `json:"host"`
+ CollectorVersion string `json:"collector_version"`
+ Error string `json:"error"`
+}
+
type MountInfo struct {
ContainerRoot string `json:"container_root"`
MountVerified bool `json:"mount_verified"`
LivesOnContainerRoot bool `json:"lives_on_container_root"`
ReadOnly bool `json:"read_only"`
Evidence string `json:"evidence"`
+ MountPoint string `json:"mount_point"`
+ Device string `json:"device"`
+ FSType string `json:"fs_type"`
Error string `json:"error,omitempty"`
}
@@ -86,29 +93,29 @@ type Database struct {
Present bool `json:"present"`
Failed bool `json:"failed"`
InManifest bool `json:"in_manifest"`
- ApparentBytes int64 `json:"apparent_bytes"`
- ActualBytes int64 `json:"actual_bytes"`
- FileCount int `json:"file_count"`
+ ApparentBytes *int64 `json:"apparent_bytes"`
+ ActualBytes *int64 `json:"actual_bytes"`
+ FileCount *int `json:"file_count"`
}
type Batch struct {
- Stamp string `json:"stamp"`
- Path string `json:"path"`
- HostPath string `json:"host_path"`
- ManifestState ManifestState `json:"manifest_state"`
- ManifestPath string `json:"manifest_path"`
- ManifestError string `json:"manifest_error,omitempty"`
- Kind string `json:"kind"`
- CreatedAt string `json:"created_at"`
- StartedAt string `json:"started_at"`
- DurationSeconds int `json:"duration_seconds"`
- ManifestBytes int64 `json:"manifest_total_bytes"`
- ApparentBytes int64 `json:"apparent_bytes"`
- ActualBytes int64 `json:"actual_bytes"`
- FileCount int `json:"file_count"`
- SizesComplete bool `json:"sizes_complete"`
- SizesError string `json:"sizes_error,omitempty"`
- Databases []Database `json:"databases"`
+ Stamp string `json:"stamp"`
+ Path string `json:"path"`
+ HostPath string `json:"host_path"`
+ ManifestState ManifestState `json:"manifest_state"`
+ ManifestPath string `json:"manifest_path"`
+ ManifestError string `json:"manifest_error,omitempty"`
+ Kind string `json:"kind"`
+ CreatedAt string `json:"created_at"`
+ StartedAt string `json:"started_at"`
+ DurationSeconds int `json:"duration_seconds"`
+ ManifestTotalBytes *int64 `json:"manifest_total_bytes"`
+ ApparentBytes *int64 `json:"apparent_bytes"`
+ ActualBytes *int64 `json:"actual_bytes"`
+ FileCount *int `json:"file_count"`
+ SizesComplete bool `json:"sizes_complete"`
+ SizesError string `json:"sizes_error,omitempty"`
+ Databases []Database `json:"databases"`
}
type Skipped struct {
@@ -119,152 +126,236 @@ type Skipped struct {
type Totals struct {
BatchCount int `json:"batch_count"`
DatabaseCount int `json:"database_count"`
- ApparentBytes int64 `json:"apparent_bytes"`
- ActualBytes int64 `json:"actual_bytes"`
+ ApparentBytes *int64 `json:"apparent_bytes"`
+ ActualBytes *int64 `json:"actual_bytes"`
LatestStamp string `json:"latest_stamp"`
- LatestActualBytes int64 `json:"latest_actual_bytes"`
+ LatestActualBytes *int64 `json:"latest_actual_bytes"`
+ Complete bool `json:"complete"`
}
type Snapshot struct {
- Wired bool `json:"wired"`
- Root string `json:"root"`
- HostRoot string `json:"host_root"`
- Source string `json:"source"`
- ObservedAt string `json:"observed_at"`
- Error string `json:"error,omitempty"`
- Mount MountInfo `json:"mount"`
- Capacity Capacity `json:"capacity"`
- Batches []Batch `json:"batches"`
- Totals Totals `json:"totals"`
- IncompleteCount int `json:"incomplete_count"`
- Skipped []Skipped `json:"skipped"`
- Truncated bool `json:"truncated"`
+ Wired bool `json:"wired"`
+ Metadata MetadataInfo `json:"metadata"`
+ Root string `json:"root"`
+ HostRoot string `json:"host_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"`
+ Batches []Batch `json:"batches"`
+ Totals Totals `json:"totals"`
+ IncompleteCount int `json:"incomplete_count"`
+ Skipped []Skipped `json:"skipped"`
+ Truncated bool `json:"truncated"`
}
type Reader struct {
config Config
now func() time.Time
- statfs func(string) (statFS, error)
- device func(string) (uint64, error)
+ read func(string) ([]byte, error)
}
func New(config Config) *Reader {
- if config.MaxBatches <= 0 {
- config.MaxBatches = defaultMaxBatches
+ if config.MaxAge <= 0 {
+ config.MaxAge = defaultMaxAge
}
- if config.MaxFiles <= 0 {
- config.MaxFiles = defaultMaxFiles
+ if config.MaxBytes <= 0 {
+ config.MaxBytes = defaultMaxBytes
}
- if config.MaxManifestBytes <= 0 {
- config.MaxManifestBytes = defaultMaxManifestBytes
- }
- return &Reader{config: config, now: time.Now, statfs: defaultStatFS, device: defaultDevice}
+ return &Reader{config: config, now: time.Now, read: os.ReadFile}
}
func (r *Reader) Available() bool {
- return r != nil && strings.TrimSpace(r.config.Root) != ""
+ return r != nil && strings.TrimSpace(r.config.MetadataPath) != ""
}
-// Snapshot 永远返回可投影的结构:未接线、目录不可读、清单损坏都写在字段里,
-// 由页面区分,不把任一种情况变成 500 或"没有备份"。
+// ---- 宿主快照文件(collector 的输出;只读、字段可验证) ----
+
+type metadata struct {
+ SchemaVersion int `json:"schema_version"`
+ CollectorVersion string `json:"collector_version"`
+ Generation string `json:"generation"`
+ CollectedAt string `json:"collected_at"`
+ Host string `json:"host"`
+ Source string `json:"source"`
+ Root string `json:"root"`
+ Complete bool `json:"complete"`
+ Errors []string `json:"errors"`
+ Filesystem metadataFilesystem `json:"filesystem"`
+ IncompleteCount int `json:"incomplete_count"`
+ Skipped []Skipped `json:"skipped"`
+ Truncated bool `json:"truncated"`
+ Batches []metadataBatch `json:"batches"`
+}
+
+type metadataFilesystem struct {
+ MountPoint string `json:"mount_point"`
+ MountSource string `json:"mount_source"`
+ FSType string `json:"fs_type"`
+ ReadOnly bool `json:"read_only"`
+ TotalBytes int64 `json:"total_bytes"`
+ FreeBytes int64 `json:"free_bytes"`
+ AvailableBytes int64 `json:"available_bytes"`
+}
+
+type metadataBatch struct {
+ Stamp string `json:"stamp"`
+ Path string `json:"path"`
+ ManifestState string `json:"manifest_state"`
+ ManifestError string `json:"manifest_error"`
+ Kind string `json:"kind"`
+ CreatedAt string `json:"created_at"`
+ StartedAt string `json:"started_at"`
+ DurationSeconds int `json:"duration_seconds"`
+ ManifestTotalBytes *int64 `json:"manifest_total_bytes"`
+ Complete bool `json:"complete"`
+ Errors []string `json:"errors"`
+ ApparentBytes *int64 `json:"apparent_bytes"`
+ ActualBytes *int64 `json:"actual_bytes"`
+ FileCount *int `json:"file_count"`
+ Databases []metadataDatabase `json:"databases"`
+}
+
+type metadataDatabase struct {
+ Name string `json:"name"`
+ DirName string `json:"dir_name"`
+ Path string `json:"path"`
+ Present bool `json:"present"`
+ Failed bool `json:"failed"`
+ InManifest bool `json:"in_manifest"`
+ ApparentBytes *int64 `json:"apparent_bytes"`
+ ActualBytes *int64 `json:"actual_bytes"`
+ FileCount *int `json:"file_count"`
+}
+
+// Snapshot 只返回可验证的事实:陈旧/缺失/不完整一律不给批次字节与容量。
func (r *Reader) Snapshot(ctx context.Context) Snapshot {
snapshot := Snapshot{
- Wired: r.Available(),
- HostRoot: r.config.HostRoot,
- Source: r.config.Source,
- Batches: []Batch{},
- Skipped: []Skipped{},
+ Wired: r.Available(),
+ Measurement: measurementLabel,
+ Batches: []Batch{},
+ Skipped: []Skipped{},
+ ObservedAt: r.observedAt(),
+ Metadata: MetadataInfo{
+ Configured: r.Available(),
+ MaxAgeSeconds: int64(r.config.MaxAge / time.Second),
+ },
}
if r == nil || !r.Available() {
- snapshot.Error = "只读盘点未接线(BACKUP_HOST_READONLY_ROOT 未设置)"
- snapshot.ObservedAt = r.observedAt()
+ snapshot.Metadata.Error = "元数据快照未接线(BACKUP_HOST_METADATA_PATH 未设置)"
+ snapshot.Error = snapshot.Metadata.Error
return snapshot
}
- snapshot.ObservedAt = r.observedAt()
- snapshot.Root = filepath.Clean(r.config.Root)
- resolved, err := filepath.EvalSymlinks(snapshot.Root)
+ snapshot.Metadata.Path = r.config.MetadataPath
+ snapshot.HostRoot = r.config.HostRoot
+ snapshot.Source = r.config.Source
+ if ctx.Err() != nil {
+ snapshot.Metadata.Error = "读取被取消:" + ctx.Err().Error()
+ snapshot.Error = snapshot.Metadata.Error
+ return snapshot
+ }
+ raw, err := r.read(r.config.MetadataPath)
if err != nil {
- snapshot.Error = "只读挂载不可读:" + err.Error()
- snapshot.Capacity.Error = snapshot.Error
- return snapshot
- }
- info, err := os.Stat(resolved)
- if err != nil {
- snapshot.Error = "只读挂载不可读:" + err.Error()
- snapshot.Capacity.Error = snapshot.Error
- return snapshot
- }
- if !info.IsDir() {
- snapshot.Error = "只读挂载不是目录:" + resolved
- snapshot.Capacity.Error = snapshot.Error
- return snapshot
- }
- snapshot.Root = resolved
- snapshot.Mount = r.mountInfo(resolved)
- if !snapshot.Mount.MountVerified {
- reason := snapshot.Mount.Evidence
- if snapshot.Mount.Error != "" {
- reason = snapshot.Mount.Error
+ if errors.Is(err, os.ErrNotExist) {
+ snapshot.Metadata.Error = "宿主元数据快照不存在:需要先运行 collect_backup_metadata.py"
+ } else {
+ snapshot.Metadata.Error = "宿主元数据快照不可读:" + err.Error()
}
- snapshot.Capacity = Capacity{Error: "无法证明只读目录位于独立挂载:" + reason}
+ snapshot.Error = snapshot.Metadata.Error
+ return snapshot
+ }
+ snapshot.Metadata.Present = true
+ if int64(len(raw)) > r.config.MaxBytes {
+ return invalid(snapshot, fmt.Sprintf("元数据快照超过 %d 字节读取上限", r.config.MaxBytes))
+ }
+ var file metadata
+ if err := json.Unmarshal(raw, &file); err != nil {
+ return invalid(snapshot, "元数据快照无法解析:"+err.Error())
+ }
+ snapshot.Metadata.SchemaVersion = file.SchemaVersion
+ snapshot.Metadata.Generation = file.Generation
+ snapshot.Metadata.Host = file.Host
+ snapshot.Metadata.CollectorVersion = file.CollectorVersion
+ snapshot.Metadata.CollectedAt = file.CollectedAt
+ snapshot.Metadata.Complete = file.Complete
+ if file.Source != "" {
+ snapshot.Source = file.Source
+ }
+ if file.SchemaVersion != SchemaVersion {
+ return invalid(snapshot, fmt.Sprintf("元数据 schema_version=%d,API 只支持 %d", file.SchemaVersion, SchemaVersion))
+ }
+ collectedAt, err := time.Parse(time.RFC3339, file.CollectedAt)
+ if err != nil {
+ return invalid(snapshot, "元数据 collected_at 非法:"+file.CollectedAt)
+ }
+ age := r.now().UTC().Sub(collectedAt.UTC())
+ if age < -futureTolerance {
+ return invalid(snapshot, "元数据 collected_at 在未来,拒绝使用")
+ }
+ snapshot.Metadata.AgeSeconds = int64(age / time.Second)
+ if age > r.config.MaxAge {
+ snapshot.Metadata.Fresh = false
+ return invalid(snapshot, fmt.Sprintf("元数据已陈旧:采集于 %s,超过 %s", file.CollectedAt, r.config.MaxAge))
+ }
+ snapshot.Metadata.Fresh = true
+ if strings.TrimSpace(r.config.HostRoot) == "" {
+ return invalid(snapshot, "宿主根路径未配置:无法校验批次路径")
+ }
+ expectedRoot := path.Clean(strings.TrimSpace(r.config.HostRoot))
+ snapshot.HostRoot = expectedRoot
+ root := strings.TrimSpace(file.Root)
+ if !path.IsAbs(root) || path.Clean(root) != root {
+ return invalid(snapshot, "元数据 root 不是规范绝对路径:"+root)
+ }
+ if root != expectedRoot {
+ return invalid(snapshot, fmt.Sprintf("元数据 root=%s 与配置 %s 不一致", root, expectedRoot))
+ }
+ snapshot.Root = root
+ if err := validateBatches(root, file.Batches); err != nil {
+ return invalid(snapshot, err.Error())
+ }
+ snapshot.Metadata.Valid = true
+ snapshot.IncompleteCount = file.IncompleteCount
+ snapshot.Skipped = append(snapshot.Skipped, file.Skipped...)
+ snapshot.Truncated = file.Truncated
+ snapshot.Mount = MountInfo{
+ Evidence: "宿主采集器上报:" + file.Host,
+ MountPoint: file.Filesystem.MountPoint,
+ Device: file.Filesystem.MountSource,
+ FSType: file.Filesystem.FSType,
+ ReadOnly: file.Filesystem.ReadOnly,
+ }
+ if file.Filesystem.MountPoint == "" || !path.IsAbs(file.Filesystem.MountPoint) {
+ snapshot.Mount.Error = "宿主采集器没有给出文件系统挂载点"
+ } else if root != file.Filesystem.MountPoint && !strings.HasPrefix(root, strings.TrimSuffix(file.Filesystem.MountPoint, "/")+"/") {
+ snapshot.Mount.Error = "批次根不在采集器上报的挂载点下"
} else {
- snapshot.Capacity = r.capacity(resolved)
+ snapshot.Mount.MountVerified = true
+ snapshot.Mount.Evidence = fmt.Sprintf("宿主采集器:%s 挂在 %s(%s),API 不遍历备份目录",
+ file.Filesystem.MountSource, file.Filesystem.MountPoint, file.Filesystem.FSType)
}
- entries, err := os.ReadDir(resolved)
- if err != nil {
- snapshot.Error = "无法列出备份目录:" + err.Error()
+ // 快照不完整/截断:路径与清单状态可展示,但所有字节与容量一律未知,
+ // 绝不用部分 counts 或完整批次的局部字节拼总量。
+ complete := file.Complete && !file.Truncated && snapshot.Mount.MountVerified && allBatchesComplete(file.Batches)
+ if !complete {
+ snapshot.Metadata.Complete = false
+ snapshot.Metadata.Error = incompleteReason(file)
+ snapshot.Capacity = Capacity{Error: "采集快照不完整:容量与占盘未知"}
+ snapshot.Mount.MountVerified = false
+ snapshot.Mount.Error = "采集快照不完整,不能据此判定文件系统与占盘"
+ snapshot.Batches = projectBatches(root, file.Batches, false)
+ snapshot.Totals = totals(snapshot.Batches, false)
+ snapshot.Error = ""
return snapshot
}
- dirs := make([]string, 0, len(entries))
- for _, entry := range entries {
- name := entry.Name()
- if strings.HasSuffix(name, ".incomplete") {
- snapshot.IncompleteCount++
- continue
- }
- if name == "" || strings.ContainsAny(name, `/\`) {
- snapshot.Skipped = append(snapshot.Skipped, Skipped{Name: name, Reason: "目录名不合法"})
- continue
- }
- if entry.Type()&os.ModeSymlink != 0 {
- snapshot.Skipped = append(snapshot.Skipped, Skipped{Name: name, Reason: "符号链接不跟随"})
- continue
- }
- if !entry.IsDir() {
- snapshot.Skipped = append(snapshot.Skipped, Skipped{Name: name, Reason: "不是批次目录"})
- continue
- }
- dirs = append(dirs, name)
- }
- sort.Sort(sort.Reverse(sort.StringSlice(dirs)))
- if len(dirs) > r.config.MaxBatches {
- dirs = dirs[:r.config.MaxBatches]
- snapshot.Truncated = true
- }
- for _, name := range dirs {
- if ctx.Err() != nil {
- snapshot.Error = "读取被取消:" + ctx.Err().Error()
- break
- }
- batch, reason, walkTruncated := r.readBatch(ctx, resolved, name)
- if reason != "" {
- snapshot.Skipped = append(snapshot.Skipped, Skipped{Name: name, Reason: reason})
- continue
- }
- if walkTruncated {
- snapshot.Truncated = true
- }
- snapshot.Batches = append(snapshot.Batches, batch)
- snapshot.Totals.ApparentBytes += batch.ApparentBytes
- snapshot.Totals.ActualBytes += batch.ActualBytes
- snapshot.Totals.DatabaseCount += len(batch.Databases)
- }
- snapshot.Totals.BatchCount = len(snapshot.Batches)
- if len(snapshot.Batches) > 0 {
- snapshot.Totals.LatestStamp = snapshot.Batches[0].Stamp
- snapshot.Totals.LatestActualBytes = snapshot.Batches[0].ActualBytes
- }
+
+ snapshot.Metadata.Complete = true
+ snapshot.Capacity = projectCapacity(file.Filesystem)
+ snapshot.Batches = projectBatches(root, file.Batches, true)
+ snapshot.Totals = totals(snapshot.Batches, true)
return snapshot
}
@@ -275,318 +366,197 @@ func (r *Reader) observedAt() string {
return r.now().UTC().Format(time.RFC3339)
}
-func (r *Reader) mountInfo(root string) MountInfo {
- info := MountInfo{ContainerRoot: "/"}
- rootDevice, err := r.device(root)
- if err != nil {
- info.Error = "无法读取挂载设备号:" + err.Error()
- info.Evidence = "无法证明挂载与容器根盘分离"
- return info
- }
- containerDevice, err := r.device("/")
- if err != nil {
- info.Error = "无法读取容器根盘设备号:" + err.Error()
- info.Evidence = "无法证明挂载与容器根盘分离"
- return info
- }
- info.LivesOnContainerRoot = rootDevice == containerDevice
- info.MountVerified = !info.LivesOnContainerRoot
- if stats, statErr := r.statfs(root); statErr == nil {
- info.ReadOnly = stats.ReadOnly
- }
- if info.MountVerified {
- info.Evidence = fmt.Sprintf("挂载设备 %d 与容器根盘 %d 不同:容量按挂载文件系统计量", rootDevice, containerDevice)
- } else {
- info.Evidence = fmt.Sprintf("挂载设备与容器根盘相同(%d):容量不代表备份主机磁盘", rootDevice)
- }
- return info
+func invalid(snapshot Snapshot, reason string) Snapshot {
+ snapshot.Metadata.Valid = false
+ snapshot.Metadata.Complete = false
+ snapshot.Metadata.Error = reason
+ snapshot.Error = reason
+ snapshot.Batches = []Batch{}
+ snapshot.Capacity = Capacity{Error: reason}
+ snapshot.Totals = Totals{}
+ return snapshot
}
-func (r *Reader) capacity(root string) Capacity {
- stats, err := r.statfs(root)
- if err != nil {
- return Capacity{Error: "无法读取文件系统容量:" + err.Error()}
+func incompleteReason(file metadata) string {
+ if len(file.Errors) > 0 {
+ return "采集不完整:" + strings.Join(limit(file.Errors, 3), ";")
}
- used := uint64(0)
- if stats.Total > stats.Free {
- used = stats.Total - stats.Free
+ for _, batch := range file.Batches {
+ if len(batch.Errors) > 0 {
+ return "采集不完整:" + strings.Join(limit(batch.Errors, 3), ";")
+ }
+ }
+ return "采集不完整:存在无法遍历/统计的目录,占盘与容量未知"
+}
+
+func limit(items []string, n int) []string {
+ if len(items) <= n {
+ return items
+ }
+ return items[:n]
+}
+
+func allBatchesComplete(batches []metadataBatch) bool {
+ for _, batch := range batches {
+ if !batch.Complete || batch.ActualBytes == nil || batch.ApparentBytes == nil || batch.FileCount == nil {
+ return false
+ }
+ for _, database := range batch.Databases {
+ if database.ActualBytes == nil || database.ApparentBytes == nil || database.FileCount == nil {
+ return false
+ }
+ }
+ }
+ return true
+}
+
+// 校验的是"快照里的路径能否被安全地当成这台主机的批次/子库":
+// 根必须精确匹配配置,批次必须精确等于 root/,子库必须精确等于
+// batch/.dir,且不允许重复、分隔符、.incomplete。
+func validateBatches(root string, batches []metadataBatch) error {
+ seen := map[string]bool{}
+ for _, batch := range batches {
+ stamp := strings.TrimSpace(batch.Stamp)
+ if err := safeSegment(stamp); err != nil {
+ return fmt.Errorf("批次名不合法:%q(%v)", stamp, err)
+ }
+ if strings.HasSuffix(stamp, ".incomplete") {
+ return fmt.Errorf("批次 %q 是未完成目录,不应进入快照", stamp)
+ }
+ if seen[stamp] {
+ return fmt.Errorf("批次 %q 重复", stamp)
+ }
+ seen[stamp] = true
+ expected := path.Join(root, stamp)
+ if batch.Path != expected || !path.IsAbs(batch.Path) {
+ return fmt.Errorf("批次 %q 路径 %q 不等于 %q", stamp, batch.Path, expected)
+ }
+ switch ManifestState(batch.ManifestState) {
+ case ManifestOK, ManifestMissing, ManifestInvalid:
+ default:
+ return fmt.Errorf("批次 %q 的 manifest_state 不认识:%q", stamp, batch.ManifestState)
+ }
+ databaseSeen := map[string]bool{}
+ for _, database := range batch.Databases {
+ name := strings.TrimSpace(database.Name)
+ if err := safeSegment(name); err != nil {
+ return fmt.Errorf("批次 %q 子库名不合法:%q", stamp, name)
+ }
+ if databaseSeen[name] {
+ return fmt.Errorf("批次 %q 子库 %q 重复", stamp, name)
+ }
+ databaseSeen[name] = true
+ expectedDir := path.Join(expected, name+".dir")
+ if database.DirName != name+".dir" || database.Path != expectedDir || !path.IsAbs(database.Path) {
+ return fmt.Errorf("批次 %q 子库 %q 路径不合法:%q", stamp, name, database.Path)
+ }
+ }
+ }
+ return nil
+}
+
+func safeSegment(value string) error {
+ if value == "" || value == "." || value == ".." {
+ return errors.New("空值或相对路径")
+ }
+ for _, r := range value {
+ if r == '/' || r == '\\' || r == 0 || r == '\n' || r == '\r' {
+ return errors.New("包含路径分隔符或控制字符")
+ }
+ }
+ return nil
+}
+
+func projectBatches(root string, batches []metadataBatch, complete bool) []Batch {
+ result := make([]Batch, 0, len(batches))
+ for _, batch := range batches {
+ item := Batch{
+ Stamp: batch.Stamp,
+ Path: path.Join(root, batch.Stamp),
+ HostPath: path.Join(root, batch.Stamp),
+ ManifestState: ManifestState(batch.ManifestState),
+ ManifestPath: path.Join(root, batch.Stamp, "MANIFEST.json"),
+ ManifestError: batch.ManifestError,
+ Kind: batch.Kind,
+ CreatedAt: batch.CreatedAt,
+ StartedAt: batch.StartedAt,
+ DurationSeconds: batch.DurationSeconds,
+ SizesComplete: complete && batch.Complete,
+ Databases: []Database{},
+ }
+ if complete && batch.Complete {
+ item.ManifestTotalBytes = batch.ManifestTotalBytes
+ item.ApparentBytes = batch.ApparentBytes
+ item.ActualBytes = batch.ActualBytes
+ item.FileCount = batch.FileCount
+ }
+ for _, database := range batch.Databases {
+ entry := Database{
+ Name: database.Name,
+ DirName: database.DirName,
+ Path: path.Join(root, batch.Stamp, database.DirName),
+ HostPath: path.Join(root, batch.Stamp, database.DirName),
+ Present: database.Present,
+ Failed: database.Failed,
+ InManifest: database.InManifest,
+ }
+ if complete && batch.Complete {
+ entry.ApparentBytes = database.ApparentBytes
+ entry.ActualBytes = database.ActualBytes
+ entry.FileCount = database.FileCount
+ }
+ item.Databases = append(item.Databases, entry)
+ }
+ if !item.SizesComplete {
+ item.SizesError = "宿主采集器该项不完整,占盘未知"
+ }
+ result = append(result, item)
+ }
+ sort.Slice(result, func(i, j int) bool { return result[i].Stamp > result[j].Stamp })
+ return result
+}
+
+func totals(batches []Batch, complete bool) Totals {
+ result := Totals{BatchCount: len(batches), Complete: complete}
+ if len(batches) > 0 {
+ result.LatestStamp = batches[0].Stamp
+ }
+ for _, batch := range batches {
+ result.DatabaseCount += len(batch.Databases)
+ }
+ if !complete {
+ return result
+ }
+ var apparent, actual int64
+ for _, batch := range batches {
+ if batch.ApparentBytes != nil {
+ apparent += *batch.ApparentBytes
+ }
+ if batch.ActualBytes != nil {
+ actual += *batch.ActualBytes
+ }
+ }
+ result.ApparentBytes = &apparent
+ result.ActualBytes = &actual
+ if len(batches) > 0 {
+ result.LatestActualBytes = batches[0].ActualBytes
+ }
+ return result
+}
+
+func projectCapacity(filesystem metadataFilesystem) Capacity {
+ if filesystem.TotalBytes <= 0 {
+ return Capacity{Error: "宿主采集器没有给出文件系统容量"}
+ }
+ used := filesystem.TotalBytes - filesystem.FreeBytes
+ if used < 0 {
+ used = 0
}
return Capacity{
Measured: true,
- TotalBytes: int64(stats.Total),
- FreeBytes: int64(stats.Free),
- AvailableBytes: int64(stats.Available),
- UsedBytes: int64(used),
+ TotalBytes: filesystem.TotalBytes,
+ FreeBytes: filesystem.FreeBytes,
+ AvailableBytes: filesystem.AvailableBytes,
+ UsedBytes: used,
}
}
-
-type manifest struct {
- Kind string `json:"kind"`
- CreatedAt string `json:"created_at"`
- StartedAt string `json:"started_at"`
- DurationSeconds int `json:"duration_seconds"`
- Databases []string `json:"databases"`
- FailedDatabases []string `json:"failed_databases"`
- TotalBytes int64 `json:"total_bytes"`
- Files []struct {
- File string `json:"file"`
- Bytes int64 `json:"bytes"`
- } `json:"files"`
-}
-
-type sizes struct {
- apparent int64
- actual int64
- files int
-}
-
-func (value *sizes) add(other sizes) {
- value.apparent += other.apparent
- value.actual += other.actual
- value.files += other.files
-}
-
-func (r *Reader) readBatch(ctx context.Context, root, name string) (Batch, string, bool) {
- fullPath := filepath.Join(root, name)
- resolved, err := filepath.EvalSymlinks(fullPath)
- if err != nil {
- return Batch{}, "无法解析批次目录:" + err.Error(), false
- }
- if !within(root, resolved) {
- return Batch{}, "批次目录指向只读挂载之外", false
- }
- batch := Batch{
- Stamp: name,
- Path: resolved,
- HostPath: joinHostPath(r.config.HostRoot, name),
- ManifestPath: filepath.Join(resolved, "MANIFEST.json"),
- ManifestState: ManifestMissing,
- Databases: []Database{},
- SizesComplete: true,
- }
-
- var parsed manifest
- state, manifestErr := readManifest(batch.ManifestPath, r.config.MaxManifestBytes, &parsed)
- batch.ManifestState = state
- batch.ManifestError = manifestErr
- if state == ManifestOK {
- batch.Kind = parsed.Kind
- batch.CreatedAt = parsed.CreatedAt
- batch.StartedAt = parsed.StartedAt
- batch.DurationSeconds = parsed.DurationSeconds
- batch.ManifestBytes = parsed.TotalBytes
- }
-
- walked, byTop, walkErr, truncated := r.walkBatch(ctx, resolved)
- batch.ApparentBytes = walked.apparent
- batch.ActualBytes = walked.actual
- batch.FileCount = walked.files
- if walkErr != nil {
- batch.SizesComplete = false
- batch.SizesError = walkErr.Error()
- }
- if state == ManifestOK && parsed.TotalBytes > 0 {
- batch.ApparentBytes = parsed.TotalBytes
- }
-
- manifestSizes := map[string]sizes{}
- if state == ManifestOK {
- for _, file := range parsed.Files {
- clean := path.Clean(filepath.ToSlash(file.File))
- if clean == "." || strings.HasPrefix(clean, "../") || path.IsAbs(clean) {
- continue
- }
- top := strings.SplitN(clean, "/", 2)[0]
- if !strings.HasSuffix(top, ".dir") {
- continue
- }
- entry := manifestSizes[top]
- entry.apparent += file.Bytes
- entry.files++
- manifestSizes[top] = entry
- }
- }
-
- seen := map[string]bool{}
- failed := map[string]bool{}
- for _, db := range parsed.FailedDatabases {
- failed[db] = true
- }
- appendDatabase := func(db string) {
- if db == "" || seen[db] {
- return
- }
- seen[db] = true
- dirName := db + ".dir"
- containerDir := filepath.Join(resolved, dirName)
- info, statErr := os.Stat(containerDir)
- present := statErr == nil && info.IsDir()
- apparent := sizes{}
- if entry, ok := manifestSizes[dirName]; ok {
- apparent = entry
- } else if walkedEntry, ok := byTop[dirName]; ok {
- apparent = walkedEntry
- }
- batch.Databases = append(batch.Databases, Database{
- Name: db,
- DirName: dirName,
- Path: containerDir,
- HostPath: joinHostPath(batch.HostPath, dirName),
- Present: present,
- Failed: failed[db],
- InManifest: contains(parsed.Databases, db),
- ApparentBytes: apparent.apparent,
- ActualBytes: byTop[dirName].actual,
- FileCount: apparent.files,
- })
- }
- for _, db := range parsed.Databases {
- appendDatabase(db)
- }
- dirNames := make([]string, 0, len(byTop))
- for top := range byTop {
- if strings.HasSuffix(top, ".dir") {
- dirNames = append(dirNames, top)
- }
- }
- sort.Strings(dirNames)
- for _, top := range dirNames {
- appendDatabase(strings.TrimSuffix(top, ".dir"))
- }
- return batch, "", truncated
-}
-
-func (r *Reader) walkBatch(ctx context.Context, batchPath string) (sizes, map[string]sizes, error, bool) {
- total := sizes{}
- byTop := map[string]sizes{}
- scanned := 0
- truncated := false
- err := filepath.WalkDir(batchPath, func(current string, entry fs.DirEntry, walkErr error) error {
- if ctx.Err() != nil {
- return ctx.Err()
- }
- if walkErr != nil {
- return walkErr
- }
- if current == batchPath {
- return nil
- }
- if entry.Type()&os.ModeSymlink != 0 {
- if entry.IsDir() {
- return filepath.SkipDir
- }
- return nil
- }
- if entry.IsDir() {
- return nil
- }
- if scanned >= r.config.MaxFiles {
- truncated = true
- return errStopWalk
- }
- info, err := entry.Info()
- if err != nil {
- return nil
- }
- relative, err := filepath.Rel(batchPath, current)
- if err != nil {
- return nil
- }
- top := strings.SplitN(filepath.ToSlash(relative), "/", 2)[0]
- fileSize := sizes{apparent: info.Size(), actual: actualBytes(info), files: 1}
- total.add(fileSize)
- entrySizes := byTop[top]
- entrySizes.add(fileSize)
- byTop[top] = entrySizes
- scanned++
- return nil
- })
- if errors.Is(err, errStopWalk) {
- err = nil
- }
- if err != nil {
- return total, byTop, err, truncated
- }
- return total, byTop, nil, truncated
-}
-
-var errStopWalk = errors.New("file scan limit reached")
-
-func readManifest(filename string, maxBytes int64, parsed *manifest) (ManifestState, string) {
- file, err := os.Open(filename)
- if err != nil {
- if os.IsNotExist(err) {
- return ManifestMissing, ""
- }
- return ManifestInvalid, err.Error()
- }
- defer file.Close()
- raw, err := io.ReadAll(io.LimitReader(file, maxBytes+1))
- if err != nil {
- return ManifestInvalid, err.Error()
- }
- if int64(len(raw)) > maxBytes {
- return ManifestInvalid, fmt.Sprintf("清单超过 %d 字节读取上限", maxBytes)
- }
- if err := json.Unmarshal(raw, parsed); err != nil {
- return ManifestInvalid, "清单无法解析:" + err.Error()
- }
- return ManifestOK, ""
-}
-
-func within(root, target string) bool {
- relative, err := filepath.Rel(root, target)
- if err != nil {
- return false
- }
- return relative != ".." && !strings.HasPrefix(relative, ".."+string(os.PathSeparator))
-}
-
-func joinHostPath(root, name string) string {
- if strings.TrimSpace(root) == "" {
- return ""
- }
- return path.Join(filepath.ToSlash(root), name)
-}
-
-func contains(list []string, value string) bool {
- for _, item := range list {
- if item == value {
- return true
- }
- }
- return false
-}
-
-func actualBytes(info fs.FileInfo) int64 {
- if stat, ok := info.Sys().(*syscall.Stat_t); ok {
- return int64(stat.Blocks) * 512
- }
- return info.Size()
-}
-
-func defaultStatFS(root string) (statFS, error) {
- var stats syscall.Statfs_t
- if err := syscall.Statfs(root, &stats); err != nil {
- return statFS{}, err
- }
- blockSize := uint64(stats.Bsize)
- return statFS{
- Total: stats.Blocks * blockSize,
- Free: stats.Bfree * blockSize,
- Available: stats.Bavail * blockSize,
- ReadOnly: stats.Flags&statReadOnly != 0,
- }, nil
-}
-
-func defaultDevice(root string) (uint64, error) {
- info, err := os.Stat(root)
- if err != nil {
- return 0, err
- }
- stat, ok := info.Sys().(*syscall.Stat_t)
- if !ok {
- return 0, fmt.Errorf("无法读取 %s 的设备号", root)
- }
- return uint64(stat.Dev), nil
-}
diff --git a/internal/backupinventory/inventory_test.go b/internal/backupinventory/inventory_test.go
index 6fa3cc1..216f5d2 100644
--- a/internal/backupinventory/inventory_test.go
+++ b/internal/backupinventory/inventory_test.go
@@ -2,152 +2,253 @@ package backupinventory
import (
"context"
+ "encoding/json"
"os"
+ "os/exec"
"path/filepath"
"strings"
- "syscall"
"testing"
+ "time"
)
-func writeFile(t *testing.T, filename string, content string) {
- t.Helper()
- if err := os.MkdirAll(filepath.Dir(filename), 0o755); err != nil {
- t.Fatal(err)
- }
- if err := os.WriteFile(filename, []byte(content), 0o644); err != nil {
- t.Fatal(err)
+const hostRoot = "/srv/kb-backups/rds-logical"
+
+func int64p(value int64) *int64 { return &value }
+func intp(value int) *int { return &value }
+
+func validMetadata() metadata {
+ latest := hostRoot + "/20261118T193001Z"
+ broken := hostRoot + "/20261117T193001Z"
+ without := hostRoot + "/20261116T193001Z"
+ return metadata{
+ SchemaVersion: SchemaVersion,
+ CollectorVersion: "backup-metadata/1",
+ Generation: "20261120T010000Z-abc123",
+ CollectedAt: "2026-11-20T01:00:00Z",
+ Host: "weknora-test",
+ Source: "weknora-test:" + hostRoot,
+ Root: hostRoot,
+ Complete: true,
+ Errors: []string{},
+ Filesystem: metadataFilesystem{
+ MountPoint: "/srv/kb-backups",
+ MountSource: "/dev/sdb1",
+ FSType: "ext4",
+ ReadOnly: false,
+ TotalBytes: 1000,
+ FreeBytes: 400,
+ AvailableBytes: 350,
+ },
+ IncompleteCount: 1,
+ Skipped: []Skipped{{Name: "notes.txt", Reason: "不是批次目录"}},
+ Batches: []metadataBatch{
+ {
+ Stamp: "20261118T193001Z",
+ Path: latest,
+ ManifestState: "ok",
+ Kind: "rds-logical-backup",
+ CreatedAt: "20261118T193001Z",
+ StartedAt: "20261118T192908Z",
+ DurationSeconds: 53,
+ ManifestTotalBytes: int64p(300),
+ Complete: true,
+ ApparentBytes: int64p(300),
+ ActualBytes: int64p(4096),
+ FileCount: intp(3),
+ Databases: []metadataDatabase{
+ {
+ Name: "weknora_v090prod", DirName: "weknora_v090prod.dir",
+ Path: latest + "/weknora_v090prod.dir", Present: true, InManifest: true,
+ ApparentBytes: int64p(250), ActualBytes: int64p(4096), FileCount: intp(2),
+ },
+ {
+ Name: "weknora_test", DirName: "weknora_test.dir",
+ Path: latest + "/weknora_test.dir", Present: true, InManifest: true, Failed: true,
+ ApparentBytes: int64p(50), ActualBytes: int64p(0), FileCount: intp(1),
+ },
+ },
+ },
+ {
+ Stamp: "20261117T193001Z",
+ Path: broken,
+ ManifestState: "invalid", ManifestError: "清单无法解析:unexpected end",
+ Complete: true, ApparentBytes: int64p(20), ActualBytes: int64p(2048), FileCount: intp(1),
+ Databases: []metadataDatabase{{
+ Name: "weknora_prod", DirName: "weknora_prod.dir",
+ Path: broken + "/weknora_prod.dir", Present: true,
+ ApparentBytes: int64p(20), ActualBytes: int64p(2048), FileCount: intp(1),
+ }},
+ },
+ {
+ Stamp: "20261116T193001Z",
+ Path: without,
+ ManifestState: "missing",
+ Complete: true, ApparentBytes: int64p(30), ActualBytes: int64p(1024), FileCount: intp(1),
+ Databases: []metadataDatabase{{
+ Name: "weknora_archive", DirName: "weknora_archive.dir",
+ Path: without + "/weknora_archive.dir", Present: true,
+ ApparentBytes: int64p(30), ActualBytes: int64p(1024), FileCount: intp(1),
+ }},
+ },
+ },
}
}
-func actualOf(t *testing.T, filename string) int64 {
+func writeMetadata(t *testing.T, value metadata) string {
t.Helper()
- info, err := os.Stat(filename)
+ raw, err := json.Marshal(value)
if err != nil {
t.Fatal(err)
}
- stat, ok := info.Sys().(*syscall.Stat_t)
- if !ok {
- t.Fatal("no stat")
+ filename := filepath.Join(t.TempDir(), "metadata.json")
+ if err := os.WriteFile(filename, raw, 0o644); err != nil {
+ t.Fatal(err)
}
- return int64(stat.Blocks) * 512
+ return filename
}
-func fixtureRoot(t *testing.T) string {
- t.Helper()
- root := t.TempDir()
- latest := filepath.Join(root, "20261118T193001Z")
- writeFile(t, filepath.Join(latest, "MANIFEST.json"), `{
- "kind": "rds-logical-backup",
- "created_at": "20261118T193001Z",
- "started_at": "20261118T192908Z",
- "duration_seconds": 53,
- "databases": ["weknora_v090prod", "weknora_test"],
- "failed_databases": ["weknora_test"],
- "total_bytes": 300,
- "files": [
- {"file": "weknora_v090prod.dir/toc.dat", "bytes": 100},
- {"file": "weknora_v090prod.dir/0001.dat.gz", "bytes": 150},
- {"file": "weknora_test.dir/toc.dat", "bytes": 50}
- ]
-}`)
- writeFile(t, filepath.Join(latest, "weknora_v090prod.dir", "toc.dat"), strings.Repeat("a", 100))
- writeFile(t, filepath.Join(latest, "weknora_v090prod.dir", "0001.dat.gz"), strings.Repeat("b", 150))
- writeFile(t, filepath.Join(latest, "weknora_test.dir", "toc.dat"), strings.Repeat("c", 50))
-
- invalid := filepath.Join(root, "20261117T193001Z")
- writeFile(t, filepath.Join(invalid, "MANIFEST.json"), "{not-json")
- writeFile(t, filepath.Join(invalid, "weknora_prod.dir", "toc.dat"), strings.Repeat("d", 20))
-
- missing := filepath.Join(root, "20261116T193001Z")
- writeFile(t, filepath.Join(missing, "weknora_archive.dir", "toc.dat"), strings.Repeat("e", 30))
-
- incomplete := filepath.Join(root, "20261115T193001Z.incomplete")
- writeFile(t, filepath.Join(incomplete, "MANIFEST.json"), `{}`)
-
- return root
+func readerAt(filename string, now time.Time) *Reader {
+ reader := New(Config{MetadataPath: filename, HostRoot: hostRoot, Source: "configured", MaxAge: 15 * time.Minute})
+ reader.now = func() time.Time { return now }
+ return reader
}
-func TestSnapshotReadsBatchesManifestsAndActualUsage(t *testing.T) {
- root := fixtureRoot(t)
- reader := New(Config{
- Root: root,
- HostRoot: "/srv/kb-backups/rds-logical",
- Source: "weknora-test:/srv/kb-backups/rds-logical",
- })
- reader.device = func(path string) (uint64, error) {
- if path == "/" {
- return 10, nil
- }
- return 20, nil
+func TestSnapshotReadsHostMetadataAndPaths(t *testing.T) {
+ filename := writeMetadata(t, validMetadata())
+ now := time.Date(2026, 11, 20, 1, 5, 0, 0, time.UTC)
+ snapshot := readerAt(filename, now).Snapshot(context.Background())
+ if !snapshot.Wired || snapshot.Error != "" || !snapshot.Metadata.Valid || !snapshot.Metadata.Fresh || !snapshot.Metadata.Complete {
+ t.Fatalf("应接受新鲜的完整快照: %+v", snapshot.Metadata)
}
- reader.statfs = func(string) (statFS, error) {
- return statFS{Total: 1000, Free: 400, Available: 350, ReadOnly: true}, nil
- }
-
- snapshot := reader.Snapshot(context.Background())
- if !snapshot.Wired || snapshot.Error != "" {
- t.Fatalf("应读到接线目录: %+v", snapshot)
- }
- if !snapshot.Mount.MountVerified || snapshot.Mount.LivesOnContainerRoot || !snapshot.Mount.ReadOnly {
- t.Fatalf("挂载判定不对: %+v", snapshot.Mount)
+ if !snapshot.Mount.MountVerified || snapshot.Mount.LivesOnContainerRoot || snapshot.Mount.MountPoint != "/srv/kb-backups" {
+ t.Fatalf("宿主挂载判定不对: %+v", snapshot.Mount)
}
if !snapshot.Capacity.Measured || snapshot.Capacity.TotalBytes != 1000 || snapshot.Capacity.AvailableBytes != 350 {
t.Fatalf("容量不对: %+v", snapshot.Capacity)
}
- if len(snapshot.Batches) != 3 || snapshot.IncompleteCount != 1 {
- t.Fatalf("批次数量不对: %d incomplete=%d", len(snapshot.Batches), snapshot.IncompleteCount)
+ if snapshot.Metadata.AgeSeconds != 300 || snapshot.Metadata.Generation == "" || snapshot.Metadata.Host != "weknora-test" {
+ t.Fatalf("元数据字段不对: %+v", snapshot.Metadata)
+ }
+ if len(snapshot.Batches) != 3 || snapshot.IncompleteCount != 1 || len(snapshot.Skipped) != 1 {
+ t.Fatalf("批次计数不对: %+v", snapshot)
}
latest := snapshot.Batches[0]
- if latest.Stamp != "20261118T193001Z" || latest.ManifestState != ManifestOK {
+ if latest.Stamp != "20261118T193001Z" || latest.ManifestState != ManifestOK || latest.SizesComplete != true {
t.Fatalf("最近批次不对: %+v", latest)
}
- if latest.CreatedAt != "20261118T193001Z" || latest.DurationSeconds != 53 || latest.ManifestBytes != 300 {
- t.Fatalf("清单字段不对: %+v", latest)
- }
- if latest.HostPath != "/srv/kb-backups/rds-logical/20261118T193001Z" {
- t.Fatalf("批次主机路径不对: %q", latest.HostPath)
- }
- if len(latest.Databases) != 2 {
- t.Fatalf("子库数量不对: %+v", latest.Databases)
+ if latest.HostPath != hostRoot+"/20261118T193001Z" || latest.ManifestTotalBytes == nil || *latest.ManifestTotalBytes != 300 {
+ t.Fatalf("批次路径/清单不对: %+v", latest)
}
prod := latest.Databases[0]
- if prod.Name != "weknora_v090prod" || !prod.Present || prod.Failed || !prod.InManifest {
- t.Fatalf("子库状态不对: %+v", prod)
- }
- if prod.Path != filepath.Join(root, "20261118T193001Z", "weknora_v090prod.dir") {
- t.Fatalf("子库容器路径不对: %q", prod.Path)
- }
- if prod.HostPath != "/srv/kb-backups/rds-logical/20261118T193001Z/weknora_v090prod.dir" {
- t.Fatalf("子库主机路径不对: %q", prod.HostPath)
- }
- expectedActual := actualOf(t, filepath.Join(root, "20261118T193001Z", "weknora_v090prod.dir", "toc.dat")) +
- actualOf(t, filepath.Join(root, "20261118T193001Z", "weknora_v090prod.dir", "0001.dat.gz"))
- if prod.ActualBytes != expectedActual {
- t.Fatalf("子库实际占盘不对: got %d want %d", prod.ActualBytes, expectedActual)
- }
- if prod.ApparentBytes != 250 || prod.FileCount != 2 {
- t.Fatalf("子库清单体积不对: %+v", prod)
+ if prod.HostPath != hostRoot+"/20261118T193001Z/weknora_v090prod.dir" || prod.ActualBytes == nil || *prod.ActualBytes != 4096 {
+ t.Fatalf("子库完整路径/占盘不对: %+v", prod)
}
if !latest.Databases[1].Failed {
t.Fatalf("失败库没有标记: %+v", latest.Databases[1])
}
-
- broken := snapshot.Batches[1]
- if broken.Stamp != "20261117T193001Z" || broken.ManifestState != ManifestInvalid || broken.ManifestError == "" {
- t.Fatalf("损坏清单没有如实标记: %+v", broken)
+ if snapshot.Batches[1].ManifestState != ManifestInvalid || snapshot.Batches[1].ManifestError == "" {
+ t.Fatalf("损坏清单没有如实标记: %+v", snapshot.Batches[1])
}
- if len(broken.Databases) != 1 || broken.Databases[0].Name != "weknora_prod" || !broken.Databases[0].Present {
- t.Fatalf("清单损坏时仍应按目录列出子库: %+v", broken.Databases)
+ if snapshot.Batches[2].ManifestState != ManifestMissing {
+ t.Fatalf("缺清单没有如实标记: %+v", snapshot.Batches[2])
}
- withoutManifest := snapshot.Batches[2]
- if withoutManifest.ManifestState != ManifestMissing {
- t.Fatalf("缺清单没有如实标记: %+v", withoutManifest)
- }
- if snapshot.Totals.BatchCount != 3 || snapshot.Totals.LatestStamp != "20261118T193001Z" {
+ if snapshot.Totals.ActualBytes == nil || *snapshot.Totals.ActualBytes != 4096+2048+1024 || !snapshot.Totals.Complete {
t.Fatalf("汇总不对: %+v", snapshot.Totals)
}
- if snapshot.ObservedAt == "" || snapshot.Source != "weknora-test:/srv/kb-backups/rds-logical" {
- t.Fatalf("观测时间/来源不对: %+v", snapshot)
+ if snapshot.Source != "weknora-test:"+hostRoot || snapshot.Measurement != "host_collector" {
+ t.Fatalf("来源/测量方式不对: %+v", snapshot)
+ }
+}
+
+func TestSnapshotStaleIsUnknown(t *testing.T) {
+ value := validMetadata()
+ value.CollectedAt = "2026-11-20T00:00:00Z"
+ 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.Fresh || snapshot.Metadata.Complete {
+ t.Fatalf("陈旧快照不能算有效: %+v", snapshot.Metadata)
+ }
+ if len(snapshot.Batches) != 0 || snapshot.Capacity.Measured || snapshot.Totals.ActualBytes != nil {
+ t.Fatalf("陈旧快照不能给批次/容量/占盘: %+v", snapshot)
+ }
+ if !strings.Contains(snapshot.Error, "陈旧") {
+ t.Fatalf("陈旧原因不清: %q", snapshot.Error)
+ }
+}
+
+func TestSnapshotMissingMetadata(t *testing.T) {
+ reader := New(Config{MetadataPath: filepath.Join(t.TempDir(), "missing.json"), HostRoot: hostRoot})
+ snapshot := reader.Snapshot(context.Background())
+ if !snapshot.Wired || snapshot.Metadata.Present || snapshot.Metadata.Valid {
+ t.Fatalf("缺失快照不能算有效: %+v", snapshot.Metadata)
+ }
+ if !strings.Contains(snapshot.Error, "不存在") {
+ t.Fatalf("缺失原因不清: %q", snapshot.Error)
+ }
+}
+
+func TestSnapshotPermissionFailureNeverUsesPartialBytes(t *testing.T) {
+ value := validMetadata()
+ value.Complete = false
+ value.Errors = nil
+ value.Batches[0].Complete = false
+ value.Batches[0].Errors = []string{"遍历失败:PermissionError: Permission denied ('.../weknora_v090prod.dir')"}
+ // 模拟采集器在权限失败前已经数到的部分字节;API 绝不能把它们当占盘。
+ value.Batches[0].ActualBytes = int64p(100)
+ value.Batches[0].Databases[0].ActualBytes = int64p(100)
+ 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("不完整快照应 valid=true/complete=false: %+v", snapshot.Metadata)
+ }
+ if snapshot.Capacity.Measured || snapshot.Totals.ActualBytes != nil || snapshot.Totals.ApparentBytes != nil {
+ t.Fatalf("不完整快照不能给容量/总量: %+v", snapshot)
+ }
+ if len(snapshot.Batches) != 3 {
+ t.Fatalf("路径仍应列出: %+v", snapshot.Batches)
+ }
+ latest := snapshot.Batches[0]
+ if latest.ActualBytes != nil || latest.ApparentBytes != nil || latest.FileCount != nil || latest.SizesComplete {
+ t.Fatalf("不完整批次不能保留部分字节: %+v", latest)
+ }
+ if latest.Databases[0].ActualBytes != nil || latest.Databases[0].ApparentBytes != nil {
+ t.Fatalf("不完整子库不能保留部分字节: %+v", latest.Databases[0])
+ }
+ if !strings.Contains(snapshot.Metadata.Error, "Permission") {
+ t.Fatalf("权限失败原因丢失: %q", snapshot.Metadata.Error)
+ }
+}
+
+func TestSnapshotTruncatedIsUnknown(t *testing.T) {
+ value := validMetadata()
+ value.Truncated = true
+ filename := writeMetadata(t, value)
+ snapshot := readerAt(filename, time.Date(2026, 11, 20, 1, 5, 0, 0, time.UTC)).Snapshot(context.Background())
+ if snapshot.Metadata.Complete || snapshot.Capacity.Measured || snapshot.Totals.ActualBytes != nil {
+ t.Fatalf("截断快照不能算完整/容量: %+v", snapshot)
+ }
+}
+
+func TestSnapshotRejectsPathMismatch(t *testing.T) {
+ value := validMetadata()
+ value.Batches[0].Path = "/srv/kb-backups/rds-logical/../evil"
+ 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 {
+ t.Fatalf("路径不一致必须整块拒绝: %+v", snapshot.Metadata)
+ }
+ if !strings.Contains(snapshot.Error, "路径") {
+ t.Fatalf("路径错误原因不清: %q", snapshot.Error)
+ }
+}
+
+func TestSnapshotRejectsUnsupportedSchema(t *testing.T) {
+ value := validMetadata()
+ value.SchemaVersion = 99
+ 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 || !strings.Contains(snapshot.Error, "schema_version") {
+ t.Fatalf("不支持的 schema 必须拒绝: %+v", snapshot)
}
}
@@ -161,45 +262,19 @@ func TestSnapshotUnconfigured(t *testing.T) {
}
}
-func TestSnapshotMissingRoot(t *testing.T) {
- reader := New(Config{Root: filepath.Join(t.TempDir(), "missing")})
- snapshot := reader.Snapshot(context.Background())
- if !snapshot.Wired || snapshot.Error == "" || snapshot.Capacity.Measured {
- t.Fatalf("目录不存在应报错且不报容量: %+v", snapshot)
- }
-}
-
-func TestSnapshotRefusesSymlinkBatches(t *testing.T) {
- root := t.TempDir()
- outside := t.TempDir()
- writeFile(t, filepath.Join(outside, "MANIFEST.json"), `{"databases":["escaped"]}`)
- if err := os.Symlink(outside, filepath.Join(root, "20261118T193001Z")); err != nil {
- t.Fatal(err)
- }
- snapshot := New(Config{Root: root}).Snapshot(context.Background())
- if len(snapshot.Batches) != 0 {
- t.Fatalf("符号链接批次不能跟随: %+v", snapshot.Batches)
- }
- if len(snapshot.Skipped) != 1 || !strings.Contains(snapshot.Skipped[0].Reason, "符号链接") {
- t.Fatalf("跳过原因不对: %+v", snapshot.Skipped)
- }
-}
-
-func TestSnapshotDoesNotUseContainerRootCapacity(t *testing.T) {
- root := fixtureRoot(t)
- reader := New(Config{Root: root})
- reader.device = func(string) (uint64, error) { return 7, nil }
- reader.statfs = func(string) (statFS, error) {
- return statFS{Total: 999, Free: 1, Available: 1}, nil
- }
- snapshot := reader.Snapshot(context.Background())
- if snapshot.Mount.MountVerified || !snapshot.Mount.LivesOnContainerRoot {
- t.Fatalf("同设备必须判定为容器根盘: %+v", snapshot.Mount)
- }
- if snapshot.Capacity.Measured || snapshot.Capacity.TotalBytes != 0 || snapshot.Capacity.Error == "" {
- t.Fatalf("容器根盘不能冒充主机容量: %+v", snapshot.Capacity)
- }
- if len(snapshot.Batches) != 3 {
- t.Fatalf("容量不可用不应影响批次读取: %+v", snapshot.Batches)
+// 宿主采集器的权限失败回归:self-test 用注入 walker 模拟 PermissionError,
+// 断言不完整时字节为 null 且不产生部分统计。
+func TestCollectorSelfTest(t *testing.T) {
+ python, err := exec.LookPath("python3")
+ if err != nil {
+ t.Skip("python3 not available")
+ }
+ command := exec.Command(python, "../../scripts/collect_backup_metadata.py", "--self-test")
+ output, err := command.CombinedOutput()
+ if err != nil {
+ t.Fatalf("collector self-test failed: %v\n%s", err, output)
+ }
+ if !strings.Contains(string(output), "self-test ok") {
+ t.Fatalf("collector self-test output unexpected: %s", output)
}
}
diff --git a/internal/httpapi/backup_inventory.go b/internal/httpapi/backup_inventory.go
index 130cb71..63033ef 100644
--- a/internal/httpapi/backup_inventory.go
+++ b/internal/httpapi/backup_inventory.go
@@ -7,15 +7,15 @@ import (
"knowledge-governance/internal/backupinventory"
)
-// BackupInventoryReader 只读盘点备份主机目录。它与 SSH 主机计划读回完全独立:
-// 挂载没接线不应拖垮计划读回,计划读回失败也不应把历史批次说成"没有"。
+// BackupInventoryReader 读取宿主采集器写出的元数据快照。它与 SSH 主机计划读回完全独立:
+// 快照缺失/陈旧不应拖垮计划读回,计划读回失败也不应把历史批次说成"没有"。
type BackupInventoryReader interface {
Available() bool
Snapshot(context.Context) backupinventory.Snapshot
}
-// handleBackupInventory 返回真实批次、子库路径与实测容量。
-// 未接线/目录不可读/清单损坏都作为 200 的字段返回,由页面区分原因;
+// handleBackupInventory 返回宿主采集器快照里的批次、子库路径与容量。
+// 未接线/快照缺失/陈旧/不完整/路径不一致都作为 200 的字段返回,由页面区分原因;
// 只有投影本身失败才 500。
func (config Config) handleBackupInventory(w http.ResponseWriter, r *http.Request) {
snapshot := config.BackupInventory.Snapshot(r.Context())
diff --git a/internal/httpapi/backup_inventory_test.go b/internal/httpapi/backup_inventory_test.go
index 197555c..879085b 100644
--- a/internal/httpapi/backup_inventory_test.go
+++ b/internal/httpapi/backup_inventory_test.go
@@ -21,30 +21,33 @@ func (fake fakeBackupInventory) Snapshot(context.Context) backupinventory.Snapsh
}
func TestBackupInventoryProjectionPassesRealFields(t *testing.T) {
+ actual := int64(1024)
+ databaseActual := int64(512)
config := Config{BackupInventory: fakeBackupInventory{snapshot: backupinventory.Snapshot{
Wired: true,
- Root: "/var/lib/knowledge-governance/backup-host/rds-logical",
+ 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},
Mount: backupinventory.MountInfo{
MountVerified: true,
ReadOnly: true,
- Evidence: "挂载设备 20 与容器根盘 10 不同",
+ Evidence: "宿主采集器:/dev/sdb1 挂在 /srv/kb-backups(ext4)",
},
Capacity: backupinventory.Capacity{Measured: true, TotalBytes: 100, FreeBytes: 40, AvailableBytes: 35, UsedBytes: 60},
Batches: []backupinventory.Batch{{
Stamp: "20261118T193001Z",
HostPath: "/srv/kb-backups/rds-logical/20261118T193001Z",
ManifestState: backupinventory.ManifestOK,
- ActualBytes: 1024,
+ ActualBytes: &actual,
Databases: []backupinventory.Database{{
Name: "weknora_v090prod",
HostPath: "/srv/kb-backups/rds-logical/20261118T193001Z/weknora_v090prod.dir",
Present: true,
- ActualBytes: 512,
+ ActualBytes: &databaseActual,
}},
}},
- Totals: backupinventory.Totals{BatchCount: 1, LatestStamp: "20261118T193001Z"},
+ Totals: backupinventory.Totals{BatchCount: 1, ActualBytes: &actual, LatestStamp: "20261118T193001Z", Complete: true},
}}}
recorder := httptest.NewRecorder()
config.handleBackupInventory(recorder, httptest.NewRequest(http.MethodGet, "/api/v1/backup-schedule/inventory", nil))
@@ -64,7 +67,7 @@ func TestBackupInventoryProjectionPassesRealFields(t *testing.T) {
payload.Data.Batches[0].Databases[0].HostPath != "/srv/kb-backups/rds-logical/20261118T193001Z/weknora_v090prod.dir" {
t.Fatalf("批次/子库真实路径丢失: %+v", payload.Data.Batches)
}
- if payload.Data.Batches[0].ActualBytes != 1024 {
+ if payload.Data.Batches[0].ActualBytes == nil || *payload.Data.Batches[0].ActualBytes != 1024 {
t.Fatalf("实际占盘字段丢失: %+v", payload.Data.Batches[0])
}
}
diff --git a/scripts/collect_backup_metadata.py b/scripts/collect_backup_metadata.py
new file mode 100755
index 0000000..a1a32cf
--- /dev/null
+++ b/scripts/collect_backup_metadata.py
@@ -0,0 +1,581 @@
+#!/usr/bin/env python3
+"""备份目录的**单次宿主元数据采集器**(只读)。
+
+为什么不在 API 里遍历:备份目录通常是 root:root 0700,API 容器用户没有进入权限;
+容器里再 df/du 也证明不了宿主的盘。这个脚本在备份主机上由有读权限的宿主进程
+(root 或备份所有者)运行,只做 stat/du 和读 MANIFEST.json,产出原子快照 JSON;
+API 只读快照,不接触备份目录,也不借用 SSH 或容器特权。
+
+不读取任何数据库内容文件:只对目录项 lstat、统计 st_size/st_blocks,并读
+MANIFEST.json(元数据)。输出用同目录临时文件 + fsync + os.replace 原子替换。
+
+用法(宿主):
+ python3 collect_backup_metadata.py \
+ --root /srv/kb-backups/rds-logical \
+ --output /var/lib/knowledge-governance/backup-metadata/metadata.json \
+ --source weknora-test:/srv/kb-backups/rds-logical
+
+退出码:0 完整;2 已写快照但采集不完整/有错误;1 连快照都没写成。
+"""
+from __future__ import annotations
+
+import argparse
+import datetime as dt
+import errno
+import json
+import os
+import re
+import socket
+import stat
+import sys
+import tempfile
+import uuid
+from typing import Any, Callable, Iterable
+
+SCHEMA_VERSION = 1
+COLLECTOR_VERSION = "backup-metadata/1"
+MAX_MANIFEST_BYTES = 8 << 20
+MAX_ERRORS = 50
+STAMP_NAME = re.compile(r"^[A-Za-z0-9._-]+$")
+
+
+class CollectError(Exception):
+ pass
+
+
+def _error_text(error: BaseException) -> str:
+ if isinstance(error, OSError) and error.filename:
+ return f"{type(error).__name__}: {error.strerror or error} ({error.filename})"
+ return f"{type(error).__name__}: {error}"
+
+
+def _append_error(errors: list[str], text: str) -> None:
+ if len(errors) < MAX_ERRORS and text not in errors:
+ errors.append(text)
+
+
+def _unescape_mount(text: str) -> str:
+ return re.sub(r"\\([0-7]{3})", lambda m: chr(int(m.group(1), 8)), text)
+
+
+def mount_info(root: str) -> dict[str, Any]:
+ """从 /proc/self/mountinfo 找覆盖 root 的最长挂载点(只读文件,不碰备份内容)。"""
+ best: dict[str, Any] | None = None
+ try:
+ with open("/proc/self/mountinfo", "r", encoding="utf-8", errors="replace") as handle:
+ for line in handle:
+ before, sep, after = line.partition(" - ")
+ if not sep:
+ continue
+ fields = before.split()
+ tail = after.split()
+ if len(fields) < 6 or len(tail) < 3:
+ continue
+ mount_point = _unescape_mount(fields[4])
+ if root == mount_point or root.startswith(mount_point.rstrip("/") + "/"):
+ if best is None or len(mount_point) > len(best["mount_point"]):
+ best = {
+ "mount_point": mount_point,
+ "mount_source": _unescape_mount(tail[1]),
+ "fs_type": tail[0],
+ "read_only": "ro" in fields[5].split(","),
+ }
+ except OSError:
+ return {}
+ return best or {}
+
+
+def capacity(root: str) -> tuple[dict[str, Any], list[str]]:
+ errors: list[str] = []
+ info = mount_info(root)
+ try:
+ stats = os.statvfs(root)
+ block = stats.f_frsize or stats.f_bsize
+ info.update(
+ {
+ "total_bytes": stats.f_blocks * block,
+ "free_bytes": stats.f_bfree * block,
+ "available_bytes": stats.f_bavail * block,
+ }
+ )
+ if "read_only" not in info:
+ flags = getattr(stats, "f_flag", 0)
+ info["read_only"] = bool(flags & getattr(os, "ST_RDONLY", 1))
+ except OSError as error:
+ _append_error(errors, "statvfs: " + _error_text(error))
+ return info, errors
+
+
+def _read_manifest(path: str) -> tuple[str, str, dict[str, Any]]:
+ # MANIFEST 只接受目录内的常规文件:lstat 拒绝符号链接,open 再带 O_NOFOLLOW,
+ # 防止采集器被一个指向别处的清单带跑(只读,也不会跟随到归档内容)。
+ try:
+ info = os.lstat(path)
+ except FileNotFoundError:
+ return "missing", "", {}
+ except OSError as error:
+ return "invalid", "清单不可读:" + _error_text(error), {}
+ if stat.S_ISLNK(info.st_mode) or not stat.S_ISREG(info.st_mode):
+ return "invalid", "清单不是目录内的常规文件(拒绝符号链接)", {}
+ if info.st_size > MAX_MANIFEST_BYTES:
+ return "invalid", f"清单超过 {MAX_MANIFEST_BYTES} 字节读取上限", {}
+ flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0)
+ try:
+ descriptor = os.open(path, flags)
+ except OSError as error:
+ return "invalid", "清单不可读:" + _error_text(error), {}
+ try:
+ with os.fdopen(descriptor, "rb") as handle:
+ opened = os.fstat(handle.fileno())
+ if not stat.S_ISREG(opened.st_mode):
+ return "invalid", "清单在打开后不是常规文件", {}
+ raw = handle.read(MAX_MANIFEST_BYTES + 1)
+ except OSError as error:
+ return "invalid", "清单不可读:" + _error_text(error), {}
+ if len(raw) > MAX_MANIFEST_BYTES:
+ return "invalid", f"清单超过 {MAX_MANIFEST_BYTES} 字节读取上限", {}
+ try:
+ value = json.loads(raw.decode("utf-8"))
+ except (UnicodeDecodeError, json.JSONDecodeError) as error:
+ return "invalid", "清单无法解析:" + str(error), {}
+ if not isinstance(value, dict):
+ return "invalid", "清单不是对象", {}
+ return "ok", "", value
+
+
+def measure_tree(path: str, scan: Callable[[str], Iterable[Any]] = os.scandir, max_files: int = 500_000) -> dict[str, Any]:
+ """只 stat 目录项;口径与 `du -sB1` 一致。
+
+ - 目录自身也计入(st_size + st_blocks),不只求和文件;
+ - 子树完整遍历,任何 lstat/scandir 错误置 complete=false;
+ - 常规文件硬链接按 (dev, ino) 只算一次(单库/整批各自独立去重);
+ - 符号链接、设备等非目录/非普通文件不跟随、不计入(与参考 du 口径一致)。
+
+ scan 可注入,self-test 用它模拟 PermissionError;生产默认 os.scandir。
+ """
+ apparent = actual = files = dirs = 0
+ seen: set[tuple[int, int]] = set()
+ errors: list[str] = []
+ complete = True
+ stack = [path]
+ while stack:
+ current = stack.pop()
+ try:
+ info = os.lstat(current)
+ except OSError as error:
+ complete = False
+ _append_error(errors, "stat 失败:" + _error_text(error))
+ continue
+ if stat.S_ISDIR(info.st_mode):
+ dirs += 1
+ apparent += int(info.st_size)
+ actual += int(getattr(info, "st_blocks", 0)) * 512
+ try:
+ entries = list(scan(current))
+ except OSError as error:
+ complete = False
+ _append_error(errors, "遍历失败:" + _error_text(error))
+ continue
+ entries.sort(key=lambda entry: entry.name)
+ for entry in entries:
+ try:
+ child = entry.stat(follow_symlinks=False)
+ except OSError as error:
+ complete = False
+ _append_error(errors, "stat 失败:" + _error_text(error))
+ continue
+ if stat.S_ISDIR(child.st_mode):
+ stack.append(entry.path)
+ continue
+ if not stat.S_ISREG(child.st_mode):
+ continue # symlink/设备不跟随,du 默认也不计目标
+ if int(getattr(child, "st_nlink", 0)) > 1:
+ key = (int(child.st_dev), int(child.st_ino))
+ if key in seen:
+ continue # du 只算一次
+ seen.add(key)
+ if files >= max_files:
+ complete = False
+ _append_error(errors, f"文件数超过采集上限 {max_files}")
+ stack.clear()
+ break
+ apparent += int(child.st_size)
+ actual += int(getattr(child, "st_blocks", 0)) * 512
+ files += 1
+ return {
+ "apparent_bytes": apparent,
+ "actual_bytes": actual,
+ "file_count": files,
+ "dir_count": dirs,
+ "complete": complete,
+ "errors": errors,
+ }
+
+
+def collect(
+ root: str,
+ source: str = "",
+ host: str | None = None,
+ max_batches: int = 100,
+ scan: Callable[[str], Iterable[Any]] = os.scandir,
+ now: dt.datetime | None = None,
+) -> dict[str, Any]:
+ root = os.path.abspath(root)
+ collected_at = (now or dt.datetime.now(dt.timezone.utc)).astimezone(dt.timezone.utc)
+ snapshot: dict[str, Any] = {
+ "schema_version": SCHEMA_VERSION,
+ "collector_version": COLLECTOR_VERSION,
+ "generation": f"{collected_at.strftime('%Y%m%dT%H%M%SZ')}-{uuid.uuid4().hex[:12]}",
+ "collected_at": collected_at.isoformat().replace("+00:00", "Z"),
+ "host": host or socket.gethostname(),
+ "source": source,
+ "root": root,
+ "complete": True,
+ "errors": [],
+ "filesystem": {},
+ "incomplete_count": 0,
+ "skipped": [],
+ "truncated": False,
+ "batches": [],
+ }
+ errors: list[str] = snapshot["errors"]
+ try:
+ if not os.path.isdir(root):
+ raise CollectError(f"备份根不是目录:{root}")
+ entries = list(os.scandir(root))
+ except OSError as error:
+ _append_error(errors, "无法列出备份根:" + _error_text(error))
+ snapshot["complete"] = False
+ snapshot["filesystem"], capacity_errors = capacity(root)
+ for item in capacity_errors:
+ _append_error(errors, item)
+ return snapshot
+
+ fs_info, capacity_errors = capacity(root)
+ snapshot["filesystem"] = fs_info
+ for item in capacity_errors:
+ _append_error(errors, item)
+
+ dirs: list[str] = []
+ for entry in entries:
+ name = entry.name
+ if name.endswith(".incomplete"):
+ snapshot["incomplete_count"] += 1
+ continue
+ if not STAMP_NAME.match(name) or "/" in name or "\\" in name:
+ snapshot["skipped"].append({"name": name, "reason": "目录名不合法"})
+ continue
+ try:
+ if entry.is_symlink():
+ snapshot["skipped"].append({"name": name, "reason": "符号链接不跟随"})
+ continue
+ if not entry.is_dir(follow_symlinks=False):
+ snapshot["skipped"].append({"name": name, "reason": "不是批次目录"})
+ continue
+ except OSError as error:
+ _append_error(errors, "批次项不可读:" + _error_text(error))
+ continue
+ dirs.append(name)
+ dirs.sort(reverse=True)
+ if len(dirs) > max_batches:
+ dirs = dirs[:max_batches]
+ snapshot["truncated"] = True
+
+ for name in dirs:
+ snapshot["batches"].append(_collect_batch(root, name, scan))
+ snapshot["complete"] = (
+ not errors
+ and not snapshot["truncated"]
+ and all(batch["complete"] for batch in snapshot["batches"])
+ )
+ return snapshot
+
+
+def _collect_batch(root: str, name: str, scan: Callable[[str], Iterable[Any]]) -> dict[str, Any]:
+ batch_path = os.path.join(root, name)
+ state, manifest_error, manifest = _read_manifest(os.path.join(batch_path, "MANIFEST.json"))
+ tree = measure_tree(batch_path, scan)
+ errors = list(tree["errors"])
+ manifest_databases = [
+ item for item in (manifest.get("databases") or []) if isinstance(item, str)
+ ] if isinstance(manifest.get("databases"), list) else []
+ raw_failed = manifest.get("failed_databases")
+ failed_values: list[Any] = raw_failed if isinstance(raw_failed, list) else []
+ failed = {item for item in failed_values if isinstance(item, str)}
+ actual_dirs: set[str] = set()
+ try:
+ for entry in scan(batch_path):
+ db_name = entry.name[: -len(".dir")] if entry.name.endswith(".dir") else ""
+ if not db_name or not STAMP_NAME.match(db_name):
+ continue
+ try:
+ info = entry.stat(follow_symlinks=False)
+ except OSError as error:
+ _append_error(errors, "子库目录不可读:" + _error_text(error))
+ continue
+ if not stat.S_ISDIR(info.st_mode) or stat.S_ISLNK(info.st_mode):
+ continue
+ actual_dirs.add(db_name)
+ except OSError as error:
+ _append_error(errors, "批次目录不可读:" + _error_text(error))
+
+ names = sorted(set(manifest_databases) | actual_dirs)
+ databases: list[dict[str, Any]] = []
+ for db in names:
+ if not db or not STAMP_NAME.match(db):
+ continue
+ dir_name = db + ".dir"
+ path = os.path.join(batch_path, dir_name)
+ present = db in actual_dirs
+ if state == "ok" and db in manifest_databases and not present:
+ _append_error(errors, f"清单列出 {db} 但 {dir_name} 不存在")
+ measured = measure_tree(path, scan) if present else None
+ db_complete = bool(measured is not None and measured["complete"])
+ if measured is not None and not measured["complete"]:
+ _append_error(errors, f"子库 {db} 遍历不完整")
+ databases.append(
+ {
+ "name": db,
+ "dir_name": dir_name,
+ "path": path,
+ "present": present,
+ "failed": db in failed,
+ "in_manifest": db in manifest_databases,
+ "apparent_bytes": measured["apparent_bytes"] if measured is not None and db_complete else None,
+ "actual_bytes": measured["actual_bytes"] if measured is not None and db_complete else None,
+ "file_count": measured["file_count"] if measured is not None and db_complete else None,
+ "dir_count": measured["dir_count"] if measured is not None and db_complete else None,
+ "complete": db_complete,
+ "errors": measured["errors"] if measured is not None else [],
+ }
+ )
+
+ complete = tree["complete"] and all(database["complete"] for database in databases) and not errors
+ manifest_total = manifest.get("total_bytes") if state == "ok" else 0
+ if state == "ok" and not isinstance(manifest_total, int):
+ manifest_total = 0
+ duration = manifest.get("duration_seconds") if state == "ok" else 0
+ if not isinstance(duration, int):
+ duration = 0
+ batch = {
+ "stamp": name,
+ "path": batch_path,
+ "manifest_state": state,
+ "manifest_error": manifest_error,
+ "kind": manifest.get("kind", "") if state == "ok" else "",
+ "created_at": manifest.get("created_at", "") if state == "ok" else "",
+ "started_at": manifest.get("started_at", "") if state == "ok" else "",
+ "duration_seconds": duration,
+ "manifest_total_bytes": int(manifest_total) if state == "ok" else None,
+ "complete": complete,
+ "errors": errors,
+ "apparent_bytes": (int(manifest_total) if state == "ok" and manifest_total else tree["apparent_bytes"]) if complete else None,
+ "actual_bytes": tree["actual_bytes"] if complete else None,
+ "file_count": tree["file_count"] if complete else None,
+ "dir_count": tree["dir_count"] if complete else None,
+ "databases": databases if complete else [
+ {**database, "apparent_bytes": None, "actual_bytes": None, "file_count": None, "dir_count": None}
+ for database in databases
+ ],
+ }
+ return batch
+
+
+def write_snapshot(output: str, snapshot: dict[str, Any]) -> None:
+ directory = os.path.dirname(os.path.abspath(output))
+ os.makedirs(directory, mode=0o755, exist_ok=True)
+ fd, temporary = tempfile.mkstemp(prefix=".metadata-", dir=directory)
+ try:
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
+ json.dump(snapshot, handle, ensure_ascii=False, sort_keys=True, indent=2)
+ handle.write("\n")
+ handle.flush()
+ os.fsync(handle.fileno())
+ os.chmod(temporary, 0o644)
+ os.replace(temporary, output)
+ dir_fd = os.open(directory, os.O_DIRECTORY)
+ try:
+ os.fsync(dir_fd)
+ finally:
+ os.close(dir_fd)
+ except BaseException:
+ try:
+ os.unlink(temporary)
+ except OSError:
+ pass
+ raise
+
+
+def _self_test() -> None:
+ import shutil
+ import sys as _sys
+
+ base = tempfile.mkdtemp(prefix="backup-metadata-test-")
+ try:
+ root = os.path.join(base, "rds-logical")
+ stamp = "20261118T193001Z"
+ batch = os.path.join(root, stamp)
+ os.makedirs(os.path.join(batch, "weknora_test.dir"), mode=0o700)
+ payload = "x" * 100
+ with open(os.path.join(batch, "weknora_test.dir", "toc.dat"), "w", encoding="utf-8") as handle:
+ handle.write(payload)
+ manifest = {
+ "kind": "rds-logical-backup",
+ "created_at": stamp,
+ "duration_seconds": 53,
+ "databases": ["weknora_test"],
+ "failed_databases": [],
+ "total_bytes": len(payload),
+ "files": [{"file": "weknora_test.dir/toc.dat", "bytes": len(payload)}],
+ }
+ with open(os.path.join(batch, "MANIFEST.json"), "w", encoding="utf-8") as handle:
+ json.dump(manifest, handle)
+ fixed = dt.datetime(2026, 11, 20, 1, 2, 3, tzinfo=dt.timezone.utc)
+ snapshot = collect(root, "weknora-test:" + root, "weknora-test", now=fixed)
+ assert snapshot["complete"] is True, snapshot
+ assert snapshot["schema_version"] == SCHEMA_VERSION
+ assert snapshot["batches"][0]["manifest_state"] == "ok"
+ assert snapshot["batches"][0]["databases"][0]["name"] == "weknora_test"
+ assert snapshot["batches"][0]["actual_bytes"] >= len(payload)
+ assert snapshot["filesystem"]["total_bytes"] > 0
+
+ def denied_scan(target: str):
+ if target.endswith(".dir"):
+ raise PermissionError(errno.EACCES, "Permission denied", target)
+ return os.scandir(target)
+
+ denied = collect(root, scan=denied_scan, now=fixed)
+ assert denied["complete"] is False
+ assert denied["batches"][0]["complete"] is False
+ assert denied["batches"][0]["actual_bytes"] is None
+ assert denied["batches"][0]["databases"][0]["actual_bytes"] is None
+ assert any("Permission denied" in item for item in denied["batches"][0]["errors"])
+
+ # 与参考 host-backup-inventory.sh 同口径:目录自身计入、树内硬链接去重、
+ # 单库与整批各自独立测量,各自与自身的 du -sB1 一致。
+ import subprocess
+
+ if shutil.which("du"):
+ def du_bytes(target: str) -> int:
+ result = subprocess.run(
+ ["du", "-sB1", target], capture_output=True, text=True, check=True
+ )
+ return int(result.stdout.split()[0])
+
+ link_root = os.path.join(base, "hardlink-root")
+ plain_root = os.path.join(base, "single-hardlink-root")
+ plain_batch = os.path.join(plain_root, "20261114T193001Z")
+ plain_db = os.path.join(plain_batch, "weknora_v090prod.dir")
+ os.makedirs(plain_db)
+ with open(os.path.join(plain_db, "base.tar"), "wb") as handle:
+ handle.write(b"x" * 5000)
+ os.link(os.path.join(plain_db, "base.tar"), os.path.join(plain_db, "base.tar.link"))
+ with open(os.path.join(plain_batch, "MANIFEST.json"), "w", encoding="utf-8") as handle:
+ json.dump({"databases": ["weknora_v090prod"]}, handle)
+ plain = collect(plain_root, now=fixed)
+ plain_db_info = plain["batches"][0]["databases"][0]
+ plain_batch_info = plain["batches"][0]
+ assert plain_db_info["actual_bytes"] == du_bytes(plain_db), plain_db_info
+ assert plain_batch_info["actual_bytes"] == du_bytes(plain_batch), plain_batch_info
+ assert plain_db_info["file_count"] == 1, plain_db_info
+
+ link_batch = os.path.join(link_root, "20261116T193001Z")
+ db_a = os.path.join(link_batch, "weknora_a.dir")
+ db_b = os.path.join(link_batch, "weknora_b.dir")
+ os.makedirs(db_a)
+ os.makedirs(db_b)
+ with open(os.path.join(db_a, "one.dat"), "wb") as handle:
+ handle.write(b"x" * 5000)
+ os.link(os.path.join(db_a, "one.dat"), os.path.join(db_a, "alias.dat"))
+ with open(os.path.join(db_b, "two.dat"), "wb") as handle:
+ handle.write(b"y" * 3000)
+ # 跨子库硬链接:整批 du 只算一次,单库 du 各自算一次。
+ os.link(os.path.join(db_a, "one.dat"), os.path.join(db_b, "shared.dat"))
+ with open(os.path.join(link_batch, "globals.sql"), "wb") as handle:
+ handle.write(b"z" * 1000)
+ with open(os.path.join(link_batch, "MANIFEST.json"), "w", encoding="utf-8") as handle:
+ json.dump({"kind": "rds-logical-backup", "databases": ["weknora_a", "weknora_b"]}, handle)
+
+ linked = collect(link_root, now=fixed)
+ linked_batch = linked["batches"][0]
+ assert linked["complete"] is True, linked
+ by_name = {item["name"]: item for item in linked_batch["databases"]}
+ assert by_name["weknora_a"]["actual_bytes"] == du_bytes(db_a), by_name["weknora_a"]
+ assert by_name["weknora_b"]["actual_bytes"] == du_bytes(db_b), by_name["weknora_b"]
+ assert linked_batch["actual_bytes"] == du_bytes(link_batch), linked_batch
+ # 逻辑文件数:one/alias/shared 同一 inode 只计一次,再加 two.dat、globals.sql、MANIFEST
+ assert by_name["weknora_a"]["file_count"] == 1, by_name["weknora_a"]
+ assert by_name["weknora_b"]["file_count"] == 2, by_name["weknora_b"]
+ assert linked_batch["file_count"] == 4, linked_batch
+ assert linked_batch["actual_bytes"] >= 5000 + 3000 + 1000
+
+ # MANIFEST 只接受批次目录内的常规文件:指向别处的符号链接必须 invalid,不能被跟随。
+ symlink_root = os.path.join(base, "symlink-root")
+ symlink_batch = os.path.join(symlink_root, "20261115T193001Z")
+ os.makedirs(os.path.join(symlink_batch, "weknora_x.dir"))
+ outside = os.path.join(base, "outside-manifest.json")
+ with open(outside, "w", encoding="utf-8") as handle:
+ json.dump({"databases": ["weknora_x"]}, handle)
+ os.symlink(outside, os.path.join(symlink_batch, "MANIFEST.json"))
+ symlinked = collect(symlink_root, now=fixed)
+ assert symlinked["batches"][0]["manifest_state"] == "invalid"
+ assert "常规文件" in symlinked["batches"][0]["manifest_error"]
+
+ incomplete_dir = os.path.join(root, "20261117T193001Z.incomplete")
+ os.makedirs(incomplete_dir)
+ with open(os.path.join(incomplete_dir, "MANIFEST.json"), "w", encoding="utf-8") as handle:
+ handle.write("{}")
+ ignored = collect(root, now=fixed)
+ assert ignored["incomplete_count"] == 1
+ assert [item["stamp"] for item in ignored["batches"]] == [stamp]
+
+ output = os.path.join(base, "out", "metadata.json")
+ write_snapshot(output, ignored)
+ with open(output, encoding="utf-8") as handle:
+ reloaded = json.load(handle)
+ assert reloaded["batches"][0]["stamp"] == stamp
+ assert not [name for name in os.listdir(os.path.dirname(output)) if name.startswith(".metadata-")]
+ print("collect_backup_metadata self-test ok")
+ _sys.stdout.flush()
+ finally:
+ shutil.rmtree(base, ignore_errors=True)
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(description="备份目录只读元数据采集器")
+ parser.add_argument("--root", required=False, help="宿主机上的 rds-logical 目录")
+ parser.add_argument("--output", required=False, help="原子写出的 metadata.json")
+ 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("--self-test", action="store_true")
+ args = parser.parse_args(argv)
+ if args.self_test:
+ _self_test()
+ return 0
+ if not args.root or not args.output:
+ parser.error("--root and --output are required unless --self-test")
+ try:
+ snapshot = collect(
+ args.root,
+ source=args.source,
+ host=args.host or None,
+ max_batches=max(1, args.max_batches),
+ )
+ write_snapshot(args.output, snapshot)
+ except (CollectError, OSError) as error:
+ print(f"collect failed: {error}", file=sys.stderr)
+ return 1
+ summary = {
+ "complete": snapshot["complete"],
+ "batches": len(snapshot["batches"]),
+ "incomplete_count": snapshot["incomplete_count"],
+ "collected_at": snapshot["collected_at"],
+ "output": args.output,
+ }
+ print(json.dumps(summary, ensure_ascii=False))
+ return 0 if snapshot["complete"] else 2
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
\ No newline at end of file
diff --git a/web/src/BackupScheduleSection.test.tsx b/web/src/BackupScheduleSection.test.tsx
index ba5fdb4..383a8fe 100644
--- a/web/src/BackupScheduleSection.test.tsx
+++ b/web/src/BackupScheduleSection.test.tsx
@@ -74,17 +74,37 @@ const diskFixture = (overrides: Partial = {}): StorageDi
const inventoryFixture = (overrides: Partial = {}): BackupInventory => {
const baseInventory: BackupInventory = {
wired: true,
- root: '/var/lib/knowledge-governance/backup-host/rds-logical',
+ metadata: {
+ configured: true,
+ present: true,
+ valid: true,
+ fresh: true,
+ complete: true,
+ path: '/var/lib/knowledge-governance/backup-host/metadata.json',
+ collected_at: '2026-11-19T03:30:00Z',
+ age_seconds: 10,
+ max_age_seconds: 900,
+ schema_version: 1,
+ generation: '20261119T033000Z-abc123',
+ host: 'weknora-test',
+ collector_version: 'backup-metadata/1',
+ error: '',
+ },
+ root: '/srv/kb-backups/rds-logical',
host_root: '/srv/kb-backups/rds-logical',
source: 'weknora-test:/srv/kb-backups/rds-logical',
observed_at: '2026-11-19T03:30:10Z',
error: '',
+ measurement: 'host_collector',
mount: {
- container_root: '/',
+ container_root: '',
mount_verified: true,
lives_on_container_root: false,
read_only: true,
- evidence: '挂载设备 20 与容器根盘 10 不同:容量按挂载文件系统计量',
+ evidence: '宿主采集器:/dev/sdb1 挂在 /srv/kb-backups(ext4),API 不遍历备份目录',
+ mount_point: '/srv/kb-backups',
+ device: '/dev/sdb1',
+ fs_type: 'ext4',
},
capacity: {
measured: true,
@@ -118,7 +138,7 @@ const inventoryFixture = (overrides: Partial = {}): BackupInven
present: true,
failed: false,
in_manifest: true,
- apparent_bytes: 696_320,
+ apparent_bytes: 700_000,
actual_bytes: 720_896,
file_count: 12,
},
@@ -175,6 +195,7 @@ const inventoryFixture = (overrides: Partial = {}): BackupInven
actual_bytes: 1_500_004_096,
latest_stamp: '20261118T193001Z',
latest_actual_bytes: 1_500_000_000,
+ complete: true,
},
incomplete_count: 1,
skipped: [{ name: 'junk', reason: '不是批次目录' }],
@@ -229,7 +250,7 @@ describe('BackupScheduleView', () => {
'备份执行主机 weknora-test 本机直连 RDS',
'最近批次含 2 个数据库',
'weknora-test 本地备份根目录',
- '备份目录未接线或不可读,不在页面猜测',
+ '元数据快照未接线或不可用,不在页面猜测',
'整批 · 2 个数据库(weknora_test、dobotai_prod)',
'100.85.111.121:22',
'立即备份一次(整批 2 个数据库)',
@@ -261,7 +282,7 @@ describe('BackupScheduleView', () => {
it('目录/配额/预留没有后端字段:控件禁用并写明原因,不会假装可保存', () => {
const html = view()
expect(html).toContain('备份主机上的目录')
- expect(html).toContain('只读盘点未接线')
+ expect(html).toContain('元数据快照未接线')
expect(html).toContain('检查目录(不可用)')
expect(html).toContain('备份总配额(GiB)')
expect(html).toContain('磁盘预留(GiB)')
@@ -270,11 +291,11 @@ describe('BackupScheduleView', () => {
expect(html).toContain('disabled')
})
- it('只读盘点:展示全部批次、MANIFEST 状态、子库完整路径与实际占盘', () => {
+ it('宿主快照:展示全部批次、MANIFEST 状态、子库完整路径与实际占盘', () => {
const html = view({}, { inventory: inventoryFixture() })
for (const text of [
'备份记录',
- '2 批 · 只读盘点',
+ '2 批 · 元数据快照',
'最近批次 20261118T193001Z',
'清单完整',
'清单损坏',
@@ -299,32 +320,41 @@ describe('BackupScheduleView', () => {
expect(html).not.toContain('复制目录(不可用)')
})
- it('没有只读盘点:不展示任何历史批次或伪造路径', () => {
+ it('没有快照:不展示任何历史批次或伪造路径', () => {
const html = view()
- expect(html).toContain('尚未读取只读盘点')
+ expect(html).toContain('尚未读取宿主元数据快照')
expect(html).not.toContain('批次戳')
expect(html).not.toContain('/srv/kb-backups/rds-logical')
})
- it('盘点未接线:说明与 SSH 计划读回独立,未读到不等于没有备份', () => {
+ it('快照未接线:说明与 SSH 计划读回独立,未读到不等于没有备份', () => {
+ const base = inventoryFixture()
const html = view(
{},
{
inventory: inventoryFixture({
wired: false,
- error: '只读盘点未接线(BACKUP_HOST_READONLY_ROOT 未设置)',
+ metadata: {
+ ...base.metadata,
+ configured: false,
+ present: false,
+ valid: false,
+ fresh: false,
+ complete: false,
+ error: '元数据快照未接线(BACKUP_HOST_METADATA_PATH 未设置)',
+ },
+ error: '元数据快照未接线(BACKUP_HOST_METADATA_PATH 未设置)',
batches: [],
capacity: { measured: false, total_bytes: 0, free_bytes: 0, available_bytes: 0, used_bytes: 0 },
}),
}
)
- expect(html).toContain('只读盘点未接线')
+ expect(html).toContain('元数据快照未接线')
expect(html).toContain('未读到批次不等于没有备份')
- expect(html).toContain('文件盘点未接线')
expect(html).not.toContain('/srv/kb-backups/rds-logical/20261118T193001Z')
})
- it('挂载可读但没有批次时说明不能据此判断成功/失败', () => {
+ it('快照可读但没有批次时说明不能据此判断成功/失败', () => {
const html = view(
{
last_run_stamp: '',
@@ -343,11 +373,12 @@ describe('BackupScheduleView', () => {
actual_bytes: 0,
latest_stamp: '',
latest_actual_bytes: 0,
+ complete: true,
},
}),
}
)
- expect(html).toContain('挂载可读,但没有批次目录')
+ expect(html).toContain('宿主快照可读,但没有批次目录')
expect(html).toContain('不能证明备份成功或失败')
})
@@ -402,7 +433,7 @@ describe('BackupScheduleView', () => {
expect(html).toContain('weknora-test · 连接失败')
expect(html).toContain('120.76.217.51:22')
expect(html).toContain('未知(未连上主机,未执行主机侧脚本)')
- expect(html).not.toContain('缺失')
+ expect(html).not.toContain('备份脚本缺失')
expect(html).toContain('主机连不上:以下"主机生效"状态未知')
expect(html).toContain('无法比对(主机不可达)')
})
@@ -451,18 +482,20 @@ describe('BackupScheduleView', () => {
expect(runMoment({ last_run_stamp: '20261009T060736Z', last_run_created_at: '2026-10-09T06:07:36Z' })).not.toBe('')
})
- it('体积格式化:MiB/GiB', () => {
- expect(formatBackupBytes(0)).toBe('—')
+ it('体积格式化:未知与零分开', () => {
+ expect(formatBackupBytes(0)).toBe('0 B')
+ expect(formatBackupBytes(null)).toBe('—')
+ expect(formatBackupBytes(undefined)).toBe('—')
expect(formatBackupBytes(1024 * 1024)).toBe('1.0 MiB')
expect(formatBackupBytes(2 * 1024 * 1024 * 1024)).toBe('2.00 GiB')
})
})
describe('整盘占用与告警', () => {
- it('没有只读盘点时:不显示示例容量,四条告警只报未知原因', () => {
+ it('没有快照时:不显示示例容量,四条告警只报未知原因', () => {
const html = view()
- expect(html).toContain('未接线 · 不显示估算容量')
- expect(html).toContain('容量来自只读挂载目录的 statfs 实测')
+ expect(html).toContain('占盘未知 · 不使用部分字节')
+ expect(html).toContain('宿主单项元数据采集器')
expect(html).toContain('无法判定')
expect(html).toContain('整盘总量 / 空闲 / 备份实际占盘:未接线')
// 原型里的示例容量不能被当成产品事实带进来。
@@ -521,7 +554,7 @@ describe('整盘占用与告警', () => {
expect(alerts.filter((item) => !item.known).map((item) => item.code)).toEqual(['disk_low', 'quota_low', 'both_low'])
})
- it('真实盘点:整盘色带取 statfs 容量与 st_blocks 实际占盘', () => {
+ it('真实快照:整盘色带取采集器容量与 st_blocks 实际占盘', () => {
const inventory = inventoryFixture()
const usage = inventoryUsage(inventory)
expect(usage).not.toBeNull()
@@ -535,35 +568,51 @@ describe('整盘占用与告警', () => {
expect(alerts.find((item) => item.code === 'quota_low')?.known).toBe(false)
const html = view({}, { inventory })
for (const text of [
- '只读挂载实测',
+ '宿主采集器实测',
'系统其他占用',
'备份实际占盘',
'可用',
'配额内/外 —(无配额字段)',
'文件系统已用',
- '挂载为只读',
- '挂载设备 20 与容器根盘 10 不同',
+ '只读挂载',
+ '宿主采集器:/dev/sdb1 挂在 /srv/kb-backups',
])
expect(html).toContain(text)
})
- it('挂载落在容器根盘:不把容器容量当主机磁盘,磁盘告警保持未知', () => {
+ it('不完整快照:容量图与占盘不使用部分字节', () => {
+ const base = inventoryFixture()
const inventory = inventoryFixture({
- mount: {
- container_root: '/',
- mount_verified: false,
- lives_on_container_root: true,
- read_only: true,
- evidence: '挂载设备与容器根盘相同(7):容量不代表备份主机磁盘',
+ metadata: {
+ ...base.metadata,
+ complete: false,
+ error: '采集不完整:遍历失败:PermissionError: Permission denied',
},
+ capacity: { measured: false, total_bytes: 0, free_bytes: 0, available_bytes: 0, used_bytes: 0 },
+ totals: { ...base.totals, apparent_bytes: null, actual_bytes: null, latest_actual_bytes: null, complete: false },
+ batches: base.batches.map((batch) => ({
+ ...batch,
+ apparent_bytes: null,
+ actual_bytes: null,
+ file_count: null,
+ sizes_complete: false,
+ sizes_error: '宿主采集器该项不完整,占盘未知',
+ databases: batch.databases.map((database) => ({
+ ...database,
+ apparent_bytes: null,
+ actual_bytes: null,
+ file_count: null,
+ })),
+ })),
})
expect(inventoryUsage(inventory)).toBeNull()
const alerts = inventoryAlerts(inventory)
expect(alerts.find((item) => item.code === 'disk_low')?.known).toBe(false)
- expect(alerts.find((item) => item.code === 'disk_low')?.detail).toContain('容器根盘')
+ expect(alerts.find((item) => item.code === 'disk_low')?.detail).toContain('不完整')
const html = view({}, { inventory })
- expect(html).toContain('容器根盘 · 不代表主机磁盘')
- expect(html).toContain('不据此判定备份主机磁盘')
+ expect(html).toContain('占盘未知 · 不使用部分字节')
+ expect(html).toContain('采集快照不完整:所有批次占盘与容量未知')
+ expect(html).toContain('占盘未知(采集不完整)')
expect(html).not.toContain('备份实际占盘 1.40 GiB')
})
diff --git a/web/src/BackupScheduleSection.tsx b/web/src/BackupScheduleSection.tsx
index f06567a..34554c1 100644
--- a/web/src/BackupScheduleSection.tsx
+++ b/web/src/BackupScheduleSection.tsx
@@ -13,8 +13,9 @@ import { fetchBackupInventory } from './backupInventory'
import type { BackupInventory, BackupInventoryBatch } from './backupInventory'
import './storageBackup.css'
-export const formatBackupBytes = (bytes: number): string => {
- if (!bytes) return '—'
+export const formatBackupBytes = (bytes: number | null | undefined): string => {
+ if (bytes === null || bytes === undefined || !Number.isFinite(bytes) || bytes < 0) return '—'
+ if (bytes === 0) return '0 B'
const mib = bytes / (1024 * 1024)
return mib >= 1024 ? `${(mib / 1024).toFixed(2)} GiB` : `${mib.toFixed(1)} MiB`
}
@@ -206,18 +207,27 @@ export interface InventoryUsage {
system_other: number
}
-// 只读挂载 + 实测容量 + 文件系统与容器根盘分离,三者同时成立才画整盘图。
-// 备份实际占盘取所有批次的 st_blocks 合计,不是 MANIFEST 的表观字节。
+// 完整新鲜的宿主快照 + 实测容量 + 采集器给出的文件系统,才画整盘图。
+// 备份实际占盘取快照的总实际分配,不是 MANIFEST 表观字节,也不接受部分字节。
export function inventoryUsage(inventory: BackupInventory | null): InventoryUsage | null {
if (
!inventory ||
!inventory.wired ||
+ !inventory.metadata.present ||
+ !inventory.metadata.valid ||
+ !inventory.metadata.fresh ||
+ !inventory.metadata.complete ||
!inventory.mount.mount_verified ||
!inventory.capacity.measured ||
- inventory.capacity.total_bytes <= 0
+ inventory.capacity.total_bytes <= 0 ||
+ inventory.totals.actual_bytes === null ||
+ inventory.totals.actual_bytes === undefined
) {
return null
}
+ if (inventory.batches.some((batch) => !batch.sizes_complete || batch.actual_bytes === null)) {
+ return null
+ }
const total = inventory.capacity.total_bytes
const used = Math.max(0, inventory.capacity.used_bytes)
const backup = Math.max(0, inventory.totals.actual_bytes)
@@ -236,20 +246,29 @@ export function inventoryAlerts(inventory: BackupInventory | null): StorageAlert
const usage = inventoryUsage(inventory)
const latest = inventory?.batches[0]
const capacityKnown = Boolean(usage)
- const latestBytes = latest?.actual_bytes ?? 0
- const diskKnown = capacityKnown && latestBytes > 0
- const diskActive = diskKnown && latestBytes > usage!.free
+ const latestBytes = latest?.actual_bytes ?? null
+ const diskKnown =
+ capacityKnown && latest !== undefined && latest.sizes_complete && latestBytes !== null && latestBytes !== undefined
+ const diskActive = diskKnown && latestBytes! > usage!.free
const diskDetail = !inventory
- ? '尚未读取备份目录'
+ ? '尚未读取宿主元数据快照'
: !inventory.wired
- ? '只读盘点未接线'
- : !inventory.mount.mount_verified
- ? '目录位于容器根盘,读数不代表备份主机磁盘'
- : !inventory.capacity.measured
- ? inventory.capacity.error || '未读到文件系统容量'
- : latestBytes <= 0
- ? '没有可参考的批次实际占盘'
- : `剩余可用 ${formatGib(usage!.free)} GiB,最近一批实际占盘 ${formatGib(latestBytes)} GiB(参考值,不含策略预留)`
+ ? '元数据快照未接线'
+ : !inventory.metadata.present
+ ? '元数据快照缺失'
+ : !inventory.metadata.valid
+ ? inventory.metadata.error || '元数据快照无效'
+ : !inventory.metadata.fresh
+ ? '元数据快照已陈旧'
+ : !inventory.metadata.complete
+ ? '元数据快照不完整:占盘与容量未知'
+ : !inventory.mount.mount_verified
+ ? '宿主采集器未给出可用文件系统'
+ : !inventory.capacity.measured
+ ? inventory.capacity.error || '未读到文件系统容量'
+ : latestBytes === null || latestBytes === undefined
+ ? '最近批次占盘未知'
+ : `剩余可用 ${formatGib(usage!.free)} GiB,最近一批实际占盘 ${formatGib(latestBytes)} GiB(参考值,不含策略预留)`
return [
{
code: 'disk_low',
@@ -308,6 +327,9 @@ export async function copyBackupPath(value: string, button?: HTMLButtonElement |
const manifestLabel = (batch: BackupInventoryBatch): string =>
batch.manifest_state === 'ok' ? '清单完整' : batch.manifest_state === 'missing' ? '清单缺失' : '清单损坏'
+const inventoryMetadataAvailable = (inventory: BackupInventory): boolean =>
+ inventory.metadata.present && inventory.metadata.valid && inventory.metadata.fresh
+
// 备份执行主机上的整库逻辑备份(全部业务库一次 pg_dump)。
// 页面只展示接口真实给出的读数;目录、配额、预留、子库路径、历史批次与恢复
// 验证在后端契约里还没有字段,保留原型位置并写明"未接线"。
@@ -407,8 +429,13 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
const alerts = disk ? storageAlerts(disk) : inventoryAlerts(inventory)
const latestBatch: BackupInventoryBatch | null = inventory?.batches[0] ?? null
const inventoryFigure = inventoryUsage(inventory)
- const inventoryReady = Boolean(inventory?.wired && !inventory.error)
- const readyInventory = inventory && inventory.wired && !inventory.error ? inventory : null
+ const inventoryReady = Boolean(
+ inventory?.wired && inventory.metadata.present && inventory.metadata.valid && inventory.metadata.fresh
+ )
+ const readyInventory =
+ inventory && inventory.wired && inventory.metadata.present && inventory.metadata.valid && inventory.metadata.fresh
+ ? inventory
+ : null
const inventoryDatabases = latestBatch?.databases.map((item) => item.name) ?? []
const scopeDatabases = inventoryDatabases.length ? inventoryDatabases : schedule.last_run_databases
const scopeDatabaseCount = scopeDatabases.length
@@ -443,12 +470,14 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
{inventoryLoading
- ? '文件盘点读取中'
+ ? '元数据读取中'
: inventoryReady
- ? '文件盘点已接线'
- : inventory?.error
- ? '文件盘点不可读'
- : '文件盘点未接线'}
+ ? inventory?.metadata.complete
+ ? '元数据快照有效'
+ : '元数据快照不完整'
+ : inventory?.metadata.error
+ ? '元数据快照不可用'
+ : '元数据未接线'}
@@ -461,7 +490,7 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
-
{inventory?.host_root || `${schedule.host_target || '(未配置)'} 本地备份根目录`}
- {inventoryReady ? '只读挂载盘点;平台没有写路径' : '备份目录未接线或不可读,不在页面猜测'}
+ {inventoryReady ? '宿主采集器快照(只读);平台没有写路径' : '元数据快照未接线或不可用,不在页面猜测'}
- 执行范围
@@ -480,7 +509,7 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
POST /api/v1/backup-schedule/run 没有单库参数,一次就是该主机全部业务库的整批
pg_dump。用单库按钮触发会连整批一起跑,因此本页不开放单库动作;单库恢复请复制「备份记录」里该库的
- 完整子目录(来自只读盘点),不要自己拼路径。
+ 完整子目录(来自宿主元数据快照),不要自己拼路径。
@@ -496,9 +525,13 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
{latestBatch
- ? `最近一批 ${latestBatch.stamp} · ${formatBackupMoment(latestBatch.created_at)} · ${scopeDatabaseCount} 个数据库 · 表观 ${formatBackupBytes(latestBatch.apparent_bytes)} · 实际占盘 ${formatBackupBytes(latestBatch.actual_bytes)} · ${latestBatch.duration_seconds} 秒`
+ ? `最近一批 ${latestBatch.stamp} · ${formatBackupMoment(latestBatch.created_at)} · ${scopeDatabaseCount} 个数据库 · 表观 ${formatBackupBytes(latestBatch.apparent_bytes)} · ${
+ latestBatch.actual_bytes === null
+ ? '实际占盘未知(采集不完整)'
+ : `实际占盘 ${formatBackupBytes(latestBatch.actual_bytes)}`
+ } · ${latestBatch.duration_seconds} 秒`
: hasLastRun
- ? `SSH 读回最近一次 ${schedule.last_run_stamp} · ${databaseCount} 个数据库 · ${formatBackupBytes(schedule.last_run_total_bytes)}(文件盘点未接线,以下仅 SSH 结果)`
+ ? `SSH 读回最近一次 ${schedule.last_run_stamp} · ${databaseCount} 个数据库 · ${formatBackupBytes(schedule.last_run_total_bytes)}(元数据快照未接线,以下仅 SSH 结果)`
: '还没有从主机读到任何批次。'}
{schedule.running ? (
@@ -540,15 +573,7 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
整盘占用与告警
- {usage
- ? '已读到主机读数'
- : inventoryFigure
- ? inventory?.mount.read_only
- ? '只读挂载实测'
- : '实测(挂载可写)'
- : inventory?.capacity.measured
- ? '容器根盘(不可作主机容量)'
- : '未接线'}
+ {usage ? '已读到主机读数' : inventoryFigure ? '宿主采集器实测' : '占盘未知'}
{usage && disk ? (
@@ -652,33 +677,19 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
)· 文件系统已用 {formatGib(inventoryFigure.used)} GiB · 可用 {formatGib(inventoryFigure.free)} GiB
- {inventory.mount.evidence} · 挂载点 {inventory.root} · 采集于 {formatBackupMoment(inventory.observed_at)}
- {inventory.mount.read_only ? ' · 挂载为只读' : ' · 挂载不是只读(部署需改 :ro)'}
+ {inventory.mount.evidence} · 挂载点 {inventory.mount.mount_point || '—'} · 采集于{' '}
+ {formatBackupMoment(inventory.metadata.collected_at || inventory.observed_at)}
+ {inventory.mount.read_only ? ' · 只读挂载' : ' · 挂载可写(采集器只读)'}
>
- ) : inventory?.capacity.measured ? (
- <>
-
- 容器根盘 · 不代表主机磁盘
-
-
- 容器根盘实测 {formatGib(inventory.capacity.total_bytes)} GiB,可用{' '}
- {formatGib(inventory.capacity.available_bytes)} GiB:仅作排障,不据此判定备份主机磁盘。
-
- {inventory.mount.evidence}
- >
) : (
<>
- {inventoryLoading ? '正在读取只读挂载…' : '未接线 · 不显示估算容量'}
+ {inventoryLoading ? '正在读取宿主元数据快照…' : '占盘未知 · 不使用部分字节'}
{['系统其他占用', '备份实际占盘', '可用', '配额内/外'].map((label, index) => (
@@ -689,14 +700,15 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
))}
- 整盘总量 / 空闲 / 备份实际占盘:{inventoryError || inventory?.error || '未接线'}
+ 整盘总量 / 空闲 / 备份实际占盘:
+ {inventoryError || inventory?.metadata.error || inventory?.error || '未接线'}
>
)}
- 容量来自只读挂载目录的 statfs 实测,并与容器根盘比较设备号;同一设备时不把容器容量当主机容量。 备份占盘按文件
- st_blocks 统计(实际分配),不是 MANIFEST 的表观字节。配额与策略预留仍无后端字段,
- 四项告警中只有磁盘项能按实测判定。
+ 容量与实际占盘来自宿主单项元数据采集器(stat/du 元数据,不读数据库内容);API 不遍历备份目录。
+ 快照陈旧、缺失或不完整时,容量图与任何可写预测都不使用部分字节。配额与策略预留仍无后端字段,
+ 四项告警中只有磁盘项能按完整快照判定。
{storageAlertSummary(alerts)}
@@ -742,7 +754,7 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
value={inventory?.host_root || ''}
readOnly
disabled
- placeholder={inventoryReady ? '' : '只读盘点未接线'}
+ placeholder={inventoryReady ? '' : '元数据快照未接线'}
aria-label="备份主机上的目录(只读展示)"
/>
@@ -752,8 +764,8 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
{inventoryReady
- ? '目录来自只读挂载来源,只读展示;修改目录需部署变更,平台没有写接口。'
- : '只读盘点未接线:目录不可证明,不能按设置推定。'}
+ ? '目录来自宿主元数据快照,只读展示;修改目录需部署变更,平台没有写接口。'
+ : '元数据快照未接线:目录不可证明,不能按设置推定。'}