fix(backup): 宿主采集器按 du 口径去重硬链接并拒绝清单符号链接
备份目录 root:root 0700,API 不再遍历;宿主采集器只读 stat/du,原子写快照。统计包含目录自身、树内 (dev,ino) 硬链接去重,单库与整批各自独立与 du -sB1 对齐;MANIFEST 仅接受目录内常规非符号链接文件并 O_NOFOLLOW 打开。快照缺失/陈旧/不完整时批次与子库字节为 null,页面不画容量图、不使用部分字节。
This commit is contained in:
@@ -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
|
||||
|
||||
+1
-1
@@ -1978,7 +1978,7 @@
|
||||
"Settings"
|
||||
],
|
||||
"operationId": "getBackupScheduleInventory",
|
||||
"summary": "只读盘点备份批次、子库完整路径与实际占盘、挂载文件系统实测容量",
|
||||
"summary": "读取宿主元数据快照:批次、子库完整路径、实际占盘与文件系统容量(陈旧/不完整一律未知)",
|
||||
"responses": {
|
||||
"200": {
|
||||
"$ref": "#/components/responses/Envelope"
|
||||
|
||||
+5
-4
@@ -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},
|
||||
})
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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` 有名字
|
||||
|
||||
+165
-124
@@ -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` | 子库完整宿主路径,必须等于 `<batch>/<name>.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 的路径校验要求批次路径精确等于 `<root>/<stamp>`、子库精确等于
|
||||
`<batch>/<name>.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. 写操作的角色细分(目前写路径统一管理员;若要“备份操作员”需另立角色)。
|
||||
6. MANIFEST 修复/重建。
|
||||
7. 采集器安装/权限变更自动化(属部署与主机权限,必须人工批准)。
|
||||
8. 写操作角色细分(目前统一管理员)。
|
||||
@@ -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") {
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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())
|
||||
|
||||
@@ -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])
|
||||
}
|
||||
}
|
||||
|
||||
Executable
+581
@@ -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())
|
||||
@@ -74,17 +74,37 @@ const diskFixture = (overrides: Partial<StorageDiskObservation> = {}): StorageDi
|
||||
const inventoryFixture = (overrides: Partial<BackupInventory> = {}): 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<BackupInventory> = {}): 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<BackupInventory> = {}): 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('<dt>备份脚本</dt><dd>缺失</dd>')
|
||||
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')
|
||||
})
|
||||
|
||||
|
||||
@@ -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) {
|
||||
</span>
|
||||
<span className={`storage-chip ${inventoryReady ? 'ok' : 'off'}`}>
|
||||
{inventoryLoading
|
||||
? '文件盘点读取中'
|
||||
? '元数据读取中'
|
||||
: inventoryReady
|
||||
? '文件盘点已接线'
|
||||
: inventory?.error
|
||||
? '文件盘点不可读'
|
||||
: '文件盘点未接线'}
|
||||
? inventory?.metadata.complete
|
||||
? '元数据快照有效'
|
||||
: '元数据快照不完整'
|
||||
: inventory?.metadata.error
|
||||
? '元数据快照不可用'
|
||||
: '元数据未接线'}
|
||||
</span>
|
||||
</div>
|
||||
<dl className="storage-facts">
|
||||
@@ -461,7 +490,7 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
|
||||
<dd>
|
||||
{inventory?.host_root || `${schedule.host_target || '(未配置)'} 本地备份根目录`}
|
||||
<span className="storage-inline-note">
|
||||
{inventoryReady ? '只读挂载盘点;平台没有写路径' : '备份目录未接线或不可读,不在页面猜测'}
|
||||
{inventoryReady ? '宿主采集器快照(只读);平台没有写路径' : '元数据快照未接线或不可用,不在页面猜测'}
|
||||
</span>
|
||||
</dd>
|
||||
<dt>执行范围</dt>
|
||||
@@ -480,7 +509,7 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
|
||||
<p className="hint">
|
||||
<code>POST /api/v1/backup-schedule/run</code> 没有单库参数,一次就是该主机全部业务库的整批
|
||||
pg_dump。用单库按钮触发会连整批一起跑,因此本页不开放单库动作;单库恢复请复制「备份记录」里该库的
|
||||
完整子目录(来自只读盘点),不要自己拼路径。
|
||||
完整子目录(来自宿主元数据快照),不要自己拼路径。
|
||||
</p>
|
||||
</div>
|
||||
</section>
|
||||
@@ -496,9 +525,13 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
|
||||
</div>
|
||||
<p>
|
||||
{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 结果)`
|
||||
: '还没有从主机读到任何批次。'}
|
||||
</p>
|
||||
{schedule.running ? (
|
||||
@@ -540,15 +573,7 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
|
||||
<div className="storage-block-heading">
|
||||
<h3 id="storage-disk-heading">整盘占用与告警</h3>
|
||||
<span className="storage-chip off">
|
||||
{usage
|
||||
? '已读到主机读数'
|
||||
: inventoryFigure
|
||||
? inventory?.mount.read_only
|
||||
? '只读挂载实测'
|
||||
: '实测(挂载可写)'
|
||||
: inventory?.capacity.measured
|
||||
? '容器根盘(不可作主机容量)'
|
||||
: '未接线'}
|
||||
{usage ? '已读到主机读数' : inventoryFigure ? '宿主采集器实测' : '占盘未知'}
|
||||
</span>
|
||||
</div>
|
||||
{usage && disk ? (
|
||||
@@ -652,33 +677,19 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
|
||||
)· 文件系统已用 {formatGib(inventoryFigure.used)} GiB · 可用 {formatGib(inventoryFigure.free)} GiB
|
||||
</p>
|
||||
<small>
|
||||
{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 ? ' · 只读挂载' : ' · 挂载可写(采集器只读)'}
|
||||
</small>
|
||||
</>
|
||||
) : inventory?.capacity.measured ? (
|
||||
<>
|
||||
<div
|
||||
className="storage-disk-track storage-disk-track-unknown"
|
||||
role="img"
|
||||
aria-label="目录位于容器根盘,容量不代表备份主机磁盘"
|
||||
>
|
||||
<span>容器根盘 · 不代表主机磁盘</span>
|
||||
</div>
|
||||
<p className="storage-metric">
|
||||
容器根盘实测 {formatGib(inventory.capacity.total_bytes)} GiB,可用{' '}
|
||||
{formatGib(inventory.capacity.available_bytes)} GiB:仅作排障,不据此判定备份主机磁盘。
|
||||
</p>
|
||||
<small>{inventory.mount.evidence}</small>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div
|
||||
className="storage-disk-track storage-disk-track-unknown"
|
||||
role="img"
|
||||
aria-label="整盘占用未接线:没有可读的只读挂载"
|
||||
aria-label="整盘占用未知:没有完整新鲜的宿主快照"
|
||||
>
|
||||
<span>{inventoryLoading ? '正在读取只读挂载…' : '未接线 · 不显示估算容量'}</span>
|
||||
<span>{inventoryLoading ? '正在读取宿主元数据快照…' : '占盘未知 · 不使用部分字节'}</span>
|
||||
</div>
|
||||
<div className="storage-disk-legend">
|
||||
{['系统其他占用', '备份实际占盘', '可用', '配额内/外'].map((label, index) => (
|
||||
@@ -689,14 +700,15 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
|
||||
))}
|
||||
</div>
|
||||
<p className="storage-metric">
|
||||
整盘总量 / 空闲 / 备份实际占盘:{inventoryError || inventory?.error || '未接线'}
|
||||
整盘总量 / 空闲 / 备份实际占盘:
|
||||
{inventoryError || inventory?.metadata.error || inventory?.error || '未接线'}
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
<p className="hint">
|
||||
容量来自只读挂载目录的 statfs 实测,并与容器根盘比较设备号;同一设备时不把容器容量当主机容量。 备份占盘按文件
|
||||
st_blocks 统计(实际分配),不是 MANIFEST 的表观字节。配额与策略预留仍无后端字段,
|
||||
四项告警中只有磁盘项能按实测判定。
|
||||
容量与实际占盘来自宿主单项元数据采集器(stat/du 元数据,不读数据库内容);API 不遍历备份目录。
|
||||
快照陈旧、缺失或不完整时,容量图与任何可写预测都不使用部分字节。配额与策略预留仍无后端字段,
|
||||
四项告警中只有磁盘项能按完整快照判定。
|
||||
</p>
|
||||
<p className="storage-alert-summary">{storageAlertSummary(alerts)}</p>
|
||||
<ul className="storage-alerts">
|
||||
@@ -742,7 +754,7 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
|
||||
value={inventory?.host_root || ''}
|
||||
readOnly
|
||||
disabled
|
||||
placeholder={inventoryReady ? '' : '只读盘点未接线'}
|
||||
placeholder={inventoryReady ? '' : '元数据快照未接线'}
|
||||
aria-label="备份主机上的目录(只读展示)"
|
||||
/>
|
||||
</label>
|
||||
@@ -752,8 +764,8 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
|
||||
</button>
|
||||
<span className="hint">
|
||||
{inventoryReady
|
||||
? '目录来自只读挂载来源,只读展示;修改目录需部署变更,平台没有写接口。'
|
||||
: '只读盘点未接线:目录不可证明,不能按设置推定。'}
|
||||
? '目录来自宿主元数据快照,只读展示;修改目录需部署变更,平台没有写接口。'
|
||||
: '元数据快照未接线:目录不可证明,不能按设置推定。'}
|
||||
</span>
|
||||
</div>
|
||||
<label className="storage-checkbox">
|
||||
@@ -858,41 +870,53 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
|
||||
<h3 id="storage-runs-heading">备份记录</h3>
|
||||
<span className="hint">
|
||||
{readyInventory
|
||||
? `${readyInventory.totals.batch_count} 批 · 只读盘点 · 实际占盘 ${formatBackupBytes(readyInventory.totals.actual_bytes)}`
|
||||
: '只读盘点'}
|
||||
? `${readyInventory.totals.batch_count} 批 · 元数据快照 · 实际占盘 ${formatBackupBytes(readyInventory.totals.actual_bytes)}`
|
||||
: '元数据快照'}
|
||||
</span>
|
||||
<button type="button" onClick={onReloadInventory} disabled={inventoryLoading}>
|
||||
{inventoryLoading ? '盘点中…' : '重新盘点'}
|
||||
{inventoryLoading ? '读取中…' : '重新读取快照'}
|
||||
</button>
|
||||
</div>
|
||||
{inventoryLoading && !inventory ? <p className="hint">正在读取只读挂载与 MANIFEST…</p> : null}
|
||||
{inventoryLoading && !inventory ? <p className="hint">正在读取宿主元数据快照…</p> : null}
|
||||
{inventoryError ? (
|
||||
<p className="error-message" role="alert">
|
||||
盘点请求失败:{inventoryError}。不能用 SSH 的“最近一次”代替历史;请检查 API 到只读挂载的接线。
|
||||
快照请求失败:{inventoryError}。不能用 SSH 的“最近一次”代替历史;请检查 API 到快照挂载的接线。
|
||||
</p>
|
||||
) : null}
|
||||
{inventory && !inventory.wired ? (
|
||||
<p className="hint">
|
||||
只读盘点未接线:{inventory.error}。部署需把备份目录以 <code>:ro</code> 挂进 API (见
|
||||
元数据快照未接线:{inventory.metadata.error}。部署需在备份主机运行单次采集器并把输出目录只读挂进 API(见
|
||||
docs/STORAGE_BACKUP_READONLY_API.md);未读到批次不等于没有备份。
|
||||
</p>
|
||||
) : null}
|
||||
{inventory && inventory.wired && inventory.error ? (
|
||||
{inventory && inventory.wired && !inventoryMetadataAvailable(inventory) ? (
|
||||
<p className="error-message" role="alert">
|
||||
只读目录不可读:{inventory.error}
|
||||
元数据快照不可用:{inventory.metadata.error || inventory.error || '缺失/陈旧/无效'}
|
||||
</p>
|
||||
) : null}
|
||||
{readyInventory ? (
|
||||
<>
|
||||
<p className="hint">
|
||||
最近批次 {readyInventory.totals.latest_stamp || '—'} · 共 {readyInventory.totals.batch_count} 批 /{' '}
|
||||
{readyInventory.totals.database_count} 个子库 · 表观{' '}
|
||||
{formatBackupBytes(readyInventory.totals.apparent_bytes)} · 实际占盘{' '}
|
||||
{formatBackupBytes(readyInventory.totals.actual_bytes)}。批次与路径来自只读目录,不依赖 SSH 计划读回。
|
||||
{readyInventory.totals.database_count} 个子库 ·{' '}
|
||||
{readyInventory.metadata.complete && readyInventory.totals.actual_bytes !== null ? (
|
||||
<>
|
||||
表观 {formatBackupBytes(readyInventory.totals.apparent_bytes)} · 实际占盘{' '}
|
||||
{formatBackupBytes(readyInventory.totals.actual_bytes)}。
|
||||
</>
|
||||
) : (
|
||||
<>采集快照不完整:所有批次占盘与容量未知。</>
|
||||
)}{' '}
|
||||
路径来自宿主快照,不依赖 SSH 计划读回。
|
||||
</p>
|
||||
<p className="hint">
|
||||
采集于 {formatBackupMoment(readyInventory.metadata.collected_at)} · 年龄{' '}
|
||||
{readyInventory.metadata.age_seconds} 秒 / 上限 {readyInventory.metadata.max_age_seconds} 秒 · 宿主{' '}
|
||||
{readyInventory.metadata.host || '—'} · 快照 {readyInventory.metadata.generation || '—'}
|
||||
</p>
|
||||
{readyInventory.batches.length === 0 ? (
|
||||
<p className="hint">
|
||||
挂载可读,但没有批次目录(可能尚未执行,或挂载到了空目录);这不能证明备份成功或失败。
|
||||
宿主快照可读,但没有批次目录(可能尚未执行,或采集到空目录);这不能证明备份成功或失败。
|
||||
</p>
|
||||
) : null}
|
||||
{readyInventory.batches.map((batch, index) => {
|
||||
@@ -907,25 +931,28 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
|
||||
<strong className={failedDatabases.length || batch.manifest_state !== 'ok' ? 'off' : 'ok'}>
|
||||
{failedDatabases.length
|
||||
? `有失败 ${failedDatabases.length} 个`
|
||||
: `实际占盘 ${formatBackupBytes(batch.actual_bytes)}`}
|
||||
: batch.actual_bytes === null
|
||||
? '占盘未知(采集不完整)'
|
||||
: `实际占盘 ${formatBackupBytes(batch.actual_bytes)}`}
|
||||
</strong>
|
||||
</summary>
|
||||
<p>
|
||||
批次戳 {batch.stamp} · 表观 {formatBackupBytes(batch.apparent_bytes)} · 实际占盘{' '}
|
||||
{formatBackupBytes(batch.actual_bytes)} · {batch.file_count} 个文件
|
||||
{batch.actual_bytes === null ? '未知' : formatBackupBytes(batch.actual_bytes)} ·{' '}
|
||||
{batch.file_count ?? '—'} 个文件
|
||||
{batch.duration_seconds ? ` · 耗时 ${batch.duration_seconds} 秒` : ''}
|
||||
{batch.kind ? ` · ${batch.kind}` : ''}
|
||||
</p>
|
||||
{batch.manifest_state === 'ok' ? null : (
|
||||
<p className="error-message">
|
||||
{batch.manifest_state === 'missing'
|
||||
? '此批次没有 MANIFEST.json:只能按目录统计占盘,无法确认完整性、耗时与库列表。'
|
||||
: `此批次清单损坏:${batch.manifest_error || '无法解析'};只能按目录统计占盘。`}
|
||||
? '此批次没有 MANIFEST.json:完整性、耗时与库列表无法确认;占盘仅在快照完整时可信。'
|
||||
: `此批次清单损坏:${batch.manifest_error || '无法解析'};库列表来自目录名,占盘仅在快照完整时可信。`}
|
||||
</p>
|
||||
)}
|
||||
{!batch.sizes_complete ? (
|
||||
<p className="error-message">
|
||||
实际占盘未扫全:{batch.sizes_error || '文件数超过上限'};显示的是已扫描部分。
|
||||
采集不完整:占盘未知({batch.sizes_error || '宿主采集器未给出完整统计'});不使用部分字节。
|
||||
</p>
|
||||
) : null}
|
||||
<div className="storage-path-row">
|
||||
@@ -934,7 +961,7 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
|
||||
<button
|
||||
type="button"
|
||||
disabled={!batch.host_path}
|
||||
title={batch.host_path ? '复制完整主机路径' : '没有主机路径(只读盘点未配置主机根)'}
|
||||
title={batch.host_path ? '复制完整主机路径' : '没有主机路径(快照未配置主机根)'}
|
||||
onClick={(event) => void copyBackupPath(batch.host_path, event.currentTarget)}
|
||||
>
|
||||
复制目录
|
||||
@@ -949,7 +976,7 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
|
||||
</span>
|
||||
<small>
|
||||
实际 {formatBackupBytes(database.actual_bytes)} · 表观{' '}
|
||||
{formatBackupBytes(database.apparent_bytes)} · {database.file_count} 个文件
|
||||
{formatBackupBytes(database.apparent_bytes)} · {database.file_count ?? '—'} 个文件
|
||||
{database.in_manifest ? '' : ' · 不在清单库列表'}
|
||||
</small>
|
||||
<div className="storage-path-row storage-sublibrary-path">
|
||||
@@ -983,14 +1010,16 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
|
||||
{readyInventory.skipped.map((item) => `${item.name}(${item.reason})`).join(';')}
|
||||
</p>
|
||||
) : null}
|
||||
{readyInventory.truncated ? <p className="hint">目录或文件数超过扫描上限,列表与占盘为部分结果。</p> : null}
|
||||
{readyInventory.truncated ? (
|
||||
<p className="hint">快照被截断:批次或文件超过采集上限,占盘未知(不使用部分结果)。</p>
|
||||
) : null}
|
||||
<p className="hint">
|
||||
盘点采集于 {formatBackupMoment(readyInventory.observed_at)} · 挂载点 {readyInventory.root || '—'} · 来源{' '}
|
||||
{readyInventory.source || '—'}
|
||||
快照采集于 {formatBackupMoment(readyInventory.metadata.collected_at)} · 快照文件{' '}
|
||||
{readyInventory.metadata.path || '—'} · 来源 {readyInventory.source || '—'}
|
||||
</p>
|
||||
</>
|
||||
) : null}
|
||||
{!inventory && !inventoryLoading && !inventoryError ? <p className="hint">尚未读取只读盘点。</p> : null}
|
||||
{!inventory && !inventoryLoading && !inventoryError ? <p className="hint">尚未读取宿主元数据快照。</p> : null}
|
||||
</section>
|
||||
|
||||
<section className="storage-block" aria-labelledby="storage-host-heading">
|
||||
@@ -1035,7 +1064,7 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
|
||||
{schedule.last_run_stamp ? (runFailed ? ' · 有失败/读取错误' : ' · 成功') : ''}
|
||||
</dd>
|
||||
<dt>最近一次成功</dt>
|
||||
<dd>未从主机读取(不能用最近一次运行代替成功;历史批次以「备份记录」的只读盘点为准)</dd>
|
||||
<dd>未从主机读取(不能用最近一次运行代替成功;历史批次以「备份记录」的元数据快照为准)</dd>
|
||||
<dt>备份耗时 / 体积</dt>
|
||||
<dd>
|
||||
{schedule.last_run_stamp
|
||||
@@ -1285,7 +1314,7 @@ export function BackupScheduleSection() {
|
||||
inventoryLoading={inventoryLoading}
|
||||
inventoryError={inventoryError}
|
||||
onReloadInventory={() => void loadInventory()}
|
||||
// disk 不传:生产只认只读挂载盘点;disk 仅测试夹具用于验证告警分支。
|
||||
// disk 不传:生产只认宿主元数据快照;disk 仅测试夹具用于验证告警分支。
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -5,16 +5,36 @@ import { fetchBackupInventory } from './backupInventory'
|
||||
const payload = {
|
||||
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-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',
|
||||
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)',
|
||||
mount_point: '/srv/kb-backups',
|
||||
device: '/dev/sdb1',
|
||||
fs_type: 'ext4',
|
||||
},
|
||||
capacity: {
|
||||
measured: true,
|
||||
@@ -46,7 +66,7 @@ const payload = {
|
||||
present: true,
|
||||
failed: false,
|
||||
in_manifest: true,
|
||||
apparent_bytes: 696320,
|
||||
apparent_bytes: 700000,
|
||||
actual_bytes: 720896,
|
||||
file_count: 12,
|
||||
},
|
||||
@@ -60,6 +80,7 @@ const payload = {
|
||||
actual_bytes: 1500000000,
|
||||
latest_stamp: '20261118T193001Z',
|
||||
latest_actual_bytes: 1500000000,
|
||||
complete: true,
|
||||
},
|
||||
incomplete_count: 1,
|
||||
skipped: [],
|
||||
|
||||
+71
-23
@@ -1,11 +1,32 @@
|
||||
// 「存储与备份 → 备份记录」只读盘点接口。真实字段来自备份主机目录的只读挂载:
|
||||
// 批次目录、每个库的完整子目录、文件系统实测容量;不是 SSH 计划读回的副产物。
|
||||
// 「存储与备份 → 备份记录」只读快照接口。真实字段来自备份主机上的单次元数据
|
||||
// 采集器:批次、子库完整路径、实际占盘、文件系统容量。API 不遍历备份目录,
|
||||
// 快照陈旧/不完整时所有字节字段为 null,页面必须显示未知。
|
||||
export interface BackupInventoryMetadata {
|
||||
configured: boolean
|
||||
present: boolean
|
||||
valid: boolean
|
||||
fresh: boolean
|
||||
complete: boolean
|
||||
path: string
|
||||
collected_at: string
|
||||
age_seconds: number
|
||||
max_age_seconds: number
|
||||
schema_version: number
|
||||
generation: string
|
||||
host: string
|
||||
collector_version: string
|
||||
error: string
|
||||
}
|
||||
|
||||
export interface BackupInventoryMount {
|
||||
container_root: string
|
||||
mount_verified: boolean
|
||||
lives_on_container_root: boolean
|
||||
read_only: boolean
|
||||
evidence: string
|
||||
mount_point: string
|
||||
device: string
|
||||
fs_type: string
|
||||
error?: string
|
||||
}
|
||||
|
||||
@@ -26,9 +47,9 @@ export interface BackupInventoryDatabase {
|
||||
present: boolean
|
||||
failed: boolean
|
||||
in_manifest: boolean
|
||||
apparent_bytes: number
|
||||
actual_bytes: number
|
||||
file_count: number
|
||||
apparent_bytes: number | null
|
||||
actual_bytes: number | null
|
||||
file_count: number | null
|
||||
}
|
||||
|
||||
export type BackupManifestState = 'ok' | 'missing' | 'invalid'
|
||||
@@ -44,10 +65,10 @@ export interface BackupInventoryBatch {
|
||||
created_at: string
|
||||
started_at: string
|
||||
duration_seconds: number
|
||||
manifest_total_bytes: number
|
||||
apparent_bytes: number
|
||||
actual_bytes: number
|
||||
file_count: number
|
||||
manifest_total_bytes: number | null
|
||||
apparent_bytes: number | null
|
||||
actual_bytes: number | null
|
||||
file_count: number | null
|
||||
sizes_complete: boolean
|
||||
sizes_error?: string
|
||||
databases: BackupInventoryDatabase[]
|
||||
@@ -60,21 +81,24 @@ export interface BackupInventorySkipped {
|
||||
|
||||
export interface BackupInventory {
|
||||
wired: boolean
|
||||
metadata: BackupInventoryMetadata
|
||||
root: string
|
||||
host_root: string
|
||||
source: string
|
||||
observed_at: string
|
||||
error?: string
|
||||
measurement: string
|
||||
mount: BackupInventoryMount
|
||||
capacity: BackupInventoryCapacity
|
||||
batches: BackupInventoryBatch[]
|
||||
totals: {
|
||||
batch_count: number
|
||||
database_count: number
|
||||
apparent_bytes: number
|
||||
actual_bytes: number
|
||||
apparent_bytes: number | null
|
||||
actual_bytes: number | null
|
||||
latest_stamp: string
|
||||
latest_actual_bytes: number
|
||||
latest_actual_bytes: number | null
|
||||
complete: boolean
|
||||
}
|
||||
incomplete_count: number
|
||||
skipped: BackupInventorySkipped[]
|
||||
@@ -86,6 +110,8 @@ const record = (value: unknown): value is Record<string, unknown> =>
|
||||
|
||||
const asString = (value: unknown): string => (typeof value === 'string' ? value : '')
|
||||
const asNumber = (value: unknown): number => (typeof value === 'number' && Number.isFinite(value) ? value : 0)
|
||||
const asNumberOrNull = (value: unknown): number | null =>
|
||||
typeof value === 'number' && Number.isFinite(value) ? value : null
|
||||
const asBool = (value: unknown): boolean => value === true
|
||||
const asList = (value: unknown): unknown[] => (Array.isArray(value) ? value : [])
|
||||
|
||||
@@ -102,9 +128,9 @@ function databaseProjection(item: unknown): BackupInventoryDatabase {
|
||||
present: asBool(value.present),
|
||||
failed: asBool(value.failed),
|
||||
in_manifest: asBool(value.in_manifest),
|
||||
apparent_bytes: asNumber(value.apparent_bytes),
|
||||
actual_bytes: asNumber(value.actual_bytes),
|
||||
file_count: asNumber(value.file_count),
|
||||
apparent_bytes: asNumberOrNull(value.apparent_bytes),
|
||||
actual_bytes: asNumberOrNull(value.actual_bytes),
|
||||
file_count: asNumberOrNull(value.file_count),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -121,10 +147,10 @@ function batchProjection(item: unknown): BackupInventoryBatch {
|
||||
created_at: asString(value.created_at),
|
||||
started_at: asString(value.started_at),
|
||||
duration_seconds: asNumber(value.duration_seconds),
|
||||
manifest_total_bytes: asNumber(value.manifest_total_bytes),
|
||||
apparent_bytes: asNumber(value.apparent_bytes),
|
||||
actual_bytes: asNumber(value.actual_bytes),
|
||||
file_count: asNumber(value.file_count),
|
||||
manifest_total_bytes: asNumberOrNull(value.manifest_total_bytes),
|
||||
apparent_bytes: asNumberOrNull(value.apparent_bytes),
|
||||
actual_bytes: asNumberOrNull(value.actual_bytes),
|
||||
file_count: asNumberOrNull(value.file_count),
|
||||
sizes_complete: asBool(value.sizes_complete),
|
||||
sizes_error: asString(value.sizes_error),
|
||||
databases: asList(value.databases).map(databaseProjection),
|
||||
@@ -136,22 +162,43 @@ function inventoryProjection(value: unknown): BackupInventory {
|
||||
if (!record(value) || typeof value.wired !== 'boolean') {
|
||||
throw new Error('备份盘点响应无效(缺 wired)')
|
||||
}
|
||||
const metadata = record(value.metadata) ? value.metadata : {}
|
||||
const mount = record(value.mount) ? value.mount : {}
|
||||
const capacity = record(value.capacity) ? value.capacity : {}
|
||||
const totals = record(value.totals) ? value.totals : {}
|
||||
return {
|
||||
wired: value.wired,
|
||||
metadata: {
|
||||
configured: asBool(metadata.configured),
|
||||
present: asBool(metadata.present),
|
||||
valid: asBool(metadata.valid),
|
||||
fresh: asBool(metadata.fresh),
|
||||
complete: asBool(metadata.complete),
|
||||
path: asString(metadata.path),
|
||||
collected_at: asString(metadata.collected_at),
|
||||
age_seconds: asNumber(metadata.age_seconds),
|
||||
max_age_seconds: asNumber(metadata.max_age_seconds),
|
||||
schema_version: asNumber(metadata.schema_version),
|
||||
generation: asString(metadata.generation),
|
||||
host: asString(metadata.host),
|
||||
collector_version: asString(metadata.collector_version),
|
||||
error: asString(metadata.error),
|
||||
},
|
||||
root: asString(value.root),
|
||||
host_root: asString(value.host_root),
|
||||
source: asString(value.source),
|
||||
observed_at: asString(value.observed_at),
|
||||
error: asString(value.error),
|
||||
measurement: asString(value.measurement),
|
||||
mount: {
|
||||
container_root: asString(mount.container_root),
|
||||
mount_verified: asBool(mount.mount_verified),
|
||||
lives_on_container_root: asBool(mount.lives_on_container_root),
|
||||
read_only: asBool(mount.read_only),
|
||||
evidence: asString(mount.evidence),
|
||||
mount_point: asString(mount.mount_point),
|
||||
device: asString(mount.device),
|
||||
fs_type: asString(mount.fs_type),
|
||||
error: asString(mount.error),
|
||||
},
|
||||
capacity: {
|
||||
@@ -166,10 +213,11 @@ function inventoryProjection(value: unknown): BackupInventory {
|
||||
totals: {
|
||||
batch_count: asNumber(totals.batch_count),
|
||||
database_count: asNumber(totals.database_count),
|
||||
apparent_bytes: asNumber(totals.apparent_bytes),
|
||||
actual_bytes: asNumber(totals.actual_bytes),
|
||||
apparent_bytes: asNumberOrNull(totals.apparent_bytes),
|
||||
actual_bytes: asNumberOrNull(totals.actual_bytes),
|
||||
latest_stamp: asString(totals.latest_stamp),
|
||||
latest_actual_bytes: asNumber(totals.latest_actual_bytes),
|
||||
latest_actual_bytes: asNumberOrNull(totals.latest_actual_bytes),
|
||||
complete: asBool(totals.complete),
|
||||
},
|
||||
incomplete_count: asNumber(value.incomplete_count),
|
||||
skipped: asList(value.skipped).map((item) => {
|
||||
@@ -186,7 +234,7 @@ export async function fetchBackupInventory(signal?: AbortSignal): Promise<Backup
|
||||
signal,
|
||||
})
|
||||
if (!response.ok) {
|
||||
throw new Error(`读取备份盘点失败(HTTP ${response.status})`)
|
||||
throw new Error(`读取备份元数据失败(HTTP ${response.status})`)
|
||||
}
|
||||
const value = (await response.json().catch(() => null)) as unknown
|
||||
if (!record(value) || !record(value.data)) throw new Error('备份盘点响应无效')
|
||||
|
||||
Reference in New Issue
Block a user