From 033f702d41bbc4fb9c70ed2114e6c64275389000 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=A7=9A=E7=AB=A0=E6=B5=A9?= Date: Fri, 20 Nov 2026 00:58:18 +0800 Subject: [PATCH] =?UTF-8?q?feat(backup):=20=E5=8F=AA=E8=AF=BB=E7=9B=98?= =?UTF-8?q?=E7=82=B9=E7=9C=9F=E5=AE=9E=E6=89=B9=E6=AC=A1=E3=80=81=E5=AD=90?= =?UTF-8?q?=E5=BA=93=E8=B7=AF=E5=BE=84=E4=B8=8E=E5=AE=B9=E9=87=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 为什么:28189 验收里历史批次/子库路径/容量都没有真实接口,页面只能占位; 用户要求修实际接口而不是继续改文案,同时不得写主机或触发备份。 怎么改:新增 GET /api/v1/backup-schedule/inventory,只读盘点 statfs 实测容量、 st_blocks 实际占盘、全部批次与 MANIFEST 状态、每个子库完整主机路径。目录必须 只读挂载;用设备号区分挂载文件系统与容器根盘,同设备时不给主机容量。清单 missing/invalid、未接线、不可读分别展示。SSH 计划读回与盘点独立加载。 前端消费该接口:整盘色带、批次列表、子库路径复制、清单失败与容器根盘提示。 怎么验:Go 单测覆盖清单/占盘/符号链接/容器根盘;handler 契约;appconfig 接线校验; vitest 627 项、tsc、vite build、prettier 通过;本地页面夹具核对 8 批与路径复制, 1440/1024/768 无横向溢出。未连接真实主机、未执行备份、未改真实计划。 --- CHANGELOG.md | 22 + api/openapi.yaml | 23 + cmd/api/main.go | 26 + compose.release-sim.yaml | 6 + docs/PRODUCTION_BACKUP_RECOVERY.md | 5 +- docs/STORAGE_BACKUP_READONLY_API.md | 187 +++++++ internal/appconfig/config.go | 27 + internal/appconfig/config_test.go | 34 ++ internal/backupinventory/inventory.go | 592 +++++++++++++++++++++ internal/backupinventory/inventory_test.go | 205 +++++++ internal/httpapi/backup_inventory.go | 23 + internal/httpapi/backup_inventory_test.go | 88 +++ internal/httpapi/server.go | 19 +- web/src/BackupScheduleSection.test.tsx | 283 ++++++++-- web/src/BackupScheduleSection.tsx | 523 +++++++++++++++--- web/src/backupInventory.test.ts | 107 ++++ web/src/backupInventory.ts | 194 +++++++ web/src/storageBackup.css | 71 +++ 18 files changed, 2317 insertions(+), 118 deletions(-) create mode 100644 docs/STORAGE_BACKUP_READONLY_API.md create mode 100644 internal/backupinventory/inventory.go create mode 100644 internal/backupinventory/inventory_test.go create mode 100644 internal/httpapi/backup_inventory.go create mode 100644 internal/httpapi/backup_inventory_test.go create mode 100644 web/src/backupInventory.test.ts create mode 100644 web/src/backupInventory.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 2d70b4a..96db63f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,27 @@ # Changelog +## 开发快照 0.1.407(备份盘点:只读挂载读真实批次与容量) + +### Added + +- `GET /api/v1/backup-schedule/inventory`:只读盘点 `rds-logical` 批次、MANIFEST 状态、每个 + 子库完整主机路径、表观/实际占盘,以及只读挂载文件系统的实测容量。 +- 新包 `internal/backupinventory`:批次按目录戳倒序,`*.incomplete` 不计入;清单缺失/损坏 + 逐批标注;实际占盘按 `st_blocks×512`;容量用 `statfs`,并与容器根盘比较设备号。 +- 系统设置 → 存储与备份接入盘点:整盘色带、批次列表、子库路径复制、清单失败与未接线分开; + SSH 计划读回与文件盘点独立加载,互不掩盖失败。 +- 文档 `docs/STORAGE_BACKUP_READONLY_API.md`:28189 候选接口契约、`:ro` 最小挂载与权限要求、 + 可验证字段、现有写路径与尚未实现的后端写能力。 + +### Changed + +- 备份策略目录改为只读展示盘点到的 `host_root`;配额/预留仍无后端字段,保留占位并标未知。 +- 磁盘告警只在“挂载与容器根盘分离 + 容量实测 + 有批次占盘参考”时判定;容器根盘读数只作排障。 + +### Security + +- 盘点不执行远端文件命令、不写备份目录;只接受只读挂载,拒绝跟随符号链接批次,扫描有上限。 + ## 开发快照 0.1.406(备份主机状态不得由历史推断) ### Fixed diff --git a/api/openapi.yaml b/api/openapi.yaml index 8a0f990..021979a 100644 --- a/api/openapi.yaml +++ b/api/openapi.yaml @@ -1972,6 +1972,29 @@ } } }, + "/api/v1/backup-schedule/inventory": { + "get": { + "tags": [ + "Settings" + ], + "operationId": "getBackupScheduleInventory", + "summary": "只读盘点备份批次、子库完整路径与实际占盘、挂载文件系统实测容量", + "responses": { + "200": { + "$ref": "#/components/responses/Envelope" + }, + "400": { + "$ref": "#/components/responses/BadRequest" + }, + "500": { + "$ref": "#/components/responses/InternalError" + }, + "503": { + "$ref": "#/components/responses/ServiceUnavailable" + } + } + } + }, "/api/v1/backup-schedule/apply": { "post": { "tags": [ diff --git a/cmd/api/main.go b/cmd/api/main.go index 0c53269..70cdd02 100644 --- a/cmd/api/main.go +++ b/cmd/api/main.go @@ -8,6 +8,7 @@ import ( "net/http" "os" "os/signal" + "path" "strings" "syscall" "time" @@ -16,6 +17,7 @@ import ( "knowledge-governance/internal/appconfig" "knowledge-governance/internal/backuphost" + "knowledge-governance/internal/backupinventory" "knowledge-governance/internal/dingtalkdiscovery" "knowledge-governance/internal/httpapi" "knowledge-governance/internal/kbbinding" @@ -55,6 +57,25 @@ func (dingtalkSourceLister) ValidateDingtalkDocument(ctx context.Context, node s return dingtalkdiscovery.ValidateDocument(ctx, dingtalkdiscovery.ExecRunner{}, node) } +// 只读盘点的展示路径必须与挂载来源同一份:容器内挂载点不可给操作者复制, +// 复制出去要在主机上能直接 cd/pg_restore。来源没配时用 target + 主机根拼。 +func backupInventoryHostRoot(config appconfig.Config) string { + if config.BackupHostReadonlyHostPath != "" { + return config.BackupHostReadonlyHostPath + } + return path.Join(config.BackupHostRoot, "rds-logical") +} + +func backupInventorySource(config appconfig.Config) string { + if config.BackupHostReadonlySource != "" { + return config.BackupHostReadonlySource + } + if config.BackupHostTarget == "" { + return "" + } + return config.BackupHostTarget + ":" + backupInventoryHostRoot(config) +} + func main() { ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) defer stop() @@ -318,6 +339,11 @@ func run(ctx context.Context, getenv func(string) string) error { ScriptDir: config.BackupHostScriptDir, Root: config.BackupHostRoot, }), + BackupInventory: backupinventory.New(backupinventory.Config{ + Root: config.BackupHostReadonlyRoot, + HostRoot: backupInventoryHostRoot(config), + Source: backupInventorySource(config), + }), Auth: &httpapi.AuthConfig{Store: authStore, SessionTTL: 12 * time.Hour}, }) if err != nil { diff --git a/compose.release-sim.yaml b/compose.release-sim.yaml index f431d94..bf4728b 100644 --- a/compose.release-sim.yaml +++ b/compose.release-sim.yaml @@ -16,9 +16,15 @@ services: BACKUP_HOST_TARGET: weknora-test 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 + # 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 release-worker: environment: diff --git a/docs/PRODUCTION_BACKUP_RECOVERY.md b/docs/PRODUCTION_BACKUP_RECOVERY.md index 3f7038a..9915f4d 100644 --- a/docs/PRODUCTION_BACKUP_RECOVERY.md +++ b/docs/PRODUCTION_BACKUP_RECOVERY.md @@ -91,13 +91,16 @@ 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`)、 `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`。 - 主机状态读取只认**有 `MANIFEST.json` 的完整目录**:被中断的运行会被脚本改名 `*.incomplete`, 所以"最近一次备份"永远不会显示一份半成品。 - 依赖两个运行前提:运行镜像里有 `openssh-client`,且容器用户的 uid 在 `/etc/passwd` 有名字 diff --git a/docs/STORAGE_BACKUP_READONLY_API.md b/docs/STORAGE_BACKUP_READONLY_API.md new file mode 100644 index 0000000..f1c23a1 --- /dev/null +++ b/docs/STORAGE_BACKUP_READONLY_API.md @@ -0,0 +1,187 @@ +# 存储与备份:只读盘点接口与 28189 候选接线 + +本页的「备份记录 / 整盘占用」只读**备份执行主机**上的 `rds-logical` 目录。接口不执行 +SSH 文件命令,也不写备份目录;它只读一个**只读挂载**进来的目录,并用 `statfs` 与 +`st_blocks` 给出实测容量和实际占盘。主机 cron 计划的读回仍是另一条 SSH 通道,两者独立。 + +## 1. 接口契约 + +`GET /api/v1/backup-schedule/inventory`(读者角色可看;不写任何东西) + +响应始终是 200 + `data`,未接线/目录不可读/清单损坏都写在字段里,页面据此区分原因。 +只有请求本身失败(如代理 502)才是非 200。 + +```json +{ + "data": { + "wired": true, + "root": "/var/lib/knowledge-governance/backup-host/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": "", + "mount": { + "container_root": "/", + "mount_verified": true, + "lives_on_container_root": false, + "read_only": true, + "evidence": "挂载设备 20 与容器根盘 10 不同:容量按挂载文件系统计量" + }, + "capacity": { + "measured": true, + "total_bytes": 257698037760, + "free_bytes": 51539607552, + "available_bytes": 48318382080, + "used_bytes": 206158430208 + }, + "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 + } + ] + } + ], + "totals": { + "batch_count": 8, + "database_count": 0, + "apparent_bytes": 11141651752, + "actual_bytes": 12000000000, + "latest_stamp": "20261118T193001Z", + "latest_actual_bytes": 1500000000 + }, + "incomplete_count": 0, + "skipped": [], + "truncated": false + } +} +``` + +> 示例中的容量、字节与库数只说明字段形状,**不是现场读数**;现场值必须由接口实测。 +> 候选现场已核实的事实只有:8 批、最近 `20261118T193001Z`、含 `weknora_v090prod.dir`。 + +### 字段语义(页面可逐项核对) + +| 字段 | 含义 | 页面行为 | +| --- | --- | --- | +| `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` | 批次或文件数超扫描上限 | 明确“部分结果” | + +`apparent_bytes` 优先取 MANIFEST 的 `total_bytes`;没有/损坏清单时退回目录 `st_size` 合计。 +`actual_bytes` 永远是文件系统实际分配,不用表观字节冒充占盘。 + +## 2. 28189 候选 API 的最小接线 + +28189 是 `weknora-test` 上的候选 API(本机通过 SSH 隧道访问)。API 容器增加三项环境变量 +和一条**只读** bind mount;不新增 SSH 权限,也不把备份目录挂成可写: + +```yaml +services: + api: + environment: + BACKUP_HOST_READONLY_ROOT: /var/lib/knowledge-governance/backup-host/rds-logical + 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 +``` + +要求: + +- 挂载必须带 `: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 +``` + +期望:`findmnt` 的 SOURCE 是宿主备份盘、OPTIONS 含 `ro`;`stat` 的设备号与 `/` 不同 +(对应 `mount.mount_verified=true`);`df` 与 `capacity` 接近;`ls` 能看到 +`20261118T193001Z`。 + +字段核对:`totals.batch_count=8`、`totals.latest_stamp=20261118T193001Z`、最近批的 +`databases` 含 `weknora_v090prod` 且 `present=true`、`host_path` 以 +`/srv/kb-backups/rds-logical/20261118T193001Z/weknora_v090prod.dir` 结尾。 + +若 `wired=false` 或 `error` 提示不可读:先查挂载与读权限,不要用 SSH 的“最近一次”补历史。 + +## 3. 与主机计划读回的关系 + +- `GET /api/v1/backup-schedule/host`:SSH 读 cron/脚本/计划 + MANIFEST 的最近一次摘要。 +- `GET /api/v1/backup-schedule/inventory`:只读挂载读全部批次、子库路径、实际占盘、容量。 + +前端分别加载,互不掩盖失败:盘点不可读时计划区仍显示读回结果;SSH 连不上时历史区仍可 +展示文件事实。历史批次与子库路径以盘点为准,SSH 的“最近一次”只作历史参考。 + +## 4. 现有写路径(本次未改) + +| 路径 | 写什么 | 权限 | +| --- | --- | --- | +| `PUT /api/v1/backup-schedule` | 计划写库;`apply=true` 时 SSH 下发 cron | 管理员 | +| `POST /api/v1/backup-schedule/apply` | SSH 重写主机 cron/计划参数 | 管理员 | +| `POST /api/v1/backup-schedule/run` | 在主机执行 `logical-backup.sh`(写备份目录/RDS dump) | 管理员 | +| `BackupScheduleStore.SaveBackupSchedule` | 计划落库 | 服务内部 | +| `MarkBackupScheduleApplied` | 下发摘要回写 | 服务内部 | +| `backuphost.Apply / RunNow` | 远端脚本执行 | 服务内部 | + +本接口没有任何写备份目录、删批次、改 cron 的代码路径。 + +## 5. 还需单独确认的后端写能力 + +以下均**未实现**,需要单独评审与授权,不能在本次只读闭环里顺手打开: + +1. 配额 / 磁盘预留的持久化与执行(当前无字段;页面保留占位并标未知)。 +2. 旧批次保留/删除(按天/按月轮转)与删除前审计、可恢复窗口。 +3. 备份目录迁移/切换(涉及主机 cron 参数与历史文件位置)。 +4. 单库备份/单库恢复(现有 `run` 是整批;单库范围需先证明)。 +5. 恢复验证执行(`pg_restore` 演练、校验和、结果留档)。 +6. MANIFEST 修复/重建(当前只如实报 missing/invalid)。 +7. 远程挂载/权限变更的自动化(属部署与主机权限,必须人工批准)。 +8. 写操作的角色细分(目前写路径统一管理员;若要“备份操作员”需另立角色)。 \ No newline at end of file diff --git a/internal/appconfig/config.go b/internal/appconfig/config.go index 65e8337..91e8afb 100644 --- a/internal/appconfig/config.go +++ b/internal/appconfig/config.go @@ -68,6 +68,11 @@ type Config struct { BackupHostTarget string BackupHostScriptDir string BackupHostRoot string + // BackupHostReadonlyRoot 是容器内只读挂载的 rds-logical 目录(批次/子库/实测容量)。 + // 留空即"未接线";它与上面的 SSH 计划读回是两条独立通道。 + BackupHostReadonlyRoot string + BackupHostReadonlyHostPath string + BackupHostReadonlySource string // 版本记录(「版本记录」页):**匿名只读**远端仓库的提交与 tag。来源留空即"未接线" // (页面降级展示,接口返回可用性=false)。只允许配置里批准的 origin 与仓库, // 不接受任何调用方传入的 URL;本功能**不使用凭据**。 @@ -223,6 +228,9 @@ 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")), + 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")), VersionHistoryRepo: valueOrDefault(strings.TrimSpace(getenv("VERSION_HISTORY_REPO")), "Weknora/knowledge-governance"), VersionHistoryAllowedOrigins: splitOrigins(getenv("VERSION_HISTORY_ALLOWED_ORIGINS")), @@ -518,6 +526,25 @@ 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.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.BackupHostReadonlyRoot == "" && + (config.BackupHostReadonlyHostPath != "" || config.BackupHostReadonlySource != "") { + return Config{}, errors.New("BACKUP_HOST_READONLY_ROOT is required when host path/source is set") + } + for _, value := range []string{config.BackupHostReadonlyHostPath, config.BackupHostReadonlySource} { + if strings.ContainsAny(value, "\x00\r\n") { + return Config{}, errors.New("backup inventory display path/source contains control characters") + } + } if config.ProductionReleaseRequestsEnabled { // 目标主机凭据要么都给要么都不给:只给一半会把"未接线"伪装成"已接线"。 if (config.BackupHostSSHConfig == "") != (config.BackupHostTarget == "") { diff --git a/internal/appconfig/config_test.go b/internal/appconfig/config_test.go index 893bbe8..9eba702 100644 --- a/internal/appconfig/config_test.go +++ b/internal/appconfig/config_test.go @@ -53,6 +53,40 @@ func TestLoadUsesSafeDefaults(t *testing.T) { } } +func TestLoadValidatesBackupInventoryMount(t *testing.T) { + base := map[string]string{"DATABASE_URL": "postgres://example"} + load := func(extra map[string]string) (Config, error) { + values := map[string]string{} + for key, value := range base { + values[key] = value + } + for key, value := range extra { + values[key] = value + } + 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_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_READONLY_HOST_PATH": "/srv/kb-backups/rds-logical"}); err == nil { + t.Fatal("host path without read-only root must be rejected") + } + config, err := load(map[string]string{ + "BACKUP_HOST_READONLY_ROOT": "/var/lib/knowledge-governance/backup-host/rds-logical", + "BACKUP_HOST_READONLY_HOST_PATH": "/srv/kb-backups/rds-logical", + "BACKUP_HOST_READONLY_SOURCE": "weknora-test:/srv/kb-backups/rds-logical", + }) + if err != nil { + t.Fatalf("valid inventory mount rejected: %v", err) + } + if config.BackupHostReadonlyRoot == "" || config.BackupHostReadonlyHostPath == "" || config.BackupHostReadonlySource == "" { + t.Fatalf("inventory mount fields lost: %#v", config) + } +} + func TestLoadRequiresDatabaseURL(t *testing.T) { if _, err := Load(func(string) string { return "" }); err == nil { t.Fatal("Load() error = nil, want missing DATABASE_URL error") diff --git a/internal/backupinventory/inventory.go b/internal/backupinventory/inventory.go new file mode 100644 index 0000000..e3c0c99 --- /dev/null +++ b/internal/backupinventory/inventory.go @@ -0,0 +1,592 @@ +// Package backupinventory 只读盘点备份执行主机上的 rds-logical 备份目录。 +// +// 为什么不是再开一条 SSH 命令:盘点要列全部历史批次、子库目录和实际占盘, +// 在主机上跑 find/du/df 既扩大远端命令面,也无法证明"读的是这块盘"。这里 +// 只接受一个**只读挂载**进来的目录,平台侧没有写路径;容量用 statfs 量, +// 并比较挂载根与容器根的文件系统设备号,避免把容器根盘冒充主机磁盘。 +package backupinventory + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "io/fs" + "os" + "path" + "path/filepath" + "sort" + "strings" + "syscall" + "time" +) + +const ( + defaultMaxBatches = 100 + defaultMaxFiles = 200_000 + defaultMaxManifestBytes = 8 << 20 + + // Linux statfs 的 ST_RDONLY;syscall 包没有导出这个名字。 + statReadOnly = 0x1 +) + +type Config struct { + // Root 是容器内只读挂载点(如 /var/lib/knowledge-governance/backup-host/rds-logical)。 + // 留空即未接线;页面显示原因,不返回空表冒充"没有备份"。 + Root string + // HostRoot 是给操作者复制/在主机上执行的路径(如 /srv/kb-backups/rds-logical)。 + HostRoot string + // Source 是展示用的来源,如 weknora-test:/srv/kb-backups/rds-logical。 + Source string + // MaxBatches/MaxFiles/MaxManifestBytes 防止一个异常目录把 API 拖死。 + MaxBatches int + MaxFiles int + MaxManifestBytes int64 +} + +type statFS struct { + Total uint64 + Free uint64 + Available uint64 + ReadOnly bool +} + +type ManifestState string + +const ( + ManifestOK ManifestState = "ok" + ManifestMissing ManifestState = "missing" + ManifestInvalid ManifestState = "invalid" +) + +type MountInfo struct { + ContainerRoot string `json:"container_root"` + MountVerified bool `json:"mount_verified"` + LivesOnContainerRoot bool `json:"lives_on_container_root"` + ReadOnly bool `json:"read_only"` + Evidence string `json:"evidence"` + Error string `json:"error,omitempty"` +} + +type Capacity struct { + Measured bool `json:"measured"` + TotalBytes int64 `json:"total_bytes"` + FreeBytes int64 `json:"free_bytes"` + AvailableBytes int64 `json:"available_bytes"` + UsedBytes int64 `json:"used_bytes"` + Error string `json:"error,omitempty"` +} + +type Database struct { + Name string `json:"name"` + DirName string `json:"dir_name"` + Path string `json:"path"` + HostPath string `json:"host_path"` + Present bool `json:"present"` + Failed bool `json:"failed"` + InManifest bool `json:"in_manifest"` + ApparentBytes int64 `json:"apparent_bytes"` + ActualBytes int64 `json:"actual_bytes"` + FileCount int `json:"file_count"` +} + +type Batch struct { + Stamp string `json:"stamp"` + Path string `json:"path"` + HostPath string `json:"host_path"` + ManifestState ManifestState `json:"manifest_state"` + ManifestPath string `json:"manifest_path"` + ManifestError string `json:"manifest_error,omitempty"` + Kind string `json:"kind"` + CreatedAt string `json:"created_at"` + StartedAt string `json:"started_at"` + DurationSeconds int `json:"duration_seconds"` + ManifestBytes int64 `json:"manifest_total_bytes"` + ApparentBytes int64 `json:"apparent_bytes"` + ActualBytes int64 `json:"actual_bytes"` + FileCount int `json:"file_count"` + SizesComplete bool `json:"sizes_complete"` + SizesError string `json:"sizes_error,omitempty"` + Databases []Database `json:"databases"` +} + +type Skipped struct { + Name string `json:"name"` + Reason string `json:"reason"` +} + +type Totals struct { + BatchCount int `json:"batch_count"` + DatabaseCount int `json:"database_count"` + ApparentBytes int64 `json:"apparent_bytes"` + ActualBytes int64 `json:"actual_bytes"` + LatestStamp string `json:"latest_stamp"` + LatestActualBytes int64 `json:"latest_actual_bytes"` +} + +type Snapshot struct { + Wired bool `json:"wired"` + Root string `json:"root"` + HostRoot string `json:"host_root"` + Source string `json:"source"` + ObservedAt string `json:"observed_at"` + Error string `json:"error,omitempty"` + Mount MountInfo `json:"mount"` + Capacity Capacity `json:"capacity"` + Batches []Batch `json:"batches"` + Totals Totals `json:"totals"` + IncompleteCount int `json:"incomplete_count"` + Skipped []Skipped `json:"skipped"` + Truncated bool `json:"truncated"` +} + +type Reader struct { + config Config + now func() time.Time + statfs func(string) (statFS, error) + device func(string) (uint64, error) +} + +func New(config Config) *Reader { + if config.MaxBatches <= 0 { + config.MaxBatches = defaultMaxBatches + } + if config.MaxFiles <= 0 { + config.MaxFiles = defaultMaxFiles + } + if config.MaxManifestBytes <= 0 { + config.MaxManifestBytes = defaultMaxManifestBytes + } + return &Reader{config: config, now: time.Now, statfs: defaultStatFS, device: defaultDevice} +} + +func (r *Reader) Available() bool { + return r != nil && strings.TrimSpace(r.config.Root) != "" +} + +// Snapshot 永远返回可投影的结构:未接线、目录不可读、清单损坏都写在字段里, +// 由页面区分,不把任一种情况变成 500 或"没有备份"。 +func (r *Reader) Snapshot(ctx context.Context) Snapshot { + snapshot := Snapshot{ + Wired: r.Available(), + HostRoot: r.config.HostRoot, + Source: r.config.Source, + Batches: []Batch{}, + Skipped: []Skipped{}, + } + if r == nil || !r.Available() { + snapshot.Error = "只读盘点未接线(BACKUP_HOST_READONLY_ROOT 未设置)" + snapshot.ObservedAt = r.observedAt() + return snapshot + } + snapshot.ObservedAt = r.observedAt() + snapshot.Root = filepath.Clean(r.config.Root) + resolved, err := filepath.EvalSymlinks(snapshot.Root) + if err != nil { + snapshot.Error = "只读挂载不可读:" + err.Error() + snapshot.Capacity.Error = snapshot.Error + return snapshot + } + info, err := os.Stat(resolved) + if err != nil { + snapshot.Error = "只读挂载不可读:" + err.Error() + snapshot.Capacity.Error = snapshot.Error + return snapshot + } + if !info.IsDir() { + snapshot.Error = "只读挂载不是目录:" + resolved + snapshot.Capacity.Error = snapshot.Error + return snapshot + } + snapshot.Root = resolved + snapshot.Mount = r.mountInfo(resolved) + if !snapshot.Mount.MountVerified { + reason := snapshot.Mount.Evidence + if snapshot.Mount.Error != "" { + reason = snapshot.Mount.Error + } + snapshot.Capacity = Capacity{Error: "无法证明只读目录位于独立挂载:" + reason} + } else { + snapshot.Capacity = r.capacity(resolved) + } + + entries, err := os.ReadDir(resolved) + if err != nil { + snapshot.Error = "无法列出备份目录:" + err.Error() + return snapshot + } + dirs := make([]string, 0, len(entries)) + for _, entry := range entries { + name := entry.Name() + if strings.HasSuffix(name, ".incomplete") { + snapshot.IncompleteCount++ + continue + } + if name == "" || strings.ContainsAny(name, `/\`) { + snapshot.Skipped = append(snapshot.Skipped, Skipped{Name: name, Reason: "目录名不合法"}) + continue + } + if entry.Type()&os.ModeSymlink != 0 { + snapshot.Skipped = append(snapshot.Skipped, Skipped{Name: name, Reason: "符号链接不跟随"}) + continue + } + if !entry.IsDir() { + snapshot.Skipped = append(snapshot.Skipped, Skipped{Name: name, Reason: "不是批次目录"}) + continue + } + dirs = append(dirs, name) + } + sort.Sort(sort.Reverse(sort.StringSlice(dirs))) + if len(dirs) > r.config.MaxBatches { + dirs = dirs[:r.config.MaxBatches] + snapshot.Truncated = true + } + for _, name := range dirs { + if ctx.Err() != nil { + snapshot.Error = "读取被取消:" + ctx.Err().Error() + break + } + batch, reason, walkTruncated := r.readBatch(ctx, resolved, name) + if reason != "" { + snapshot.Skipped = append(snapshot.Skipped, Skipped{Name: name, Reason: reason}) + continue + } + if walkTruncated { + snapshot.Truncated = true + } + snapshot.Batches = append(snapshot.Batches, batch) + snapshot.Totals.ApparentBytes += batch.ApparentBytes + snapshot.Totals.ActualBytes += batch.ActualBytes + snapshot.Totals.DatabaseCount += len(batch.Databases) + } + snapshot.Totals.BatchCount = len(snapshot.Batches) + if len(snapshot.Batches) > 0 { + snapshot.Totals.LatestStamp = snapshot.Batches[0].Stamp + snapshot.Totals.LatestActualBytes = snapshot.Batches[0].ActualBytes + } + return snapshot +} + +func (r *Reader) observedAt() string { + if r == nil || r.now == nil { + return "" + } + return r.now().UTC().Format(time.RFC3339) +} + +func (r *Reader) mountInfo(root string) MountInfo { + info := MountInfo{ContainerRoot: "/"} + rootDevice, err := r.device(root) + if err != nil { + info.Error = "无法读取挂载设备号:" + err.Error() + info.Evidence = "无法证明挂载与容器根盘分离" + return info + } + containerDevice, err := r.device("/") + if err != nil { + info.Error = "无法读取容器根盘设备号:" + err.Error() + info.Evidence = "无法证明挂载与容器根盘分离" + return info + } + info.LivesOnContainerRoot = rootDevice == containerDevice + info.MountVerified = !info.LivesOnContainerRoot + if stats, statErr := r.statfs(root); statErr == nil { + info.ReadOnly = stats.ReadOnly + } + if info.MountVerified { + info.Evidence = fmt.Sprintf("挂载设备 %d 与容器根盘 %d 不同:容量按挂载文件系统计量", rootDevice, containerDevice) + } else { + info.Evidence = fmt.Sprintf("挂载设备与容器根盘相同(%d):容量不代表备份主机磁盘", rootDevice) + } + return info +} + +func (r *Reader) capacity(root string) Capacity { + stats, err := r.statfs(root) + if err != nil { + return Capacity{Error: "无法读取文件系统容量:" + err.Error()} + } + used := uint64(0) + if stats.Total > stats.Free { + used = stats.Total - stats.Free + } + return Capacity{ + Measured: true, + TotalBytes: int64(stats.Total), + FreeBytes: int64(stats.Free), + AvailableBytes: int64(stats.Available), + UsedBytes: int64(used), + } +} + +type manifest struct { + Kind string `json:"kind"` + CreatedAt string `json:"created_at"` + StartedAt string `json:"started_at"` + DurationSeconds int `json:"duration_seconds"` + Databases []string `json:"databases"` + FailedDatabases []string `json:"failed_databases"` + TotalBytes int64 `json:"total_bytes"` + Files []struct { + File string `json:"file"` + Bytes int64 `json:"bytes"` + } `json:"files"` +} + +type sizes struct { + apparent int64 + actual int64 + files int +} + +func (value *sizes) add(other sizes) { + value.apparent += other.apparent + value.actual += other.actual + value.files += other.files +} + +func (r *Reader) readBatch(ctx context.Context, root, name string) (Batch, string, bool) { + fullPath := filepath.Join(root, name) + resolved, err := filepath.EvalSymlinks(fullPath) + if err != nil { + return Batch{}, "无法解析批次目录:" + err.Error(), false + } + if !within(root, resolved) { + return Batch{}, "批次目录指向只读挂载之外", false + } + batch := Batch{ + Stamp: name, + Path: resolved, + HostPath: joinHostPath(r.config.HostRoot, name), + ManifestPath: filepath.Join(resolved, "MANIFEST.json"), + ManifestState: ManifestMissing, + Databases: []Database{}, + SizesComplete: true, + } + + var parsed manifest + state, manifestErr := readManifest(batch.ManifestPath, r.config.MaxManifestBytes, &parsed) + batch.ManifestState = state + batch.ManifestError = manifestErr + if state == ManifestOK { + batch.Kind = parsed.Kind + batch.CreatedAt = parsed.CreatedAt + batch.StartedAt = parsed.StartedAt + batch.DurationSeconds = parsed.DurationSeconds + batch.ManifestBytes = parsed.TotalBytes + } + + walked, byTop, walkErr, truncated := r.walkBatch(ctx, resolved) + batch.ApparentBytes = walked.apparent + batch.ActualBytes = walked.actual + batch.FileCount = walked.files + if walkErr != nil { + batch.SizesComplete = false + batch.SizesError = walkErr.Error() + } + if state == ManifestOK && parsed.TotalBytes > 0 { + batch.ApparentBytes = parsed.TotalBytes + } + + manifestSizes := map[string]sizes{} + if state == ManifestOK { + for _, file := range parsed.Files { + clean := path.Clean(filepath.ToSlash(file.File)) + if clean == "." || strings.HasPrefix(clean, "../") || path.IsAbs(clean) { + continue + } + top := strings.SplitN(clean, "/", 2)[0] + if !strings.HasSuffix(top, ".dir") { + continue + } + entry := manifestSizes[top] + entry.apparent += file.Bytes + entry.files++ + manifestSizes[top] = entry + } + } + + seen := map[string]bool{} + failed := map[string]bool{} + for _, db := range parsed.FailedDatabases { + failed[db] = true + } + appendDatabase := func(db string) { + if db == "" || seen[db] { + return + } + seen[db] = true + dirName := db + ".dir" + containerDir := filepath.Join(resolved, dirName) + info, statErr := os.Stat(containerDir) + present := statErr == nil && info.IsDir() + apparent := sizes{} + if entry, ok := manifestSizes[dirName]; ok { + apparent = entry + } else if walkedEntry, ok := byTop[dirName]; ok { + apparent = walkedEntry + } + batch.Databases = append(batch.Databases, Database{ + Name: db, + DirName: dirName, + Path: containerDir, + HostPath: joinHostPath(batch.HostPath, dirName), + Present: present, + Failed: failed[db], + InManifest: contains(parsed.Databases, db), + ApparentBytes: apparent.apparent, + ActualBytes: byTop[dirName].actual, + FileCount: apparent.files, + }) + } + for _, db := range parsed.Databases { + appendDatabase(db) + } + dirNames := make([]string, 0, len(byTop)) + for top := range byTop { + if strings.HasSuffix(top, ".dir") { + dirNames = append(dirNames, top) + } + } + sort.Strings(dirNames) + for _, top := range dirNames { + appendDatabase(strings.TrimSuffix(top, ".dir")) + } + return batch, "", truncated +} + +func (r *Reader) walkBatch(ctx context.Context, batchPath string) (sizes, map[string]sizes, error, bool) { + total := sizes{} + byTop := map[string]sizes{} + scanned := 0 + truncated := false + err := filepath.WalkDir(batchPath, func(current string, entry fs.DirEntry, walkErr error) error { + if ctx.Err() != nil { + return ctx.Err() + } + if walkErr != nil { + return walkErr + } + if current == batchPath { + return nil + } + if entry.Type()&os.ModeSymlink != 0 { + if entry.IsDir() { + return filepath.SkipDir + } + return nil + } + if entry.IsDir() { + return nil + } + if scanned >= r.config.MaxFiles { + truncated = true + return errStopWalk + } + info, err := entry.Info() + if err != nil { + return nil + } + relative, err := filepath.Rel(batchPath, current) + if err != nil { + return nil + } + top := strings.SplitN(filepath.ToSlash(relative), "/", 2)[0] + fileSize := sizes{apparent: info.Size(), actual: actualBytes(info), files: 1} + total.add(fileSize) + entrySizes := byTop[top] + entrySizes.add(fileSize) + byTop[top] = entrySizes + scanned++ + return nil + }) + if errors.Is(err, errStopWalk) { + err = nil + } + if err != nil { + return total, byTop, err, truncated + } + return total, byTop, nil, truncated +} + +var errStopWalk = errors.New("file scan limit reached") + +func readManifest(filename string, maxBytes int64, parsed *manifest) (ManifestState, string) { + file, err := os.Open(filename) + if err != nil { + if os.IsNotExist(err) { + return ManifestMissing, "" + } + return ManifestInvalid, err.Error() + } + defer file.Close() + raw, err := io.ReadAll(io.LimitReader(file, maxBytes+1)) + if err != nil { + return ManifestInvalid, err.Error() + } + if int64(len(raw)) > maxBytes { + return ManifestInvalid, fmt.Sprintf("清单超过 %d 字节读取上限", maxBytes) + } + if err := json.Unmarshal(raw, parsed); err != nil { + return ManifestInvalid, "清单无法解析:" + err.Error() + } + return ManifestOK, "" +} + +func within(root, target string) bool { + relative, err := filepath.Rel(root, target) + if err != nil { + return false + } + return relative != ".." && !strings.HasPrefix(relative, ".."+string(os.PathSeparator)) +} + +func joinHostPath(root, name string) string { + if strings.TrimSpace(root) == "" { + return "" + } + return path.Join(filepath.ToSlash(root), name) +} + +func contains(list []string, value string) bool { + for _, item := range list { + if item == value { + return true + } + } + return false +} + +func actualBytes(info fs.FileInfo) int64 { + if stat, ok := info.Sys().(*syscall.Stat_t); ok { + return int64(stat.Blocks) * 512 + } + return info.Size() +} + +func defaultStatFS(root string) (statFS, error) { + var stats syscall.Statfs_t + if err := syscall.Statfs(root, &stats); err != nil { + return statFS{}, err + } + blockSize := uint64(stats.Bsize) + return statFS{ + Total: stats.Blocks * blockSize, + Free: stats.Bfree * blockSize, + Available: stats.Bavail * blockSize, + ReadOnly: stats.Flags&statReadOnly != 0, + }, nil +} + +func defaultDevice(root string) (uint64, error) { + info, err := os.Stat(root) + if err != nil { + return 0, err + } + stat, ok := info.Sys().(*syscall.Stat_t) + if !ok { + return 0, fmt.Errorf("无法读取 %s 的设备号", root) + } + return uint64(stat.Dev), nil +} diff --git a/internal/backupinventory/inventory_test.go b/internal/backupinventory/inventory_test.go new file mode 100644 index 0000000..6fa3cc1 --- /dev/null +++ b/internal/backupinventory/inventory_test.go @@ -0,0 +1,205 @@ +package backupinventory + +import ( + "context" + "os" + "path/filepath" + "strings" + "syscall" + "testing" +) + +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) + } +} + +func actualOf(t *testing.T, filename string) int64 { + t.Helper() + info, err := os.Stat(filename) + if err != nil { + t.Fatal(err) + } + stat, ok := info.Sys().(*syscall.Stat_t) + if !ok { + t.Fatal("no stat") + } + return int64(stat.Blocks) * 512 +} + +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 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 + } + 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.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) + } + latest := snapshot.Batches[0] + if latest.Stamp != "20261118T193001Z" || latest.ManifestState != ManifestOK { + 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) + } + 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 !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 len(broken.Databases) != 1 || broken.Databases[0].Name != "weknora_prod" || !broken.Databases[0].Present { + t.Fatalf("清单损坏时仍应按目录列出子库: %+v", broken.Databases) + } + withoutManifest := snapshot.Batches[2] + if withoutManifest.ManifestState != ManifestMissing { + t.Fatalf("缺清单没有如实标记: %+v", withoutManifest) + } + if snapshot.Totals.BatchCount != 3 || snapshot.Totals.LatestStamp != "20261118T193001Z" { + t.Fatalf("汇总不对: %+v", snapshot.Totals) + } + if snapshot.ObservedAt == "" || snapshot.Source != "weknora-test:/srv/kb-backups/rds-logical" { + t.Fatalf("观测时间/来源不对: %+v", snapshot) + } +} + +func TestSnapshotUnconfigured(t *testing.T) { + snapshot := New(Config{}).Snapshot(context.Background()) + if snapshot.Wired || snapshot.Error == "" || len(snapshot.Batches) != 0 { + t.Fatalf("未接线必须给出原因且不伪造批次: %+v", snapshot) + } + if !strings.Contains(snapshot.Error, "未接线") { + t.Fatalf("未接线原因不清: %q", snapshot.Error) + } +} + +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) + } +} diff --git a/internal/httpapi/backup_inventory.go b/internal/httpapi/backup_inventory.go new file mode 100644 index 0000000..130cb71 --- /dev/null +++ b/internal/httpapi/backup_inventory.go @@ -0,0 +1,23 @@ +package httpapi + +import ( + "context" + "net/http" + + "knowledge-governance/internal/backupinventory" +) + +// BackupInventoryReader 只读盘点备份主机目录。它与 SSH 主机计划读回完全独立: +// 挂载没接线不应拖垮计划读回,计划读回失败也不应把历史批次说成"没有"。 +type BackupInventoryReader interface { + Available() bool + Snapshot(context.Context) backupinventory.Snapshot +} + +// handleBackupInventory 返回真实批次、子库路径与实测容量。 +// 未接线/目录不可读/清单损坏都作为 200 的字段返回,由页面区分原因; +// 只有投影本身失败才 500。 +func (config Config) handleBackupInventory(w http.ResponseWriter, r *http.Request) { + snapshot := config.BackupInventory.Snapshot(r.Context()) + writeJSON(w, http.StatusOK, map[string]any{"data": snapshot}) +} diff --git a/internal/httpapi/backup_inventory_test.go b/internal/httpapi/backup_inventory_test.go new file mode 100644 index 0000000..197555c --- /dev/null +++ b/internal/httpapi/backup_inventory_test.go @@ -0,0 +1,88 @@ +package httpapi + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + + "knowledge-governance/internal/backupinventory" +) + +type fakeBackupInventory struct { + snapshot backupinventory.Snapshot +} + +func (fake fakeBackupInventory) Available() bool { return fake.snapshot.Wired } + +func (fake fakeBackupInventory) Snapshot(context.Context) backupinventory.Snapshot { + return fake.snapshot +} + +func TestBackupInventoryProjectionPassesRealFields(t *testing.T) { + config := Config{BackupInventory: fakeBackupInventory{snapshot: backupinventory.Snapshot{ + Wired: true, + Root: "/var/lib/knowledge-governance/backup-host/rds-logical", + HostRoot: "/srv/kb-backups/rds-logical", + Source: "weknora-test:/srv/kb-backups/rds-logical", + Mount: backupinventory.MountInfo{ + MountVerified: true, + ReadOnly: true, + Evidence: "挂载设备 20 与容器根盘 10 不同", + }, + 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, + Databases: []backupinventory.Database{{ + Name: "weknora_v090prod", + HostPath: "/srv/kb-backups/rds-logical/20261118T193001Z/weknora_v090prod.dir", + Present: true, + ActualBytes: 512, + }}, + }}, + Totals: backupinventory.Totals{BatchCount: 1, LatestStamp: "20261118T193001Z"}, + }}} + recorder := httptest.NewRecorder() + config.handleBackupInventory(recorder, httptest.NewRequest(http.MethodGet, "/api/v1/backup-schedule/inventory", nil)) + if recorder.Code != http.StatusOK { + t.Fatalf("status = %d", recorder.Code) + } + var payload struct { + Data backupinventory.Snapshot `json:"data"` + } + if err := json.Unmarshal(recorder.Body.Bytes(), &payload); err != nil { + t.Fatal(err) + } + if !payload.Data.Wired || !payload.Data.Mount.MountVerified || !payload.Data.Capacity.Measured { + t.Fatalf("接线/挂载/容量字段丢失: %+v", payload.Data) + } + if len(payload.Data.Batches) != 1 || + 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 { + t.Fatalf("实际占盘字段丢失: %+v", payload.Data.Batches[0]) + } +} + +func TestBackupInventoryUnconfiguredIsNotAnError(t *testing.T) { + config := Config{BackupInventory: backupinventory.New(backupinventory.Config{})} + recorder := httptest.NewRecorder() + config.handleBackupInventory(recorder, httptest.NewRequest(http.MethodGet, "/api/v1/backup-schedule/inventory", nil)) + if recorder.Code != http.StatusOK { + t.Fatalf("未接线不应 500: %d", recorder.Code) + } + var payload struct { + Data backupinventory.Snapshot `json:"data"` + } + if err := json.Unmarshal(recorder.Body.Bytes(), &payload); err != nil { + t.Fatal(err) + } + if payload.Data.Wired || payload.Data.Error == "" || payload.Data.Batches == nil { + t.Fatalf("未接线必须给原因且批次为空数组: %+v", payload.Data) + } +} diff --git a/internal/httpapi/server.go b/internal/httpapi/server.go index 13443b6..d65ec88 100644 --- a/internal/httpapi/server.go +++ b/internal/httpapi/server.go @@ -15,6 +15,7 @@ import ( "time" "knowledge-governance/internal/backuphost" + "knowledge-governance/internal/backupinventory" "knowledge-governance/internal/dingtalkdiscovery" "knowledge-governance/internal/governance" "knowledge-governance/internal/jobs" @@ -198,10 +199,13 @@ type Config struct { // 它不是运行时开关:生产部署不设置它,那次探测仍然直连目标库逐表计数。 LibraryScopeProbe func(ctx context.Context, scope string) (bool, map[string]int64, error) // LibraryRetentionVersions/Days 是保留策略;都为 0 = 未设置(不生成清理候选)。 - LibraryRetentionVersions int - LibraryRetentionDays int - BackupSchedule BackupScheduleStore - BackupHost BackupHost + LibraryRetentionVersions int + LibraryRetentionDays int + BackupSchedule BackupScheduleStore + BackupHost BackupHost + // BackupInventory 读的是只读挂载的 rds-logical 目录(批次/子库/实测容量)。 + // 与 BackupHost 的 SSH 计划读回分离,任一侧失败都不能影响另一侧。 + BackupInventory BackupInventoryReader BackupRuns *BackupRunTracker ProductionBindings ProductionBindingStore ProductionKnowledgeBases ProductionKnowledgeBaseLister @@ -251,6 +255,10 @@ func NewHandler(config Config) (http.Handler, error) { // 未挂载主机凭据:Available()=false,页面显示"未接线"而不是 500。 config.BackupHost = backuphost.New(backuphost.Config{}) } + if config.BackupInventory == nil { + // 未挂载只读备份目录:批次/容量显示"未接线",独立于 SSH 计划读回。 + config.BackupInventory = backupinventory.New(backupinventory.Config{}) + } for _, knowledgeBaseID := range []string{config.InternalRoutingKnowledgeBaseID, config.ExternalRoutingKnowledgeBaseID} { if knowledgeBaseID != "" && !validCatalogID(knowledgeBaseID) { return nil, errors.New("routing knowledge base ID is invalid") @@ -431,6 +439,9 @@ func NewHandler(config Config) (http.Handler, error) { } config.handleBackupScheduleHost(w, r) }) + mux.HandleFunc("GET /api/v1/backup-schedule/inventory", func(w http.ResponseWriter, r *http.Request) { + config.handleBackupInventory(w, r) + }) mux.HandleFunc("PUT /api/v1/backup-schedule", func(w http.ResponseWriter, r *http.Request) { if config.BackupSchedule == nil { writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "backup schedule storage unavailable"}) diff --git a/web/src/BackupScheduleSection.test.tsx b/web/src/BackupScheduleSection.test.tsx index 93dbc76..ba5fdb4 100644 --- a/web/src/BackupScheduleSection.test.tsx +++ b/web/src/BackupScheduleSection.test.tsx @@ -6,13 +6,17 @@ import { backupDaysValid, backupMonthsValid, backupTimeValid, + copyBackupPath, formatBackupBytes, + inventoryAlerts, + inventoryUsage, runMoment, storageAlerts, storageAlertSummary, storageUsage, } from './BackupScheduleSection' import type { StorageDiskObservation } from './BackupScheduleSection' +import type { BackupInventory } from './backupInventory' import type { BackupSchedule } from './backupSchedule' const base: BackupSchedule = { @@ -67,6 +71,118 @@ const diskFixture = (overrides: Partial = {}): StorageDi ...overrides, }) +const inventoryFixture = (overrides: Partial = {}): BackupInventory => { + const baseInventory: BackupInventory = { + wired: true, + root: '/var/lib/knowledge-governance/backup-host/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: '', + mount: { + container_root: '/', + mount_verified: true, + lives_on_container_root: false, + read_only: true, + evidence: '挂载设备 20 与容器根盘 10 不同:容量按挂载文件系统计量', + }, + capacity: { + measured: true, + total_bytes: 240 * GiB, + free_bytes: 48 * GiB, + available_bytes: 45 * GiB, + used_bytes: 192 * GiB, + }, + batches: [ + { + stamp: '20261118T193001Z', + path: '/var/lib/knowledge-governance/backup-host/rds-logical/20261118T193001Z', + host_path: '/srv/kb-backups/rds-logical/20261118T193001Z', + manifest_state: 'ok', + manifest_path: '/var/lib/knowledge-governance/backup-host/rds-logical/20261118T193001Z/MANIFEST.json', + kind: 'rds-logical-backup', + created_at: '20261118T193001Z', + started_at: '20261118T192908Z', + duration_seconds: 53, + manifest_total_bytes: 1_393_646_469, + apparent_bytes: 1_393_646_469, + actual_bytes: 1_500_000_000, + file_count: 214, + sizes_complete: true, + databases: [ + { + name: 'weknora_v090prod', + dir_name: 'weknora_v090prod.dir', + path: '/var/lib/knowledge-governance/backup-host/rds-logical/20261118T193001Z/weknora_v090prod.dir', + host_path: '/srv/kb-backups/rds-logical/20261118T193001Z/weknora_v090prod.dir', + present: true, + failed: false, + in_manifest: true, + apparent_bytes: 696_320, + actual_bytes: 720_896, + file_count: 12, + }, + { + name: 'weknora_test', + dir_name: 'weknora_test.dir', + path: '/var/lib/knowledge-governance/backup-host/rds-logical/20261118T193001Z/weknora_test.dir', + host_path: '/srv/kb-backups/rds-logical/20261118T193001Z/weknora_test.dir', + present: true, + failed: true, + in_manifest: true, + apparent_bytes: 10, + actual_bytes: 4096, + file_count: 1, + }, + ], + }, + { + stamp: '20261117T193001Z', + path: '/var/lib/knowledge-governance/backup-host/rds-logical/20261117T193001Z', + host_path: '/srv/kb-backups/rds-logical/20261117T193001Z', + manifest_state: 'invalid', + manifest_path: '/var/lib/knowledge-governance/backup-host/rds-logical/20261117T193001Z/MANIFEST.json', + manifest_error: '清单无法解析:unexpected end of JSON input', + kind: '', + created_at: '', + started_at: '', + duration_seconds: 0, + manifest_total_bytes: 0, + apparent_bytes: 2048, + actual_bytes: 4096, + file_count: 1, + sizes_complete: true, + databases: [ + { + name: 'weknora_archive', + dir_name: 'weknora_archive.dir', + path: '/var/lib/knowledge-governance/backup-host/rds-logical/20261117T193001Z/weknora_archive.dir', + host_path: '/srv/kb-backups/rds-logical/20261117T193001Z/weknora_archive.dir', + present: false, + failed: false, + in_manifest: false, + apparent_bytes: 0, + actual_bytes: 0, + file_count: 0, + }, + ], + }, + ], + totals: { + batch_count: 2, + database_count: 3, + apparent_bytes: 1_393_648_517, + actual_bytes: 1_500_004_096, + latest_stamp: '20261118T193001Z', + latest_actual_bytes: 1_500_000_000, + }, + incomplete_count: 1, + skipped: [{ name: 'junk', reason: '不是批次目录' }], + truncated: false, + } + return { ...baseInventory, ...overrides } +} + const view = ( overrides: Partial = {}, extra: Record = {}, @@ -95,6 +211,10 @@ const view = ( onRunNow={vi.fn()} onReload={vi.fn()} disk={disk} + inventory={(extra.inventory as BackupInventory) ?? null} + inventoryLoading={(extra.inventoryLoading as boolean) ?? false} + inventoryError={(extra.inventoryError as string | null) ?? null} + onReloadInventory={vi.fn()} /> ) } @@ -109,7 +229,7 @@ describe('BackupScheduleView', () => { '备份执行主机 weknora-test 本机直连 RDS', '最近批次含 2 个数据库', 'weknora-test 本地备份根目录', - '具体根目录未由接口返回', + '备份目录未接线或不可读,不在页面猜测', '整批 · 2 个数据库(weknora_test、dobotai_prod)', '100.85.111.121:22', '立即备份一次(整批 2 个数据库)', @@ -141,7 +261,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)') @@ -150,34 +270,85 @@ describe('BackupScheduleView', () => { expect(html).toContain('disabled') }) - it('最近批次只展示接口真实字段;子库路径/复制/恢复验证明确未接线', () => { - const html = view({ last_run_failed_databases: ['dobotai_prod'] }) - expect(html).toContain('备份记录') - expect(html).toContain('接口只返回最近一批') - expect(html).toContain('批次戳 20261009T052909Z') - expect(html).toContain('耗时 33 秒') - expect(html).toContain('742.4 MiB') - expect(html).toContain('weknora_test') - expect(html).toContain('dobotai_prod') - expect(html).toContain('失败') - expect(html).toContain('子库目录与单库字节未由接口返回') - expect(html).toContain('复制目录(不可用)') - expect(html).toContain('恢复验证:未接线') - // 不拼造历史批次或示例子目录。 - expect(html).not.toContain('/srv/kb-backups/rds-logical') - expect(html).not.toContain('11 月 19 日 03:30') + it('只读盘点:展示全部批次、MANIFEST 状态、子库完整路径与实际占盘', () => { + const html = view({}, { inventory: inventoryFixture() }) + for (const text of [ + '备份记录', + '2 批 · 只读盘点', + '最近批次 20261118T193001Z', + '清单完整', + '清单损坏', + '批次戳 20261118T193001Z', + '实际占盘', + 'weknora_v090prod', + 'weknora_test', + '已写入', + '失败', + '目录缺失', + '/srv/kb-backups/rds-logical/20261118T193001Z', + '/srv/kb-backups/rds-logical/20261118T193001Z/weknora_v090prod.dir', + '/srv/kb-backups/rds-logical/20261117T193001Z/weknora_archive.dir', + '复制子库目录', + '清单无法解析', + '有 1 个', + 'junk(不是批次目录)', + '恢复验证:未接线', + ]) + expect(html).toContain(text) + expect(html).not.toContain('子库路径待接口返回') + expect(html).not.toContain('复制目录(不可用)') }) - it('没有批次时说明不能据此判断成功/失败', () => { - const html = view({ - last_run_stamp: '', - last_run_created_at: '', - last_run_databases: [], - last_run_total_bytes: 0, - host_reachable: false, - }) - expect(html).toContain('还没有读到任何批次') - expect(html).toContain('不能据此判断备份成功或失败') + it('没有只读盘点:不展示任何历史批次或伪造路径', () => { + const html = view() + expect(html).toContain('尚未读取只读盘点') + expect(html).not.toContain('批次戳') + expect(html).not.toContain('/srv/kb-backups/rds-logical') + }) + + it('盘点未接线:说明与 SSH 计划读回独立,未读到不等于没有备份', () => { + const html = view( + {}, + { + inventory: inventoryFixture({ + wired: false, + error: '只读盘点未接线(BACKUP_HOST_READONLY_ROOT 未设置)', + 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).not.toContain('/srv/kb-backups/rds-logical/20261118T193001Z') + }) + + it('挂载可读但没有批次时说明不能据此判断成功/失败', () => { + const html = view( + { + last_run_stamp: '', + last_run_created_at: '', + last_run_databases: [], + last_run_total_bytes: 0, + host_reachable: false, + }, + { + inventory: inventoryFixture({ + batches: [], + totals: { + batch_count: 0, + database_count: 0, + apparent_bytes: 0, + actual_bytes: 0, + latest_stamp: '', + latest_actual_bytes: 0, + }, + }), + } + ) + expect(html).toContain('挂载可读,但没有批次目录') + expect(html).toContain('不能证明备份成功或失败') }) it('非管理员只读:没有保存/下发/立即备份按钮,只给当前设置', () => { @@ -288,12 +459,12 @@ describe('BackupScheduleView', () => { }) describe('整盘占用与告警', () => { - it('没有磁盘接口时:不显示示例容量,四条告警一律无法判定', () => { + it('没有只读盘点时:不显示示例容量,四条告警只报未知原因', () => { const html = view() expect(html).toContain('未接线 · 不显示估算容量') - expect(html).toContain('后端目前没有「备份主机磁盘总量、空闲、备份目录占用」接口') + expect(html).toContain('容量来自只读挂载目录的 statfs 实测') expect(html).toContain('无法判定') - expect(html).toContain('整盘总量 / 空闲 / 备份占用:未接线') + expect(html).toContain('整盘总量 / 空闲 / 备份实际占盘:未接线') // 原型里的示例容量不能被当成产品事实带进来。 expect(html).not.toContain('总容量 240 GiB') expect(html).not.toContain('总容量 500 GiB') @@ -349,4 +520,54 @@ describe('整盘占用与告警', () => { const alerts = storageAlerts(diskFixture({ estimate_bytes: null })) expect(alerts.filter((item) => !item.known).map((item) => item.code)).toEqual(['disk_low', 'quota_low', 'both_low']) }) + + it('真实盘点:整盘色带取 statfs 容量与 st_blocks 实际占盘', () => { + const inventory = inventoryFixture() + const usage = inventoryUsage(inventory) + expect(usage).not.toBeNull() + expect(usage!.total).toBe(240 * GiB) + expect(usage!.free).toBe(45 * GiB) + expect(usage!.backup).toBe(1_500_004_096) + expect(usage!.system_other).toBe(192 * GiB - 1_500_004_096) + const alerts = inventoryAlerts(inventory) + expect(alerts.find((item) => item.code === 'disk_low')?.known).toBe(true) + expect(alerts.find((item) => item.code === 'disk_low')?.active).toBe(false) + expect(alerts.find((item) => item.code === 'quota_low')?.known).toBe(false) + const html = view({}, { inventory }) + for (const text of [ + '只读挂载实测', + '系统其他占用', + '备份实际占盘', + '可用', + '配额内/外 —(无配额字段)', + '文件系统已用', + '挂载为只读', + '挂载设备 20 与容器根盘 10 不同', + ]) + expect(html).toContain(text) + }) + + it('挂载落在容器根盘:不把容器容量当主机磁盘,磁盘告警保持未知', () => { + const inventory = inventoryFixture({ + mount: { + container_root: '/', + mount_verified: false, + lives_on_container_root: true, + read_only: true, + evidence: '挂载设备与容器根盘相同(7):容量不代表备份主机磁盘', + }, + }) + 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('容器根盘') + const html = view({}, { inventory }) + expect(html).toContain('容器根盘 · 不代表主机磁盘') + expect(html).toContain('不据此判定备份主机磁盘') + expect(html).not.toContain('备份实际占盘 1.40 GiB') + }) + + it('复制路径:空值与不可用按钮不谎报成功', async () => { + expect(await copyBackupPath('')).toBe(false) + }) }) diff --git a/web/src/BackupScheduleSection.tsx b/web/src/BackupScheduleSection.tsx index 669037f..f06567a 100644 --- a/web/src/BackupScheduleSection.tsx +++ b/web/src/BackupScheduleSection.tsx @@ -9,6 +9,8 @@ import { saveBackupSchedule, } from './backupSchedule' import type { BackupSchedule } from './backupSchedule' +import { fetchBackupInventory } from './backupInventory' +import type { BackupInventory, BackupInventoryBatch } from './backupInventory' import './storageBackup.css' export const formatBackupBytes = (bytes: number): string => { @@ -190,11 +192,122 @@ const percent = (part: number, total: number): string => (total > 0 ? `${(100 * export const storageAlertSummary = (alerts: StorageAlert[]): string => { const unknown = alerts.filter((item) => !item.known) - if (unknown.length) return '无法判定(缺主机磁盘读数)' + if (unknown.length === alerts.length) return '无法判定(缺读数与配额字段)' + if (unknown.length) return `部分无法判定(${unknown.map((item) => item.label).join('、')})` const active = alerts.filter((item) => item.active) return active.length ? active.map((item) => item.label).join('、') : '四项均正常' } +export interface InventoryUsage { + total: number + used: number + free: number + backup: number + system_other: number +} + +// 只读挂载 + 实测容量 + 文件系统与容器根盘分离,三者同时成立才画整盘图。 +// 备份实际占盘取所有批次的 st_blocks 合计,不是 MANIFEST 的表观字节。 +export function inventoryUsage(inventory: BackupInventory | null): InventoryUsage | null { + if ( + !inventory || + !inventory.wired || + !inventory.mount.mount_verified || + !inventory.capacity.measured || + inventory.capacity.total_bytes <= 0 + ) { + 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) + return { + total, + used, + free: Math.max(0, inventory.capacity.available_bytes), + backup, + system_other: Math.max(0, used - backup), + } +} + +// 配额与策略预留在后端仍是缺字段,不能因为容量读到了就假装能判定配额; +// 磁盘告警只拿"最近一批实际占盘"做参考,并注明不含预留。 +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 diskDetail = !inventory + ? '尚未读取备份目录' + : !inventory.wired + ? '只读盘点未接线' + : !inventory.mount.mount_verified + ? '目录位于容器根盘,读数不代表备份主机磁盘' + : !inventory.capacity.measured + ? inventory.capacity.error || '未读到文件系统容量' + : latestBytes <= 0 + ? '没有可参考的批次实际占盘' + : `剩余可用 ${formatGib(usage!.free)} GiB,最近一批实际占盘 ${formatGib(latestBytes)} GiB(参考值,不含策略预留)` + return [ + { + code: 'disk_low', + label: '磁盘不足', + active: diskActive, + known: diskKnown, + detail: diskDetail, + }, + { + code: 'quota_low', + label: '配额不足', + active: false, + known: false, + detail: '后端没有备份总配额字段,无法判定', + }, + { + code: 'both_low', + label: '磁盘与配额同时不足', + active: false, + known: false, + detail: '缺配额字段,无法判定', + }, + { + code: 'quota_over_physical', + label: '配额超出物理空闲', + active: false, + known: false, + detail: '缺配额字段,无法判定', + }, + ] +} + +export async function copyBackupPath(value: string, button?: HTMLButtonElement | null): Promise { + if (!value) return false + try { + await navigator.clipboard.writeText(value) + if (button) button.textContent = '已复制' + return true + } catch { + // 内网 http 页面没有 clipboard API 权限时退回选中,不谎报“已复制”。 + const area = document.createElement('textarea') + area.value = value + area.setAttribute('readonly', '') + area.style.position = 'fixed' + area.style.opacity = '0' + document.body.append(area) + area.focus() + area.select() + const copied = document.execCommand('copy') + area.remove() + if (button) button.textContent = copied ? '已复制' : '路径已选中,可复制' + return copied + } +} + +const manifestLabel = (batch: BackupInventoryBatch): string => + batch.manifest_state === 'ok' ? '清单完整' : batch.manifest_state === 'missing' ? '清单缺失' : '清单损坏' + // 备份执行主机上的整库逻辑备份(全部业务库一次 pg_dump)。 // 页面只展示接口真实给出的读数;目录、配额、预留、子库路径、历史批次与恢复 // 验证在后端契约里还没有字段,保留原型位置并写明"未接线"。 @@ -218,8 +331,12 @@ export interface BackupScheduleViewProps { onApply: () => void onRunNow: () => void onReload: () => void - // 仅测试夹具提供;生产容器不传,磁盘区显示"未接线"。 + // 仅测试夹具提供;生产容器不传,磁盘区改用真实盘点的容量。 disk?: StorageDiskObservation | null + inventory?: BackupInventory | null + inventoryLoading?: boolean + inventoryError?: string | null + onReloadInventory?: () => void } export function BackupScheduleView(props: BackupScheduleViewProps) { @@ -244,6 +361,10 @@ export function BackupScheduleView(props: BackupScheduleViewProps) { onRunNow, onReload, disk = null, + inventory = null, + inventoryLoading = false, + inventoryError = null, + onReloadInventory, } = props const days = Number(daysDraft) const months = Number(monthsDraft) @@ -283,7 +404,16 @@ export function BackupScheduleView(props: BackupScheduleViewProps) { const hasLastRun = Boolean(schedule.last_run_stamp) const runFailed = failedCount > 0 || Boolean(schedule.last_run_error) const usage = disk ? storageUsage(disk) : null - const alerts = storageAlerts(disk) + 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 inventoryDatabases = latestBatch?.databases.map((item) => item.name) ?? [] + const scopeDatabases = inventoryDatabases.length ? inventoryDatabases : schedule.last_run_databases + const scopeDatabaseCount = scopeDatabases.length + const scopeFailed = latestBatch ? latestBatch.databases.filter((item) => item.failed).length : failedCount + const hasScopeBatch = Boolean(latestBatch) || hasLastRun return (
@@ -311,22 +441,33 @@ export function BackupScheduleView(props: BackupScheduleViewProps) { {schedule.host_configured ? '平台已接主机凭据' : '平台未接主机凭据'} + + {inventoryLoading + ? '文件盘点读取中' + : inventoryReady + ? '文件盘点已接线' + : inventory?.error + ? '文件盘点不可读' + : '文件盘点未接线'} +
读取源
- {`备份执行主机 ${schedule.host_target || '(未配置)'} 本机直连 RDS`} - {databaseCount ? ` · 最近批次含 ${databaseCount} 个数据库` : ' · 数据库清单未从主机读到'} + {inventory?.source || `备份执行主机 ${schedule.host_target || '(未配置)'} 本机直连 RDS`} + {scopeDatabaseCount ? ` · 最近批次含 ${scopeDatabaseCount} 个数据库` : ' · 数据库清单未读到'}
写入方向
- {`${schedule.host_target || '(未配置)'} 本地备份根目录`} - 具体根目录未由接口返回,不在页面猜测 + {inventory?.host_root || `${schedule.host_target || '(未配置)'} 本地备份根目录`} + + {inventoryReady ? '只读挂载盘点;平台没有写路径' : '备份目录未接线或不可读,不在页面猜测'} +
执行范围
- {databaseCount - ? `整批 · ${databaseCount} 个数据库(${schedule.last_run_databases.join('、')})` + {scopeDatabaseCount + ? `整批 · ${scopeDatabaseCount} 个数据库(${scopeDatabases.join('、')})` : '整批 · 数据库清单未读到,无法列出库名'}
拨号地址
@@ -338,8 +479,8 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {

POST /api/v1/backup-schedule/run 没有单库参数,一次就是该主机全部业务库的整批 - pg_dump。用单库按钮触发会连整批一起跑,因此本页不开放单库动作;单库恢复只能用批次里该库的子目录, - 但子目录路径当前接口没有返回。 + pg_dump。用单库按钮触发会连整批一起跑,因此本页不开放单库动作;单库恢复请复制「备份记录」里该库的 + 完整子目录(来自只读盘点),不要自己拼路径。

@@ -347,19 +488,23 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {

立即备份

- - {hasLastRun ? (runFailed ? '最近一批有失败' : '最近一批成功') : '尚无批次读数'} + + {hasScopeBatch ? (scopeFailed > 0 ? '最近一批有失败' : '最近一批成功') : '尚无批次读数'}

- {hasLastRun - ? `最近一批 ${schedule.last_run_stamp}${runMoment(schedule) ? ` · ${runMoment(schedule)}` : ''} · ${databaseCount} 个数据库 · ${formatBackupBytes(schedule.last_run_total_bytes)} · ${schedule.last_run_duration_seconds} 秒` - : '还没有从主机读到任何批次。'} + {latestBatch + ? `最近一批 ${latestBatch.stamp} · ${formatBackupMoment(latestBatch.created_at)} · ${scopeDatabaseCount} 个数据库 · 表观 ${formatBackupBytes(latestBatch.apparent_bytes)} · 实际占盘 ${formatBackupBytes(latestBatch.actual_bytes)} · ${latestBatch.duration_seconds} 秒` + : hasLastRun + ? `SSH 读回最近一次 ${schedule.last_run_stamp} · ${databaseCount} 个数据库 · ${formatBackupBytes(schedule.last_run_total_bytes)}(文件盘点未接线,以下仅 SSH 结果)` + : '还没有从主机读到任何批次。'}

{schedule.running ? (

- 正在备份({formatBackupMoment(schedule.running_started_at)} 开始,整批 {databaseCount || '未知'}{' '} + 正在备份({formatBackupMoment(schedule.running_started_at)} 开始,整批 {scopeDatabaseCount || '未知'}{' '} 个数据库)。 没有真实百分比接口,这里只报在途状态,完成后自动刷新。

@@ -394,7 +539,17 @@ export function BackupScheduleView(props: BackupScheduleViewProps) { >

整盘占用与告警

- {usage ? '已读到主机读数' : '未接线'} + + {usage + ? '已读到主机读数' + : inventoryFigure + ? inventory?.mount.read_only + ? '只读挂载实测' + : '实测(挂载可写)' + : inventory?.capacity.measured + ? '容器根盘(不可作主机容量)' + : '未接线'} +
{usage && disk ? ( <> @@ -446,29 +601,102 @@ export function BackupScheduleView(props: BackupScheduleViewProps) { : ''} + ) : inventoryFigure && inventory ? ( + <> +
+
+
+
+
+
+ + + 系统其他占用 {formatGib(inventoryFigure.system_other)} GiB + + + + 备份实际占盘 {formatGib(inventoryFigure.backup)} GiB + + + + 可用 {formatGib(inventoryFigure.free)} GiB + + + + 配额内/外 —(无配额字段) + +
+

+ 备份实际占盘 {formatGib(inventoryFigure.backup)} / 整盘 {formatGib(inventoryFigure.total)} GiB( + {inventoryFigure.total > 0 + ? `${((100 * inventoryFigure.backup) / inventoryFigure.total).toFixed(2)}%` + : '—'} + )· 文件系统已用 {formatGib(inventoryFigure.used)} GiB · 可用 {formatGib(inventoryFigure.free)} GiB +

+ + {inventory.mount.evidence} · 挂载点 {inventory.root} · 采集于 {formatBackupMoment(inventory.observed_at)} + {inventory.mount.read_only ? ' · 挂载为只读' : ' · 挂载不是只读(部署需改 :ro)'} + + + ) : inventory?.capacity.measured ? ( + <> +
+ 容器根盘 · 不代表主机磁盘 +
+

+ 容器根盘实测 {formatGib(inventory.capacity.total_bytes)} GiB,可用{' '} + {formatGib(inventory.capacity.available_bytes)} GiB:仅作排障,不据此判定备份主机磁盘。 +

+ {inventory.mount.evidence} + ) : ( <>
- 未接线 · 不显示估算容量 + {inventoryLoading ? '正在读取只读挂载…' : '未接线 · 不显示估算容量'}
- {['系统其他占用', '备份已用', '配额内空闲', '配额外空闲'].map((label, index) => ( + {['系统其他占用', '备份实际占盘', '可用', '配额内/外'].map((label, index) => ( - + {label} — ))}
-

整盘总量 / 空闲 / 备份占用:未接线

+

+ 整盘总量 / 空闲 / 备份实际占盘:{inventoryError || inventory?.error || '未接线'} +

)}

- 后端目前没有「备份主机磁盘总量、空闲、备份目录占用」接口:这里保留单条整盘图的位置, - 不填示例容量、不用配额推算磁盘。以下四项告警按同一份真实读数判定。 + 容量来自只读挂载目录的 statfs 实测,并与容器根盘比较设备号;同一设备时不把容器容量当主机容量。 备份占盘按文件 + st_blocks 统计(实际分配),不是 MANIFEST 的表观字节。配额与策略预留仍无后端字段, + 四项告警中只有磁盘项能按实测判定。

{storageAlertSummary(alerts)}

    @@ -511,18 +739,22 @@ export function BackupScheduleView(props: BackupScheduleViewProps) { 备份主机上的目录
    - 目录检查接口未接线:无法证明目录可写、挂在哪块盘。 + + {inventoryReady + ? '目录来自只读挂载来源,只读展示;修改目录需部署变更,平台没有写接口。' + : '只读盘点未接线:目录不可证明,不能按设置推定。'} +
@@ -712,14 +1028,14 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
-
最近一次运行
+
SSH 最近一次结果(历史)
{schedule.last_run_stamp || '—'} {runMoment(schedule) ? ` · ${runMoment(schedule)}` : ''} {schedule.last_run_stamp ? (runFailed ? ' · 有失败/读取错误' : ' · 成功') : ''}
最近一次成功
-
未从主机读取(不能用最近一次运行代替成功;失败库/读取错误见上)
+
未从主机读取(不能用最近一次运行代替成功;历史批次以「备份记录」的只读盘点为准)
备份耗时 / 体积
{schedule.last_run_stamp @@ -738,6 +1054,9 @@ export function BackupScheduleView(props: BackupScheduleViewProps) { {schedule.host_error ?

主机探测:{schedule.host_error}

: null} {schedule.last_run_error ?

最近一次结果读取:{schedule.last_run_error}

: null} + {schedule.last_run_failed_databases.length ? ( +

SSH 结果的失败库:{schedule.last_run_failed_databases.join('、')}

+ ) : null} {schedule.host_cron_lines.length ? (

主机 cron 条目:{schedule.host_cron_lines.join(' ; ')} @@ -767,6 +1086,9 @@ export function BackupScheduleSection() { const [timeDraft, setTimeDraft] = useState('03:30') const [daysDraft, setDaysDraft] = useState('7') const [monthsDraft, setMonthsDraft] = useState('3') + const [inventory, setInventory] = useState(null) + const [inventoryLoading, setInventoryLoading] = useState(true) + const [inventoryError, setInventoryError] = useState(null) const polling = useRef(null) const adopt = useCallback((next: BackupSchedule) => { @@ -797,10 +1119,40 @@ export function BackupScheduleSection() { } }, [adopt]) + const loadInventory = useCallback(async () => { + setInventoryLoading(true) + setInventoryError(null) + try { + setInventory(await fetchBackupInventory()) + } catch (cause) { + setInventoryError(cause instanceof Error ? cause.message : '读取只读备份盘点失败') + } finally { + setInventoryLoading(false) + } + }, []) + + useEffect(() => { + void loadInventory() + }, [loadInventory]) + useEffect(() => { void load() }, [load]) + // 备份完成(running 转假)后再盘点一次,新批次才会出现在历史里; + // 运行中不反复扫目录,避免把主机 IO 当成轮询接口。 + const wasRunning = useRef(false) + useEffect(() => { + if (schedule?.running) { + wasRunning.current = true + return + } + if (wasRunning.current) { + wasRunning.current = false + void loadInventory() + } + }, [schedule?.running, loadInventory]) + // 立即备份约 30~60 秒:在途时轮询主机状态,直到 running 转假并出现新的最近一次结果。 useEffect(() => { if (!schedule?.running) { @@ -925,8 +1277,15 @@ export function BackupScheduleSection() { onSave={() => void save()} onApply={() => void apply()} onRunNow={() => void runNow()} - onReload={() => void load()} - // disk 不传:后端还没有磁盘读数接口,磁盘区显示"未接线",绝不填示例容量。 + onReload={() => { + void load() + void loadInventory() + }} + inventory={inventory} + inventoryLoading={inventoryLoading} + inventoryError={inventoryError} + onReloadInventory={() => void loadInventory()} + // disk 不传:生产只认只读挂载盘点;disk 仅测试夹具用于验证告警分支。 /> ) } diff --git a/web/src/backupInventory.test.ts b/web/src/backupInventory.test.ts new file mode 100644 index 0000000..358eb22 --- /dev/null +++ b/web/src/backupInventory.test.ts @@ -0,0 +1,107 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' + +import { fetchBackupInventory } from './backupInventory' + +const payload = { + data: { + wired: true, + root: '/var/lib/knowledge-governance/backup-host/rds-logical', + host_root: '/srv/kb-backups/rds-logical', + source: 'weknora-test:/srv/kb-backups/rds-logical', + observed_at: '2026-11-19T03:30:10Z', + mount: { + container_root: '/', + mount_verified: true, + lives_on_container_root: false, + read_only: true, + evidence: '挂载设备 20 与容器根盘 10 不同', + }, + capacity: { + measured: true, + total_bytes: 257698037760, + free_bytes: 51539607552, + available_bytes: 48318382080, + used_bytes: 206158430208, + }, + batches: [ + { + stamp: '20261118T193001Z', + path: '/var/lib/knowledge-governance/backup-host/rds-logical/20261118T193001Z', + host_path: '/srv/kb-backups/rds-logical/20261118T193001Z', + manifest_state: 'ok', + manifest_path: '/var/lib/knowledge-governance/backup-host/rds-logical/20261118T193001Z/MANIFEST.json', + kind: 'rds-logical-backup', + created_at: '20261118T193001Z', + duration_seconds: 53, + apparent_bytes: 1393646469, + actual_bytes: 1500000000, + file_count: 214, + sizes_complete: true, + databases: [ + { + name: 'weknora_v090prod', + dir_name: 'weknora_v090prod.dir', + path: '/var/lib/knowledge-governance/backup-host/rds-logical/20261118T193001Z/weknora_v090prod.dir', + host_path: '/srv/kb-backups/rds-logical/20261118T193001Z/weknora_v090prod.dir', + present: true, + failed: false, + in_manifest: true, + apparent_bytes: 696320, + actual_bytes: 720896, + file_count: 12, + }, + ], + }, + ], + totals: { + batch_count: 1, + database_count: 1, + apparent_bytes: 1393646469, + actual_bytes: 1500000000, + latest_stamp: '20261118T193001Z', + latest_actual_bytes: 1500000000, + }, + incomplete_count: 1, + skipped: [], + truncated: false, + }, +} + +afterEach(() => { + vi.unstubAllGlobals() +}) + +describe('fetchBackupInventory', () => { + it('保留真实批次、子库完整主机路径与实际占盘', async () => { + vi.stubGlobal( + 'fetch', + vi.fn(() => Promise.resolve({ ok: true, json: () => Promise.resolve(payload) })) + ) + const inventory = await fetchBackupInventory() + expect(inventory.wired).toBe(true) + expect(inventory.mount.mount_verified).toBe(true) + expect(inventory.capacity.measured).toBe(true) + expect(inventory.totals.actual_bytes).toBe(1500000000) + expect(inventory.batches[0].host_path).toBe('/srv/kb-backups/rds-logical/20261118T193001Z') + expect(inventory.batches[0].databases[0].host_path).toBe( + '/srv/kb-backups/rds-logical/20261118T193001Z/weknora_v090prod.dir' + ) + expect(inventory.batches[0].databases[0].actual_bytes).toBe(720896) + }) + + it('响应缺 wired 时整块报错,不默认成未接线', async () => { + vi.stubGlobal( + 'fetch', + vi.fn(() => Promise.resolve({ ok: true, json: () => Promise.resolve({ data: {} }) })) + ) + await expect(fetchBackupInventory()).rejects.toThrow('缺 wired') + }) + + it('HTTP 失败不返回空批次', async () => { + vi.stubGlobal( + 'fetch', + vi.fn(() => Promise.resolve({ ok: false, status: 502 })) + ) + await expect(fetchBackupInventory()).rejects.toThrow('HTTP 502') + }) +}) diff --git a/web/src/backupInventory.ts b/web/src/backupInventory.ts new file mode 100644 index 0000000..ac6bd6d --- /dev/null +++ b/web/src/backupInventory.ts @@ -0,0 +1,194 @@ +// 「存储与备份 → 备份记录」只读盘点接口。真实字段来自备份主机目录的只读挂载: +// 批次目录、每个库的完整子目录、文件系统实测容量;不是 SSH 计划读回的副产物。 +export interface BackupInventoryMount { + container_root: string + mount_verified: boolean + lives_on_container_root: boolean + read_only: boolean + evidence: string + error?: string +} + +export interface BackupInventoryCapacity { + measured: boolean + total_bytes: number + free_bytes: number + available_bytes: number + used_bytes: number + error?: string +} + +export interface BackupInventoryDatabase { + name: string + dir_name: string + path: string + host_path: string + present: boolean + failed: boolean + in_manifest: boolean + apparent_bytes: number + actual_bytes: number + file_count: number +} + +export type BackupManifestState = 'ok' | 'missing' | 'invalid' + +export interface BackupInventoryBatch { + stamp: string + path: string + host_path: string + manifest_state: BackupManifestState + manifest_path: string + manifest_error?: string + kind: string + created_at: string + started_at: string + duration_seconds: number + manifest_total_bytes: number + apparent_bytes: number + actual_bytes: number + file_count: number + sizes_complete: boolean + sizes_error?: string + databases: BackupInventoryDatabase[] +} + +export interface BackupInventorySkipped { + name: string + reason: string +} + +export interface BackupInventory { + wired: boolean + root: string + host_root: string + source: string + observed_at: string + error?: string + mount: BackupInventoryMount + capacity: BackupInventoryCapacity + batches: BackupInventoryBatch[] + totals: { + batch_count: number + database_count: number + apparent_bytes: number + actual_bytes: number + latest_stamp: string + latest_actual_bytes: number + } + incomplete_count: number + skipped: BackupInventorySkipped[] + truncated: boolean +} + +const record = (value: unknown): value is Record => + Boolean(value) && typeof value === 'object' && !Array.isArray(value) + +const asString = (value: unknown): string => (typeof value === 'string' ? value : '') +const asNumber = (value: unknown): number => (typeof value === 'number' && Number.isFinite(value) ? value : 0) +const asBool = (value: unknown): boolean => value === true +const asList = (value: unknown): unknown[] => (Array.isArray(value) ? value : []) + +const manifestState = (value: unknown): BackupManifestState => + value === 'ok' || value === 'missing' || value === 'invalid' ? value : 'invalid' + +function databaseProjection(item: unknown): BackupInventoryDatabase { + const value = record(item) ? item : {} + return { + name: asString(value.name), + dir_name: asString(value.dir_name), + path: asString(value.path), + host_path: asString(value.host_path), + 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), + } +} + +function batchProjection(item: unknown): BackupInventoryBatch { + const value = record(item) ? item : {} + return { + stamp: asString(value.stamp), + path: asString(value.path), + host_path: asString(value.host_path), + manifest_state: manifestState(value.manifest_state), + manifest_path: asString(value.manifest_path), + manifest_error: asString(value.manifest_error), + kind: asString(value.kind), + 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), + sizes_complete: asBool(value.sizes_complete), + sizes_error: asString(value.sizes_error), + databases: asList(value.databases).map(databaseProjection), + } +} + +// 形状不对就整块报错:不能让缺 wired 的响应用默认 false 冒充"未接线"。 +function inventoryProjection(value: unknown): BackupInventory { + if (!record(value) || typeof value.wired !== 'boolean') { + throw new Error('备份盘点响应无效(缺 wired)') + } + 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, + root: asString(value.root), + host_root: asString(value.host_root), + source: asString(value.source), + observed_at: asString(value.observed_at), + error: asString(value.error), + 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), + error: asString(mount.error), + }, + capacity: { + measured: asBool(capacity.measured), + total_bytes: asNumber(capacity.total_bytes), + free_bytes: asNumber(capacity.free_bytes), + available_bytes: asNumber(capacity.available_bytes), + used_bytes: asNumber(capacity.used_bytes), + error: asString(capacity.error), + }, + batches: asList(value.batches).map(batchProjection), + 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), + latest_stamp: asString(totals.latest_stamp), + latest_actual_bytes: asNumber(totals.latest_actual_bytes), + }, + incomplete_count: asNumber(value.incomplete_count), + skipped: asList(value.skipped).map((item) => { + const entry = record(item) ? item : {} + return { name: asString(entry.name), reason: asString(entry.reason) } + }), + truncated: asBool(value.truncated), + } +} + +export async function fetchBackupInventory(signal?: AbortSignal): Promise { + const response = await fetch('/api/v1/backup-schedule/inventory', { + headers: { Accept: 'application/json' }, + signal, + }) + if (!response.ok) { + throw new Error(`读取备份盘点失败(HTTP ${response.status})`) + } + const value = (await response.json().catch(() => null)) as unknown + if (!record(value) || !record(value.data)) throw new Error('备份盘点响应无效') + return inventoryProjection(value.data) +} diff --git a/web/src/storageBackup.css b/web/src/storageBackup.css index 354d3f2..4790780 100644 --- a/web/src/storageBackup.css +++ b/web/src/storageBackup.css @@ -39,6 +39,20 @@ font-size: 13px; color: var(--ink-base); } +.storage-block-heading button { + font: inherit; + font-size: 10px; + padding: 3px 9px; + border-radius: 5px; + border: 1px solid var(--border-base, #cbd5e1); + background: var(--bg-panel, #fff); + color: inherit; + cursor: pointer; +} +.storage-block-heading button:disabled { + opacity: 0.55; + cursor: default; +} .storage-chip { border-radius: 999px; padding: 2px 9px; @@ -194,6 +208,60 @@ font-size: 11px; font-weight: 600; } +.storage-manifest { + font-size: 10px; + padding: 1px 7px; + border-radius: 999px; + border: 1px solid var(--border-base, #e2e8f0); +} +.storage-manifest.ok { + color: #17695a; + border-color: #a9d5c8; + background: #effaf5; +} +.storage-manifest.missing, +.storage-manifest.invalid { + color: #a03a1e; + border-color: #f3c2b8; + background: #fff6f3; +} +.storage-path-row { + display: grid; + grid-template-columns: max-content minmax(0, 1fr) max-content; + gap: 4px 8px; + align-items: center; + margin: 5px 0; +} +.storage-path-row small { + color: var(--ink-mute, #64748b); +} +.storage-path-row code { + font-size: 10px; + padding: 3px 6px; + border-radius: 4px; + background: var(--bg-soft, #f6f8fa); + overflow-wrap: anywhere; +} +.storage-path-row button, +.storage-sublibraries button { + font: inherit; + font-size: 10px; + padding: 3px 8px; + border-radius: 5px; + border: 1px solid var(--border-base, #cbd5e1); + background: var(--bg-panel, #fff); + color: inherit; + cursor: pointer; +} +.storage-path-row button:disabled, +.storage-sublibraries button:disabled { + opacity: 0.55; + cursor: default; +} +.storage-sublibrary-path { + margin: 2px 0 0; + grid-template-columns: minmax(0, 1fr) max-content; +} .storage-alert-summary { margin: 8px 0 0; font-size: 11px; @@ -330,6 +398,9 @@ border-radius: 5px; background: var(--bg-soft, #f6f8fa); } +.storage-sublibrary-path { + grid-column: 1 / -1; +} .storage-sublibraries .ok { color: #17695a; }