feat(backup): 配额改按备份根占用并在超限时清理最旧批次 #37
@@ -1,5 +1,34 @@
|
||||
# Changelog
|
||||
|
||||
## 开发快照 0.1.423(存储与备份:配额改按备份根占用)
|
||||
|
||||
### Fixed
|
||||
|
||||
- **页面配额行读错数据源**:`归档占用` 卡片读 `/api/v1/library/storage`(`runtime/library`
|
||||
归档库,现场 1.67 MB),与 `/srv/kb-backups` 的整库逻辑备份无关;现改为「备份占用 X / 配额 50 GB」,
|
||||
只读宿主采集器上报的备份根累计占用。归档库接口仍服务归档写入门禁,不再被本页调用。
|
||||
- **备份没有按字节的执行路径**:`logical-backup.sh` 过去只有按份数/月份轮转;现在 dump 前按
|
||||
`KB_BACKUP_QUOTA_BYTES` 预检,最旧优先清理且保留最新一份,空间仍不够时零删除并取消本次备份;
|
||||
dump 后复查并保护本次新批次。只删 `rds-logical` 完整批次,`es-snapshots`/`target-kb-snapshots`/
|
||||
`logs` 与 `*.incomplete` 不动。
|
||||
- **根占用不完整不牵连批次**:采集器对根树遍历失败时 `usage.actual_bytes=null`,批次表与磁盘容量仍可用;
|
||||
旧采集器快照缺 `usage/quota` 时显式「未上报」,不用批次和冒充。
|
||||
|
||||
### Added
|
||||
|
||||
- 采集器 `collect_backup_metadata.py` 新增 `--usage-root/--quota-bytes/--config`,快照新增
|
||||
`backup_root/usage/quota_bytes/quota_error`(加性字段,schema 仍为 1),根占用与 `du -sB1` 对拍。
|
||||
- `scripts/prune_backup_batches.py`:配额清理独立工具 + self-test(最旧优先、预检保留最新、
|
||||
不足零删除、非批次日录/符号链接不动、dump 后保护新批次)。
|
||||
- API 校验 `usage.root == BACKUP_HOST_ROOT`,占用与配额不完整/非法时只降级对应字段;
|
||||
`install_backup_schedule.sh --show` 增加备份根占用/配额读数。
|
||||
|
||||
### Changed
|
||||
|
||||
- `backup_layout.sh` 把 `KB_BACKUP_QUOTA_BYTES=53687091200` 写入 `backup.env`(已有值不覆盖);
|
||||
页面 4 条容量告警的配额项统一改用备份占用/配额,磁盘项仍取文件系统实测值。
|
||||
- 契约与核验命令更新到 `docs/STORAGE_BACKUP_READONLY_API.md`、`docs/PRODUCTION_BACKUP_RECOVERY.md`。
|
||||
|
||||
## 开发快照 0.1.422(知识库绑定:不再按控制台传输形态拦截 Key)
|
||||
|
||||
### Fixed
|
||||
|
||||
+1
-1
@@ -1978,7 +1978,7 @@
|
||||
"Settings"
|
||||
],
|
||||
"operationId": "getBackupScheduleInventory",
|
||||
"summary": "读取宿主元数据快照:批次、子库完整路径、实际占盘与文件系统容量(陈旧/不完整一律未知)",
|
||||
"summary": "读取宿主元数据快照:批次、子库完整路径、备份根累计占用、配额与文件系统容量(陈旧/不完整一律未知)",
|
||||
"responses": {
|
||||
"200": {
|
||||
"$ref": "#/components/responses/Envelope"
|
||||
|
||||
@@ -349,6 +349,7 @@ func run(ctx context.Context, getenv func(string) string) error {
|
||||
BackupInventory: backupinventory.New(backupinventory.Config{
|
||||
MetadataPath: config.BackupHostMetadataPath,
|
||||
HostRoot: config.BackupHostReadonlyHostPath,
|
||||
BackupRoot: config.BackupHostRoot,
|
||||
Source: backupInventorySource(config),
|
||||
MaxAge: config.BackupHostMetadataMaxAge,
|
||||
}),
|
||||
|
||||
@@ -96,6 +96,16 @@ python3 scripts/restore_drill.py --snapshot-dir $KB_BACKUP_ROOT/target-kb-snapsh
|
||||
写操作按角色网关(`classifyRole`)限管理员——这份计划会落到数据面主机的 cron 上。
|
||||
- 主机侧:`scripts/install_backup_schedule.sh`(幂等)写 `/etc/knowledge-governance/backup-schedule.env`
|
||||
与 `/etc/cron.d/kb-logical-backup`;`logical-backup.sh` 从该文件读保留策略(显式传 `KEEP_DAILY/KEEP_MONTHS` 可覆盖)。
|
||||
- **配额(按字节,硬上限)**:`/etc/knowledge-governance/backup.env` 的 `KB_BACKUP_QUOTA_BYTES`
|
||||
约束**备份根累计占用**(默认 `53687091200` = 50 GiB,`backup_layout.sh` 写入,重跑不覆盖已有值)。
|
||||
采集器把同一份配额与根占用写进快照,页面/告警只读该值,不再看归档库。
|
||||
- dump 前预检:预留最近一份完整批次大小,从最旧开始计划删批次,**永不删最新一份**;
|
||||
空间仍不够 → **一个都不删**、非 0 退出,本次备份取消。
|
||||
- dump 后复查:保护本次新批次,允许删旧(含上一份);仍超限则保留新备份并告警退出。
|
||||
- 只删 `rds-logical/<UTC>` 完整批次(含常规 `MANIFEST.json`、非符号链接);
|
||||
`es-snapshots`/`target-kb-snapshots`/`logs` 与 `*.incomplete` 永不删。
|
||||
- 现场对账:`du -sB1 -- $KB_BACKUP_ROOT` 与页面「备份占用」应一致(≤1%);
|
||||
`bash scripts/install_backup_schedule.sh --show` 也会打印根占用/配额。
|
||||
- 凭据:容器内只读挂载 `secrets/backup-host/{ssh_config,id_ed25519,known_hosts}`(0600),
|
||||
环境变量 `BACKUP_HOST_SSH_CONFIG / BACKUP_HOST_TARGET / BACKUP_HOST_SCRIPT_DIR / BACKUP_HOST_ROOT`;
|
||||
**三项缺任一即"未接线"**,页面降级提示而不是报错。只读盘点另用宿主采集器
|
||||
|
||||
@@ -19,11 +19,15 @@
|
||||
```sh
|
||||
python3 collect_backup_metadata.py \
|
||||
--root /srv/kb-backups/rds-logical \
|
||||
--usage-root /srv/kb-backups \
|
||||
--output /var/lib/knowledge-governance/backup-metadata/metadata.json \
|
||||
--source weknora-test:/srv/kb-backups/rds-logical
|
||||
```
|
||||
|
||||
- 退出码:`0` 完整;`2` 已写快照但采集不完整/有错误;`1` 连快照都没写成。
|
||||
- 备份根与配额来自 `/etc/knowledge-governance/backup.env`(`backup_layout.sh` 生成):
|
||||
`KB_BACKUP_ROOT`(默认 `/srv/kb-backups`)与 `KB_BACKUP_QUOTA_BYTES`(默认 `53687091200` = 50 GiB)。
|
||||
`--usage-root` / `--quota-bytes` 可显式覆盖;`--config` 换配置文件路径。
|
||||
- 退出码:`0` 完整且配额可用;`2` 已写快照但批次/根占用不完整或配额非法;`1` 连快照都没写成。
|
||||
- 只读取:目录项 `lstat`、`statvfs`、`/proc/self/mountinfo`、`MANIFEST.json`;
|
||||
**不打开任何 `.dat/.gz` 数据文件**。
|
||||
- 不跟随符号链接;`*.incomplete` 只计数不进入批次;单次最多 100 批(可调)。
|
||||
@@ -47,6 +51,8 @@ python3 collect_backup_metadata.py \
|
||||
```
|
||||
|
||||
目录 `0755`、文件 `0644`,只包含路径/清单摘要/计数,不含数据库内容。
|
||||
采集器自己读 `/etc/knowledge-governance/backup.env` 拿 `KB_BACKUP_ROOT`/`KB_BACKUP_QUOTA_BYTES`,
|
||||
所以配额调整不需要改 cron;只想临时覆盖时再加 `--usage-root`/`--quota-bytes`。
|
||||
|
||||
### 快照 schema(version 1)
|
||||
|
||||
@@ -58,6 +64,10 @@ python3 collect_backup_metadata.py \
|
||||
| `collected_at` | UTC RFC3339;超过 `BACKUP_HOST_METADATA_MAX_AGE` 即陈旧 |
|
||||
| `generation` | 每次采集唯一 ID,便于核对读到的是哪一次原子快照 |
|
||||
| `root` | 宿主上的 `rds-logical` 绝对路径;API 要求与配置完全一致 |
|
||||
| `backup_root` | 宿主上的备份根(`KB_BACKUP_ROOT`);API 要求等于 `BACKUP_HOST_ROOT` |
|
||||
| `usage` | 备份根整棵树的累计占用:`root/complete/actual_bytes/apparent_bytes/file_count/dir_count/errors`;`complete=false` 时字节必须为 `null` |
|
||||
| `quota_bytes` | 备份根累计占用硬上限(字节);非法/缺失时为 `null`,原因写 `quota_error` |
|
||||
| `quota_error` | 配额不可用的原因(例如 `KB_BACKUP_QUOTA_BYTES` 不是正整数) |
|
||||
| `complete` | 全局完整;权限失败/截断/有错误时为 false |
|
||||
| `filesystem` | `mount_point/mount_source/fs_type/read_only/total/free/available` |
|
||||
| `batches[].complete` | 该批遍历完整;false 时字节必须为 null |
|
||||
@@ -87,8 +97,16 @@ python3 collect_backup_metadata.py \
|
||||
},
|
||||
"root": "/srv/kb-backups/rds-logical",
|
||||
"host_root": "/srv/kb-backups/rds-logical",
|
||||
"backup_root": "/srv/kb-backups",
|
||||
"source": "weknora-test:/srv/kb-backups/rds-logical",
|
||||
"measurement": "host_collector",
|
||||
"usage": {
|
||||
"root": "/srv/kb-backups", "complete": true,
|
||||
"actual_bytes": 24318382080, "apparent_bytes": 23000000000,
|
||||
"file_count": 900, "dir_count": 30, "errors": []
|
||||
},
|
||||
"quota_bytes": 53687091200,
|
||||
"quota_error": "",
|
||||
"mount": {
|
||||
"mount_verified": true, "read_only": false,
|
||||
"mount_point": "/srv/kb-backups", "device": "/dev/sdb1", "fs_type": "ext4",
|
||||
@@ -135,8 +153,11 @@ python3 collect_backup_metadata.py \
|
||||
| `wired=false` | `metadata.error=未接线`,批次空 | 显示未接线与安装方式,不显示空表当“没备份” |
|
||||
| 快照文件缺失/不可读 | `present=false`、`valid=false` | 显示缺失;不使用 SSH 最近一次补历史 |
|
||||
| `collected_at` 超过 max age | `fresh=false`、`valid=false`、批次空、容量未测 | 显示陈旧;容量图/占盘未知 |
|
||||
| 任一批不完整/权限失败/截断 | `valid=true`、`complete=false`;所有 `*_bytes=null` | 列出路径与清单状态;占盘/容量“未知”,不画色带 |
|
||||
| 完整且新鲜 | 批次/子库字节与容量按快照 | 色带、批次、子库路径复制可用 |
|
||||
| 任一批不完整/权限失败/截断 | `valid=true`、`complete=false`;所有批次 `*_bytes=null` | 列出路径与清单状态;批次/容量“未知”,不画色带;根占用若自身完整仍可显示 |
|
||||
| 根占用遍历失败 | `metadata.valid=true`;`usage.actual_bytes=null`、`usage.error` 给原因 | 「备份占用 —」并显示原因;批次表与磁盘剩余不受影响 |
|
||||
| 旧采集器无 `usage/quota` | 字段缺省,API 返回显式「未上报」原因 | 「备份占用 —」「配额未上报」,绝不用批次和冒充 |
|
||||
| `usage.root` 与 `BACKUP_HOST_ROOT` 不一致 | `valid=false`,整块拒绝 | 显示校验失败,不展示可疑占用 |
|
||||
| 完整且新鲜 | 批次/子库字节、根占用与配额按快照 | 色带、批次、`备份占用 X / 配额 50 GB` |
|
||||
| 批次路径/子库路径与 root 不一致 | `valid=false`,整块拒绝 | 显示校验失败,不展示可疑路径 |
|
||||
|
||||
API 的路径校验要求批次路径精确等于 `<root>/<stamp>`、子库精确等于
|
||||
@@ -187,7 +208,13 @@ curl -s http://127.0.0.1:28189/api/v1/backup-schedule/inventory | head -c 400
|
||||
|
||||
字段核对(以现场为准,示例值不写死):
|
||||
|
||||
- `metadata.valid=true`、`fresh=true`;`complete=true` 才允许看占盘与容量。
|
||||
- `metadata.valid=true`、`fresh=true`;`complete=true` 才允许看批次字节与容量。
|
||||
- `usage.complete=true` 时,`usage.actual_bytes` 必须与宿主 `du -sB1 -- /srv/kb-backups` 一致
|
||||
(误差 ≤1%);`quota_bytes` 与 `/etc/knowledge-governance/backup.env` 的 `KB_BACKUP_QUOTA_BYTES` 相同。
|
||||
- `usage.actual_bytes` **不是** `totals.actual_bytes`:后者只累加 `rds-logical` 批次,
|
||||
前者还包含 `es-snapshots`/`target-kb-snapshots`/`logs`。
|
||||
- 根占用遍历失败:`usage.complete=false`、`usage.actual_bytes=null`,同时批次仍应可用;
|
||||
**不要**用批次和代替根占用。
|
||||
- `totals.batch_count=8`;`totals.latest_stamp=20261118T193001Z`。
|
||||
- 最近批 `databases` 含 `weknora_v090prod`、`present=true`,`host_path` 指向
|
||||
`/srv/kb-backups/rds-logical/20261118T193001Z/weknora_v090prod.dir`。
|
||||
@@ -218,7 +245,7 @@ curl -s http://127.0.0.1:28189/api/v1/backup-schedule/inventory | head -c 400
|
||||
|
||||
## 6. 还需单独确认的后端写能力
|
||||
|
||||
1. 配额 / 磁盘预留的持久化与执行(当前无字段)。
|
||||
1. 配额 / 磁盘预留的持久化:配额已按部署配置(`backup.env`)执行并上报;**平台页面编辑/下发**仍未实现(需 DB 字段与写接口)。
|
||||
2. 旧批次保留/删除与删除前审计、可恢复窗口。
|
||||
3. 备份目录迁移/切换。
|
||||
4. 单库备份/单库恢复(现有 run 是整批)。
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
package backuphost
|
||||
|
||||
import (
|
||||
"os/exec"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// 配额清理工具是唯一会删历史备份的代码。它的 self-test 覆盖「最旧优先 / 预检保留最新 /
|
||||
// 空间不够零删除 / 非批次日录与符号链接不动 / dump 后保护新批次」,必须随 Go 测试一起跑。
|
||||
func TestPruneBackupBatchesSelfTest(t *testing.T) {
|
||||
python, err := exec.LookPath("python3")
|
||||
if err != nil {
|
||||
t.Skip("python3 not available")
|
||||
}
|
||||
command := exec.Command(python, "../../scripts/prune_backup_batches.py", "--self-test")
|
||||
output, err := command.CombinedOutput()
|
||||
if err != nil {
|
||||
t.Fatalf("prune self-test failed: %v\n%s", err, output)
|
||||
}
|
||||
if !strings.Contains(string(output), "self-test ok") {
|
||||
t.Fatalf("prune self-test output unexpected: %s", output)
|
||||
}
|
||||
}
|
||||
@@ -31,6 +31,9 @@ type Config struct {
|
||||
MetadataPath string
|
||||
// HostRoot 是宿主上的 rds-logical 绝对路径,用于校验快照里的 root/批次路径。
|
||||
HostRoot string
|
||||
// BackupRoot 是宿主上的备份根(KB_BACKUP_ROOT),用于校验快照里的根占用范围。
|
||||
// 它必须与 BACKUP_HOST_ROOT 同源;不同源时占用不可信,整份快照拒绝。
|
||||
BackupRoot string
|
||||
// Source 是展示来源;快照里的 source 非空时以快照为准。
|
||||
Source string
|
||||
// MaxAge 超过即视为陈旧,旧快照的批次与容量一律不使用。
|
||||
@@ -85,6 +88,19 @@ type Capacity struct {
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
// Usage 是**备份根累计占用**(配额约束的对象),不是 rds-logical 批次之和。
|
||||
// Measured=false 时所有字节为 null:部分遍历永远不能当占盘。
|
||||
type Usage struct {
|
||||
Root string `json:"root"`
|
||||
Measured bool `json:"measured"`
|
||||
Complete bool `json:"complete"`
|
||||
ActualBytes *int64 `json:"actual_bytes"`
|
||||
ApparentBytes *int64 `json:"apparent_bytes"`
|
||||
FileCount *int `json:"file_count"`
|
||||
DirCount *int `json:"dir_count"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
type Database struct {
|
||||
Name string `json:"name"`
|
||||
DirName string `json:"dir_name"`
|
||||
@@ -138,12 +154,16 @@ type Snapshot struct {
|
||||
Metadata MetadataInfo `json:"metadata"`
|
||||
Root string `json:"root"`
|
||||
HostRoot string `json:"host_root"`
|
||||
BackupRoot string `json:"backup_root"`
|
||||
Source string `json:"source"`
|
||||
ObservedAt string `json:"observed_at"`
|
||||
Error string `json:"error,omitempty"`
|
||||
Measurement string `json:"measurement"`
|
||||
Mount MountInfo `json:"mount"`
|
||||
Capacity Capacity `json:"capacity"`
|
||||
Usage Usage `json:"usage"`
|
||||
QuotaBytes *int64 `json:"quota_bytes"`
|
||||
QuotaError string `json:"quota_error,omitempty"`
|
||||
Batches []Batch `json:"batches"`
|
||||
Totals Totals `json:"totals"`
|
||||
IncompleteCount int `json:"incomplete_count"`
|
||||
@@ -181,6 +201,10 @@ type metadata struct {
|
||||
Host string `json:"host"`
|
||||
Source string `json:"source"`
|
||||
Root string `json:"root"`
|
||||
BackupRoot string `json:"backup_root"`
|
||||
Usage metadataUsage `json:"usage"`
|
||||
QuotaBytes *int64 `json:"quota_bytes"`
|
||||
QuotaError string `json:"quota_error"`
|
||||
Complete bool `json:"complete"`
|
||||
Errors []string `json:"errors"`
|
||||
Filesystem metadataFilesystem `json:"filesystem"`
|
||||
@@ -190,6 +214,16 @@ type metadata struct {
|
||||
Batches []metadataBatch `json:"batches"`
|
||||
}
|
||||
|
||||
type metadataUsage struct {
|
||||
Root string `json:"root"`
|
||||
Complete bool `json:"complete"`
|
||||
ActualBytes *int64 `json:"actual_bytes"`
|
||||
ApparentBytes *int64 `json:"apparent_bytes"`
|
||||
FileCount *int `json:"file_count"`
|
||||
DirCount *int `json:"dir_count"`
|
||||
Errors []string `json:"errors"`
|
||||
}
|
||||
|
||||
type metadataFilesystem struct {
|
||||
MountPoint string `json:"mount_point"`
|
||||
MountSource string `json:"mount_source"`
|
||||
@@ -313,6 +347,14 @@ func (r *Reader) Snapshot(ctx context.Context) Snapshot {
|
||||
return invalid(snapshot, fmt.Sprintf("元数据 root=%s 与配置 %s 不一致", root, expectedRoot))
|
||||
}
|
||||
snapshot.Root = root
|
||||
backupRoot, usage, quotaBytes, quotaError, err := projectUsageAndQuota(r.config.BackupRoot, root, file)
|
||||
if err != nil {
|
||||
return invalid(snapshot, err.Error())
|
||||
}
|
||||
snapshot.BackupRoot = backupRoot
|
||||
snapshot.Usage = usage
|
||||
snapshot.QuotaBytes = quotaBytes
|
||||
snapshot.QuotaError = quotaError
|
||||
if err := validateBatches(root, file.Batches); err != nil {
|
||||
return invalid(snapshot, err.Error())
|
||||
}
|
||||
@@ -366,6 +408,66 @@ func (r *Reader) observedAt() string {
|
||||
return r.now().UTC().Format(time.RFC3339)
|
||||
}
|
||||
|
||||
// projectUsageAndQuota 校验「备份根占用」与「配额」并把它们投影给页面。
|
||||
//
|
||||
// 三条独立边界:
|
||||
// 1. 旧采集器没有 usage/quota —— 批次照旧可用,占用与配额显式「未上报」,绝不用批次和冒充;
|
||||
// 2. 路径必须与部署配置的备份根完全一致,批次根必须在其下 —— 否则整份快照拒绝;
|
||||
// 3. 遍历不完整/配额非法 —— 只把对应字段降为未知,不牵连批次表与磁盘容量。
|
||||
func projectUsageAndQuota(configuredRoot, batchRoot string, file metadata) (string, Usage, *int64, string, error) {
|
||||
expected := path.Clean(strings.TrimSpace(configuredRoot))
|
||||
reported := strings.TrimSpace(file.Usage.Root)
|
||||
declared := strings.TrimSpace(file.BackupRoot)
|
||||
usageReported := reported != "" || declared != "" || file.Usage.Complete ||
|
||||
file.Usage.ActualBytes != nil || len(file.Usage.Errors) > 0
|
||||
if !usageReported {
|
||||
quotaError := strings.TrimSpace(file.QuotaError)
|
||||
if quotaError == "" {
|
||||
quotaError = "采集器未上报备份配额(需要升级采集器)"
|
||||
}
|
||||
return expected, Usage{Error: "采集器未上报备份根占用(需要升级采集器)"}, nil, quotaError, nil
|
||||
}
|
||||
if expected == "" || !path.IsAbs(expected) {
|
||||
return "", Usage{}, nil, "", errors.New("备份根未配置:无法校验快照里的根占用")
|
||||
}
|
||||
if reported != expected || declared != expected {
|
||||
return "", Usage{}, nil, "", fmt.Errorf("快照 backup_root=%q/usage.root=%q 与配置 %q 不一致", declared, reported, expected)
|
||||
}
|
||||
if batchRoot != expected && !strings.HasPrefix(batchRoot, expected+"/") {
|
||||
return "", Usage{}, nil, "", fmt.Errorf("批次根 %s 不在备份根 %s 下", batchRoot, expected)
|
||||
}
|
||||
usage := Usage{Root: reported, Complete: file.Usage.Complete}
|
||||
if file.Usage.Complete && file.Usage.ActualBytes != nil {
|
||||
usage.Measured = true
|
||||
usage.ActualBytes = file.Usage.ActualBytes
|
||||
usage.ApparentBytes = file.Usage.ApparentBytes
|
||||
usage.FileCount = file.Usage.FileCount
|
||||
usage.DirCount = file.Usage.DirCount
|
||||
} else {
|
||||
usage.Complete = false
|
||||
usage.ActualBytes = nil
|
||||
usage.ApparentBytes = nil
|
||||
usage.FileCount = nil
|
||||
usage.DirCount = nil
|
||||
reasons := limit(file.Usage.Errors, 3)
|
||||
if len(reasons) == 0 {
|
||||
usage.Error = "备份根占用未知:采集器未给出完整字节"
|
||||
} else {
|
||||
usage.Error = "备份根占用未知:" + strings.Join(reasons, ";")
|
||||
}
|
||||
}
|
||||
quota := file.QuotaBytes
|
||||
quotaError := strings.TrimSpace(file.QuotaError)
|
||||
if quota != nil && *quota <= 0 {
|
||||
quota = nil
|
||||
quotaError = fmt.Sprintf("备份配额必须为正整数:%d", *file.QuotaBytes)
|
||||
}
|
||||
if quota == nil && quotaError == "" {
|
||||
quotaError = "采集器未上报备份配额(需要升级采集器)"
|
||||
}
|
||||
return expected, usage, quota, quotaError, nil
|
||||
}
|
||||
|
||||
func invalid(snapshot Snapshot, reason string) Snapshot {
|
||||
snapshot.Metadata.Valid = false
|
||||
snapshot.Metadata.Complete = false
|
||||
@@ -374,6 +476,8 @@ func invalid(snapshot Snapshot, reason string) Snapshot {
|
||||
snapshot.Batches = []Batch{}
|
||||
snapshot.Capacity = Capacity{Error: reason}
|
||||
snapshot.Totals = Totals{}
|
||||
snapshot.Usage = Usage{Error: reason}
|
||||
snapshot.QuotaBytes = nil
|
||||
return snapshot
|
||||
}
|
||||
|
||||
|
||||
@@ -28,8 +28,14 @@ func validMetadata() metadata {
|
||||
Host: "weknora-test",
|
||||
Source: "weknora-test:" + hostRoot,
|
||||
Root: hostRoot,
|
||||
Complete: true,
|
||||
Errors: []string{},
|
||||
BackupRoot: "/srv/kb-backups",
|
||||
Usage: metadataUsage{
|
||||
Root: "/srv/kb-backups", Complete: true,
|
||||
ActualBytes: int64p(20000), ApparentBytes: int64p(18000), FileCount: intp(12), DirCount: intp(4),
|
||||
},
|
||||
QuotaBytes: int64p(53687091200),
|
||||
Complete: true,
|
||||
Errors: []string{},
|
||||
Filesystem: metadataFilesystem{
|
||||
MountPoint: "/srv/kb-backups",
|
||||
MountSource: "/dev/sdb1",
|
||||
@@ -108,7 +114,7 @@ func writeMetadata(t *testing.T, value metadata) string {
|
||||
}
|
||||
|
||||
func readerAt(filename string, now time.Time) *Reader {
|
||||
reader := New(Config{MetadataPath: filename, HostRoot: hostRoot, Source: "configured", MaxAge: 15 * time.Minute})
|
||||
reader := New(Config{MetadataPath: filename, HostRoot: hostRoot, BackupRoot: "/srv/kb-backups", Source: "configured", MaxAge: 15 * time.Minute})
|
||||
reader.now = func() time.Time { return now }
|
||||
return reader
|
||||
}
|
||||
@@ -156,7 +162,82 @@ func TestSnapshotReadsHostMetadataAndPaths(t *testing.T) {
|
||||
t.Fatalf("汇总不对: %+v", snapshot.Totals)
|
||||
}
|
||||
if snapshot.Source != "weknora-test:"+hostRoot || snapshot.Measurement != "host_collector" {
|
||||
t.Fatalf("来源/测量方式不对: %+v", snapshot)
|
||||
t.Fatalf("来源/测量方式不对: %+v", snapshot.Source)
|
||||
}
|
||||
if snapshot.BackupRoot != "/srv/kb-backups" || !snapshot.Usage.Measured || snapshot.Usage.ActualBytes == nil || *snapshot.Usage.ActualBytes != 20000 {
|
||||
t.Fatalf("备份根占用没有投影: %+v", snapshot.Usage)
|
||||
}
|
||||
if snapshot.QuotaBytes == nil || *snapshot.QuotaBytes != 53687091200 {
|
||||
t.Fatalf("配额没有投影: %v", snapshot.QuotaBytes)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSnapshotLegacyMetadataKeepsBatchesButOccupancyUnknown(t *testing.T) {
|
||||
value := validMetadata()
|
||||
value.BackupRoot = ""
|
||||
value.Usage = metadataUsage{}
|
||||
value.QuotaBytes = nil
|
||||
value.QuotaError = ""
|
||||
filename := writeMetadata(t, value)
|
||||
snapshot := readerAt(filename, time.Date(2026, 11, 20, 1, 5, 0, 0, time.UTC)).Snapshot(context.Background())
|
||||
if !snapshot.Metadata.Valid || !snapshot.Metadata.Complete {
|
||||
t.Fatalf("旧快照仍应可用: %+v", snapshot.Metadata)
|
||||
}
|
||||
if len(snapshot.Batches) != 3 || snapshot.Totals.ActualBytes == nil {
|
||||
t.Fatalf("旧快照的批次不能丢: %+v", snapshot.Batches)
|
||||
}
|
||||
if snapshot.Usage.Measured || snapshot.Usage.ActualBytes != nil || snapshot.Usage.Error == "" {
|
||||
t.Fatalf("缺少 usage 必须显式未上报: %+v", snapshot.Usage)
|
||||
}
|
||||
if snapshot.QuotaBytes != nil || snapshot.QuotaError == "" {
|
||||
t.Fatalf("缺少配额必须显式未上报: %v/%q", snapshot.QuotaBytes, snapshot.QuotaError)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSnapshotRejectsUsageRootMismatch(t *testing.T) {
|
||||
value := validMetadata()
|
||||
value.Usage.Root = "/data/kb-backups"
|
||||
filename := writeMetadata(t, value)
|
||||
snapshot := readerAt(filename, time.Date(2026, 11, 20, 1, 5, 0, 0, time.UTC)).Snapshot(context.Background())
|
||||
if snapshot.Metadata.Valid || len(snapshot.Batches) != 0 || snapshot.Usage.Measured {
|
||||
t.Fatalf("占用根与配置不一致必须整块拒绝: %+v", snapshot)
|
||||
}
|
||||
if !strings.Contains(snapshot.Error, "不一致") {
|
||||
t.Fatalf("不一致原因不清: %q", snapshot.Error)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSnapshotIncompleteUsageDoesNotBlankBatches(t *testing.T) {
|
||||
value := validMetadata()
|
||||
value.Usage.Complete = false
|
||||
value.Usage.ActualBytes = int64p(123) // 部分计数:必须被丢弃
|
||||
value.Usage.Errors = []string{"遍历失败:PermissionError: Permission denied"}
|
||||
filename := writeMetadata(t, value)
|
||||
snapshot := readerAt(filename, time.Date(2026, 11, 20, 1, 5, 0, 0, time.UTC)).Snapshot(context.Background())
|
||||
if !snapshot.Metadata.Valid || !snapshot.Metadata.Complete {
|
||||
t.Fatalf("根占用不完整不能牵连整份快照: %+v", snapshot.Metadata)
|
||||
}
|
||||
if len(snapshot.Batches) != 3 || snapshot.Totals.ActualBytes == nil || !snapshot.Capacity.Measured {
|
||||
t.Fatalf("批次与磁盘容量必须保留: %+v", snapshot)
|
||||
}
|
||||
if snapshot.Usage.Measured || snapshot.Usage.ActualBytes != nil || !strings.Contains(snapshot.Usage.Error, "Permission") {
|
||||
t.Fatalf("占用必须为 null 并带原因: %+v", snapshot.Usage)
|
||||
}
|
||||
if snapshot.QuotaBytes == nil || *snapshot.QuotaBytes != 53687091200 {
|
||||
t.Fatalf("配额是配置事实,应保留: %v", snapshot.QuotaBytes)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSnapshotRejectsInvalidQuota(t *testing.T) {
|
||||
value := validMetadata()
|
||||
value.QuotaBytes = int64p(0)
|
||||
filename := writeMetadata(t, value)
|
||||
snapshot := readerAt(filename, time.Date(2026, 11, 20, 1, 5, 0, 0, time.UTC)).Snapshot(context.Background())
|
||||
if snapshot.QuotaBytes != nil || !strings.Contains(snapshot.QuotaError, "正整数") {
|
||||
t.Fatalf("非法配额必须降为未知: %v/%q", snapshot.QuotaBytes, snapshot.QuotaError)
|
||||
}
|
||||
if !snapshot.Metadata.Valid {
|
||||
t.Fatalf("配额非法不应否掉批次: %+v", snapshot.Metadata)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -24,11 +24,16 @@ func TestBackupInventoryProjectionPassesRealFields(t *testing.T) {
|
||||
actual := int64(1024)
|
||||
databaseActual := int64(512)
|
||||
config := Config{BackupInventory: fakeBackupInventory{snapshot: backupinventory.Snapshot{
|
||||
Wired: true,
|
||||
Root: "/srv/kb-backups/rds-logical",
|
||||
HostRoot: "/srv/kb-backups/rds-logical",
|
||||
Source: "weknora-test:/srv/kb-backups/rds-logical",
|
||||
Metadata: backupinventory.MetadataInfo{Configured: true, Present: true, Valid: true, Fresh: true, Complete: true},
|
||||
Wired: true,
|
||||
Root: "/srv/kb-backups/rds-logical",
|
||||
HostRoot: "/srv/kb-backups/rds-logical",
|
||||
Source: "weknora-test:/srv/kb-backups/rds-logical",
|
||||
Metadata: backupinventory.MetadataInfo{Configured: true, Present: true, Valid: true, Fresh: true, Complete: true},
|
||||
BackupRoot: "/srv/kb-backups",
|
||||
Usage: backupinventory.Usage{
|
||||
Root: "/srv/kb-backups", Measured: true, Complete: true, ActualBytes: &actual,
|
||||
},
|
||||
QuotaBytes: func() *int64 { value := int64(53687091200); return &value }(),
|
||||
Mount: backupinventory.MountInfo{
|
||||
MountVerified: true,
|
||||
ReadOnly: true,
|
||||
@@ -70,6 +75,13 @@ func TestBackupInventoryProjectionPassesRealFields(t *testing.T) {
|
||||
if payload.Data.Batches[0].ActualBytes == nil || *payload.Data.Batches[0].ActualBytes != 1024 {
|
||||
t.Fatalf("实际占盘字段丢失: %+v", payload.Data.Batches[0])
|
||||
}
|
||||
if payload.Data.BackupRoot != "/srv/kb-backups" || !payload.Data.Usage.Measured ||
|
||||
payload.Data.Usage.ActualBytes == nil || *payload.Data.Usage.ActualBytes != 1024 {
|
||||
t.Fatalf("备份根占用字段丢失: %+v", payload.Data.Usage)
|
||||
}
|
||||
if payload.Data.QuotaBytes == nil || *payload.Data.QuotaBytes != 53687091200 {
|
||||
t.Fatalf("配额字段丢失: %v", payload.Data.QuotaBytes)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBackupInventoryUnconfiguredIsNotAnError(t *testing.T) {
|
||||
|
||||
@@ -22,10 +22,22 @@ set -euo pipefail
|
||||
KB_BACKUP_ROOT="${KB_BACKUP_ROOT:-/srv/kb-backups}"
|
||||
CONFIG_FILE="${CONFIG_FILE:-/etc/knowledge-governance/backup.env}"
|
||||
SUBDIRS=(target-kb-snapshots rds-logical es-snapshots logs)
|
||||
# 配额与备份根写在同一份契约里:页面/采集器/备份脚本读的是同一个值。
|
||||
# 重跑本脚本时沿用已有配额,避免把运维显式调过的值重置回默认。
|
||||
QUOTA_BYTES="${KB_BACKUP_QUOTA_BYTES:-}"
|
||||
if [ -z "$QUOTA_BYTES" ] && [ -f "$CONFIG_FILE" ]; then
|
||||
QUOTA_BYTES="$(sed -n 's/^[[:space:]]*KB_BACKUP_QUOTA_BYTES=//p' "$CONFIG_FILE" | tail -1 | tr -d "\"' \r")"
|
||||
fi
|
||||
QUOTA_BYTES="${QUOTA_BYTES:-53687091200}"
|
||||
case "$QUOTA_BYTES" in
|
||||
''|*[!0-9]*) echo "KB_BACKUP_QUOTA_BYTES 必须是正整数,收到 '$QUOTA_BYTES'" >&2; exit 1 ;;
|
||||
esac
|
||||
[ "$QUOTA_BYTES" -gt 0 ] || { echo "KB_BACKUP_QUOTA_BYTES 必须大于 0" >&2; exit 1; }
|
||||
PRINT_ONLY=0
|
||||
[ "${1:-}" = "--print" ] && PRINT_ONLY=1
|
||||
|
||||
echo "备份根目录: $KB_BACKUP_ROOT"
|
||||
echo "备份配额 : $QUOTA_BYTES 字节"
|
||||
echo "配置文件 : $CONFIG_FILE"
|
||||
echo "子目录 :"
|
||||
total_bytes=0
|
||||
@@ -52,6 +64,8 @@ mkdir -p "$(dirname "$CONFIG_FILE")"
|
||||
cat >"$CONFIG_FILE" <<EOF
|
||||
# 由 scripts/backup_layout.sh 生成:备份目录契约(换主机时只改这里)
|
||||
KB_BACKUP_ROOT=$KB_BACKUP_ROOT
|
||||
# 备份根累计占用硬上限(字节):采集器上报、logical-backup.sh 执行同一条线。
|
||||
KB_BACKUP_QUOTA_BYTES=$QUOTA_BYTES
|
||||
EOF
|
||||
echo "已写入 $CONFIG_FILE"
|
||||
echo
|
||||
|
||||
@@ -37,12 +37,71 @@ COLLECTOR_VERSION = "backup-metadata/1"
|
||||
MAX_MANIFEST_BYTES = 8 << 20
|
||||
MAX_ERRORS = 50
|
||||
STAMP_NAME = re.compile(r"^[A-Za-z0-9._-]+$")
|
||||
# 备份根与配额是**同一份部署契约**:backup_layout.sh 写、采集器读、备份脚本执行。
|
||||
# 采集器不自己发明 50 GB,缺配置时用同一默认值,页面上报的配额因此就是脚本执行的值。
|
||||
DEFAULT_BACKUP_ROOT = "/srv/kb-backups"
|
||||
DEFAULT_QUOTA_BYTES = 53687091200 # 50 GiB
|
||||
LAYOUT_CONFIG = "/etc/knowledge-governance/backup.env"
|
||||
|
||||
|
||||
class CollectError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def read_layout(path: str) -> dict[str, str]:
|
||||
"""读 backup.env 的 KEY=VALUE(只取本脚本认识的键)。
|
||||
|
||||
为什么不用 sh source:采集器是 Python,且这里只需要两个标量;整文件执行会把无关的
|
||||
主机配置带进进程。文件不存在返回空(本地/未接线按默认值),显式给了路径却读不到则报错。
|
||||
"""
|
||||
try:
|
||||
with open(path, "r", encoding="utf-8") as handle:
|
||||
lines = handle.readlines()
|
||||
except FileNotFoundError:
|
||||
return {}
|
||||
except OSError as error:
|
||||
raise CollectError(f"备份配置不可读:{_error_text(error)}") from error
|
||||
values: dict[str, str] = {}
|
||||
for line in lines:
|
||||
stripped = line.strip()
|
||||
if not stripped or stripped.startswith("#") or "=" not in stripped:
|
||||
continue
|
||||
key, _, value = stripped.partition("=")
|
||||
key = key.strip()
|
||||
if key in ("KB_BACKUP_ROOT", "KB_BACKUP_QUOTA_BYTES"):
|
||||
values[key] = value.strip().strip('"').strip("'")
|
||||
return values
|
||||
|
||||
|
||||
def resolve_backup_settings(
|
||||
batch_root: str,
|
||||
usage_root: str | None,
|
||||
quota: int | None,
|
||||
config_path: str,
|
||||
) -> tuple[str, int | None, str]:
|
||||
"""解析备份根与配额:显式参数 > backup.env > 默认值。
|
||||
|
||||
配额非法时返回 quota=None + 原因(不是猜一个值);配额/路径错误都不阻止批次盘点,
|
||||
由 API 把「占用/配额未知」和「批次可用」分开呈现。
|
||||
"""
|
||||
batch_root = os.path.abspath(batch_root)
|
||||
layout = read_layout(config_path)
|
||||
raw_root = usage_root or layout.get("KB_BACKUP_ROOT") or DEFAULT_BACKUP_ROOT
|
||||
if not os.path.isabs(raw_root) or os.path.normpath(raw_root) != raw_root:
|
||||
raise CollectError(f"备份根不是规范绝对路径:{raw_root}")
|
||||
backup_root = raw_root
|
||||
if batch_root != backup_root and not batch_root.startswith(backup_root.rstrip("/") + "/"):
|
||||
raise CollectError(f"批次根 {batch_root} 不在备份根 {backup_root} 下")
|
||||
quota_text = str(quota) if quota is not None else layout.get("KB_BACKUP_QUOTA_BYTES", str(DEFAULT_QUOTA_BYTES))
|
||||
try:
|
||||
quota_value = int(quota_text)
|
||||
except (TypeError, ValueError):
|
||||
return backup_root, None, f"备份配额不是整数:{quota_text!r}"
|
||||
if quota_value <= 0:
|
||||
return backup_root, None, f"备份配额必须为正整数:{quota_value}"
|
||||
return backup_root, quota_value, ""
|
||||
|
||||
|
||||
def _error_text(error: BaseException) -> str:
|
||||
if isinstance(error, OSError) and error.filename:
|
||||
return f"{type(error).__name__}: {error.strerror or error} ({error.filename})"
|
||||
@@ -212,6 +271,28 @@ def measure_tree(path: str, scan: Callable[[str], Iterable[Any]] = os.scandir, m
|
||||
}
|
||||
|
||||
|
||||
def project_usage(root: str, tree: dict[str, Any]) -> dict[str, Any]:
|
||||
"""把根树测量投影成「可展示的占用」:不完整时一律不给字节。
|
||||
|
||||
与批次同样的纪律(0.1.408/0.1.410):部分计数永远不能当占盘;
|
||||
但这里的 error 只属于 usage,不会被塞进 snapshot.errors 去污染批次完整性。
|
||||
"""
|
||||
complete = bool(tree["complete"])
|
||||
errors = list(tree["errors"])[:MAX_ERRORS]
|
||||
if not complete and not errors:
|
||||
errors = ["备份根遍历不完整"]
|
||||
return {
|
||||
"root": root,
|
||||
"complete": complete,
|
||||
"actual_bytes": tree["actual_bytes"] if complete else None,
|
||||
"apparent_bytes": tree["apparent_bytes"] if complete else None,
|
||||
"file_count": tree["file_count"] if complete else None,
|
||||
"dir_count": tree["dir_count"] if complete else None,
|
||||
"errors": errors,
|
||||
"error": "" if complete else "备份根占用未知:" + ";".join(errors[:3]),
|
||||
}
|
||||
|
||||
|
||||
def collect(
|
||||
root: str,
|
||||
source: str = "",
|
||||
@@ -219,8 +300,12 @@ def collect(
|
||||
max_batches: int = 100,
|
||||
scan: Callable[[str], Iterable[Any]] = os.scandir,
|
||||
now: dt.datetime | None = None,
|
||||
backup_root: str = "",
|
||||
quota_bytes: int | None = None,
|
||||
quota_error: str = "",
|
||||
) -> dict[str, Any]:
|
||||
root = os.path.abspath(root)
|
||||
backup_root = os.path.abspath(backup_root or root)
|
||||
collected_at = (now or dt.datetime.now(dt.timezone.utc)).astimezone(dt.timezone.utc)
|
||||
snapshot: dict[str, Any] = {
|
||||
"schema_version": SCHEMA_VERSION,
|
||||
@@ -230,6 +315,10 @@ def collect(
|
||||
"host": host or socket.gethostname(),
|
||||
"source": source,
|
||||
"root": root,
|
||||
"backup_root": backup_root,
|
||||
"usage": {},
|
||||
"quota_bytes": quota_bytes,
|
||||
"quota_error": quota_error,
|
||||
"complete": True,
|
||||
"errors": [],
|
||||
"filesystem": {},
|
||||
@@ -239,6 +328,9 @@ def collect(
|
||||
"batches": [],
|
||||
}
|
||||
errors: list[str] = snapshot["errors"]
|
||||
# 根占用与批次完整性**分开**:某个保护目录读不到时,占用可以说「未知」,
|
||||
# 但批次表/磁盘容量仍然有效;把两者绑在一起会把「占用未知」扩大成「全部未知」。
|
||||
snapshot["usage"] = project_usage(backup_root, measure_tree(backup_root, scan))
|
||||
try:
|
||||
if not os.path.isdir(root):
|
||||
raise CollectError(f"备份根不是目录:{root}")
|
||||
@@ -529,6 +621,61 @@ def _self_test() -> None:
|
||||
assert ignored["incomplete_count"] == 1
|
||||
assert [item["stamp"] for item in ignored["batches"]] == [stamp]
|
||||
|
||||
# 根占用:测整棵备份根(不只是 rds-logical),与 du -sB1 对拍。
|
||||
kb_root = os.path.join(base, "kb-backups")
|
||||
kb_batch_root = os.path.join(kb_root, "rds-logical")
|
||||
kb_batch = os.path.join(kb_batch_root, "20261119T193001Z")
|
||||
os.makedirs(os.path.join(kb_batch, "weknora_kb.dir"))
|
||||
with open(os.path.join(kb_batch, "weknora_kb.dir", "toc.dat"), "wb") as handle:
|
||||
handle.write(b"k" * 1000)
|
||||
with open(os.path.join(kb_batch, "MANIFEST.json"), "w", encoding="utf-8") as handle:
|
||||
json.dump({"databases": ["weknora_kb"]}, handle)
|
||||
es_dir = os.path.join(kb_root, "es-snapshots")
|
||||
os.makedirs(es_dir)
|
||||
with open(os.path.join(es_dir, "index-0"), "wb") as handle:
|
||||
handle.write(b"e" * 2000)
|
||||
rooted = collect(kb_batch_root, backup_root=kb_root, quota_bytes=DEFAULT_QUOTA_BYTES, now=fixed)
|
||||
assert rooted["complete"] is True, rooted
|
||||
assert rooted["usage"]["complete"] is True, rooted["usage"]
|
||||
assert rooted["usage"]["root"] == kb_root
|
||||
assert rooted["quota_bytes"] == DEFAULT_QUOTA_BYTES
|
||||
assert rooted["usage"]["actual_bytes"] >= 3000
|
||||
if shutil.which("du"):
|
||||
assert rooted["usage"]["actual_bytes"] == du_bytes(kb_root), rooted["usage"]
|
||||
assert rooted["usage"]["actual_bytes"] > rooted["batches"][0]["actual_bytes"]
|
||||
|
||||
# 根占用遍历失败:只让占用未知,批次与整体 complete 不受影响。
|
||||
def denied_root_scan(target: str):
|
||||
if target == kb_root:
|
||||
raise PermissionError(errno.EACCES, "Permission denied", target)
|
||||
return os.scandir(target)
|
||||
|
||||
partial = collect(kb_batch_root, backup_root=kb_root, scan=denied_root_scan, now=fixed)
|
||||
assert partial["usage"]["complete"] is False
|
||||
assert partial["usage"]["actual_bytes"] is None
|
||||
assert "Permission denied" in partial["usage"]["error"]
|
||||
assert partial["complete"] is True, partial
|
||||
assert len(partial["batches"]) == 1
|
||||
|
||||
# 配置解析:备份根/配额来自 backup.env;非法配额给原因而不是默认放行。
|
||||
config_path = os.path.join(base, "backup.env")
|
||||
with open(config_path, "w", encoding="utf-8") as handle:
|
||||
handle.write(f"KB_BACKUP_ROOT={kb_root}\nKB_BACKUP_QUOTA_BYTES=12345\n")
|
||||
resolved_root, resolved_quota, resolved_error = resolve_backup_settings(
|
||||
kb_batch_root, None, None, config_path
|
||||
)
|
||||
assert resolved_root == kb_root and resolved_quota == 12345 and resolved_error == ""
|
||||
with open(config_path, "w", encoding="utf-8") as handle:
|
||||
handle.write(f"KB_BACKUP_ROOT={kb_root}\nKB_BACKUP_QUOTA_BYTES=50GB\n")
|
||||
_, bad_quota, bad_error = resolve_backup_settings(kb_batch_root, None, None, config_path)
|
||||
assert bad_quota is None and "不是整数" in bad_error
|
||||
try:
|
||||
resolve_backup_settings(kb_batch_root, os.path.join(base, "outside"), None, config_path)
|
||||
except CollectError:
|
||||
pass
|
||||
else:
|
||||
raise AssertionError("批次根不在备份根下必须拒绝")
|
||||
|
||||
output = os.path.join(base, "out", "metadata.json")
|
||||
write_snapshot(output, ignored)
|
||||
with open(output, encoding="utf-8") as handle:
|
||||
@@ -548,6 +695,9 @@ def main(argv: list[str] | None = None) -> int:
|
||||
parser.add_argument("--source", default="", help="展示来源,如 weknora-test:/srv/...")
|
||||
parser.add_argument("--host", default="", help="采集主机名(默认当前主机)")
|
||||
parser.add_argument("--max-batches", type=int, default=100)
|
||||
parser.add_argument("--usage-root", default="", help="备份根(默认读 backup.env 的 KB_BACKUP_ROOT)")
|
||||
parser.add_argument("--quota-bytes", type=int, default=None, help="备份配额(默认读 backup.env)")
|
||||
parser.add_argument("--config", default=LAYOUT_CONFIG, help="部署配置 backup.env")
|
||||
parser.add_argument("--self-test", action="store_true")
|
||||
args = parser.parse_args(argv)
|
||||
if args.self_test:
|
||||
@@ -556,11 +706,17 @@ def main(argv: list[str] | None = None) -> int:
|
||||
if not args.root or not args.output:
|
||||
parser.error("--root and --output are required unless --self-test")
|
||||
try:
|
||||
backup_root, quota_bytes, quota_error = resolve_backup_settings(
|
||||
args.root, args.usage_root or None, args.quota_bytes, args.config
|
||||
)
|
||||
snapshot = collect(
|
||||
args.root,
|
||||
source=args.source,
|
||||
host=args.host or None,
|
||||
max_batches=max(1, args.max_batches),
|
||||
backup_root=backup_root,
|
||||
quota_bytes=quota_bytes,
|
||||
quota_error=quota_error,
|
||||
)
|
||||
write_snapshot(args.output, snapshot)
|
||||
except (CollectError, OSError) as error:
|
||||
@@ -570,11 +726,17 @@ def main(argv: list[str] | None = None) -> int:
|
||||
"complete": snapshot["complete"],
|
||||
"batches": len(snapshot["batches"]),
|
||||
"incomplete_count": snapshot["incomplete_count"],
|
||||
"backup_root": snapshot["backup_root"],
|
||||
"usage_bytes": snapshot["usage"].get("actual_bytes"),
|
||||
"usage_complete": snapshot["usage"].get("complete"),
|
||||
"quota_bytes": snapshot["quota_bytes"],
|
||||
"quota_error": snapshot["quota_error"],
|
||||
"collected_at": snapshot["collected_at"],
|
||||
"output": args.output,
|
||||
}
|
||||
print(json.dumps(summary, ensure_ascii=False))
|
||||
return 0 if snapshot["complete"] else 2
|
||||
healthy = bool(snapshot["complete"] and snapshot["usage"].get("complete") and not snapshot["quota_error"])
|
||||
return 0 if healthy else 2
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -54,7 +54,10 @@ show_state() {
|
||||
if command -v systemctl >/dev/null 2>&1; then
|
||||
echo "cron 服务: $(systemctl is-active cron 2>/dev/null || systemctl is-active crond 2>/dev/null || echo unknown)"
|
||||
fi
|
||||
echo "备份根目录: $KB_BACKUP_ROOT($(du -sh "$KB_BACKUP_ROOT/rds-logical" 2>/dev/null | cut -f1 || echo 0) 已用)"
|
||||
QUOTA_BYTES="${KB_BACKUP_QUOTA_BYTES:-53687091200}"
|
||||
if ROOT_BYTES="$(du -sB1 -- "$KB_BACKUP_ROOT" 2>/dev/null | cut -f1)"; then :; else ROOT_BYTES="未知"; fi
|
||||
LOGICAL_USAGE="$(du -sh "$KB_BACKUP_ROOT/rds-logical" 2>/dev/null | cut -f1 || echo 未知)"
|
||||
echo "备份根占用: $KB_BACKUP_ROOT(${ROOT_BYTES:-未知} 字节 / 配额 $QUOTA_BYTES 字节;rds-logical $LOGICAL_USAGE)"
|
||||
}
|
||||
|
||||
if [ "$MODE" = "show" ]; then
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
# JOBS 并行度(默认 4)
|
||||
# KEEP_DAILY 保留最近几份每日备份(默认 7)
|
||||
# KEEP_MONTHS 额外保留最近几个自然月各一份(默认 3)
|
||||
# KB_BACKUP_QUOTA_BYTES 备份根累计占用硬上限(默认 53687091200 = 50 GiB,来自 backup.env)
|
||||
# EXCLUDE_DBS 逗号分隔的跳过列表(默认 rdsadmin:RDS 管理库,普通账号导不出来)
|
||||
set -euo pipefail
|
||||
|
||||
@@ -31,7 +32,28 @@ if [ -z "${KB_BACKUP_ROOT:-}" ] && [ -f /etc/knowledge-governance/backup.env ];
|
||||
. /etc/knowledge-governance/backup.env
|
||||
fi
|
||||
KB_BACKUP_ROOT="${KB_BACKUP_ROOT:-/srv/kb-backups}"
|
||||
# 配额与备份根同属 backup.env;KB_BACKUP_ROOT 显式传入时仍要读到配额,所以单独取值。
|
||||
layout_value() {
|
||||
local key="$1"
|
||||
[ -f "${KB_BACKUP_LAYOUT_ENV:-/etc/knowledge-governance/backup.env}" ] || return 0
|
||||
sed -n "s/^[[:space:]]*${key}=//p" "${KB_BACKUP_LAYOUT_ENV:-/etc/knowledge-governance/backup.env}" \
|
||||
| tail -1 | tr -d "\"' \r"
|
||||
}
|
||||
BACKUP_ROOT="${BACKUP_ROOT:-$KB_BACKUP_ROOT/rds-logical}"
|
||||
# 配额约束的是备份根(含 es-snapshots/target-kb-snapshots/logs),不是批次根。
|
||||
# 若显式把 BACKUP_ROOT 指到别处,就以它的父目录为准,避免量错盘。
|
||||
case "$BACKUP_ROOT" in
|
||||
"$KB_BACKUP_ROOT"/*) QUOTA_ROOT="$KB_BACKUP_ROOT" ;;
|
||||
*) QUOTA_ROOT="$(dirname "$BACKUP_ROOT")" ;;
|
||||
esac
|
||||
QUOTA_BYTES="${KB_BACKUP_QUOTA_BYTES:-$(layout_value KB_BACKUP_QUOTA_BYTES)}"
|
||||
QUOTA_BYTES="${QUOTA_BYTES:-53687091200}"
|
||||
case "$QUOTA_BYTES" in
|
||||
''|*[!0-9]*) echo "KB_BACKUP_QUOTA_BYTES 必须是正整数,收到 '$QUOTA_BYTES'" >&2; exit 1 ;;
|
||||
esac
|
||||
[ "$QUOTA_BYTES" -gt 0 ] || { echo "KB_BACKUP_QUOTA_BYTES 必须大于 0" >&2; exit 1; }
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
PRUNE_TOOL="$SCRIPT_DIR/prune_backup_batches.py"
|
||||
APP_CONTAINER="${APP_CONTAINER:-weknora-test-v071-app-1}"
|
||||
PG_IMAGE="${PG_IMAGE:-postgres:17.9-alpine}"
|
||||
JOBS="${JOBS:-4}"
|
||||
@@ -49,6 +71,26 @@ DRY_RUN="${DRY_RUN:-0}"
|
||||
DBS="${DBS:-}"
|
||||
EXCLUDE_DBS="${EXCLUDE_DBS:-rdsadmin}"
|
||||
STAMP="$(date -u +%Y%m%dT%H%M%SZ)"
|
||||
TARGET="$BACKUP_ROOT/$STAMP"
|
||||
|
||||
[ -f "$PRUNE_TOOL" ] || { echo "缺少配额清理工具:$PRUNE_TOOL(未开始备份)" >&2; exit 1; }
|
||||
|
||||
# 配额预检在 dump 之前、且不依赖 DB 凭据:失败时旧备份原样保留,也不会留下半成品目录。
|
||||
# 预留量取最近一份完整批次大小;prune 内部保证「保留最新一份」和「不够就一个都不删」。
|
||||
run_quota_prune() {
|
||||
local label="$1"; shift
|
||||
echo "-- 配额检查:$label --"
|
||||
python3 "$PRUNE_TOOL" \
|
||||
--backup-root "$QUOTA_ROOT" \
|
||||
--batch-root "$BACKUP_ROOT" \
|
||||
--quota-bytes "$QUOTA_BYTES" "$@"
|
||||
}
|
||||
|
||||
if [ "$DRY_RUN" = "1" ]; then
|
||||
run_quota_prune "预检(DRY_RUN,只打印计划)" --estimate latest --keep-latest || true
|
||||
echo "DRY_RUN=1,不执行"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
env_value() {
|
||||
docker inspect "$APP_CONTAINER" --format '{{range .Config.Env}}{{println .}}{{end}}' \
|
||||
@@ -81,8 +123,6 @@ print(','.join(d for d in sys.argv[1].split(',') if d and d not in exclude))
|
||||
fi
|
||||
if [ -z "$DBS" ]; then echo "没有可备份的库" >&2; exit 1; fi
|
||||
|
||||
TARGET="$BACKUP_ROOT/$STAMP"
|
||||
|
||||
# 失败或被中断(含被 head/管道 SIGPIPE 杀掉):把目录显式标记为半成品,
|
||||
# 这样"最近一次备份"的选择器与人都不会把它误当成功结果。
|
||||
mark_incomplete() {
|
||||
@@ -97,7 +137,14 @@ echo "备份目标: $TARGET"
|
||||
echo "库列表 : $DBS"
|
||||
echo "镜像 : $PG_IMAGE (并行 $JOBS)"
|
||||
echo "保留策略: 每日 $KEEP_DAILY 份 / 每月 $KEEP_MONTHS 份"
|
||||
if [ "$DRY_RUN" = "1" ]; then echo "DRY_RUN=1,不执行"; exit 0; fi
|
||||
echo "配额 : $QUOTA_BYTES 字节(备份根 $QUOTA_ROOT)"
|
||||
|
||||
# 真正删除旧批次放在凭据/库列表校验之后:连不上库时不应该先清历史备份。
|
||||
if run_quota_prune "预检" --estimate latest --keep-latest --apply; then :; else
|
||||
rc=$?
|
||||
echo "配额预检未通过(rc=$rc):本次备份取消,旧备份未被删除" >&2
|
||||
exit "$rc"
|
||||
fi
|
||||
|
||||
mkdir -p "$TARGET"
|
||||
STARTED_AT="$(date -u +%Y-%m-%dT%H:%M:%SZ)"
|
||||
@@ -215,6 +262,13 @@ for path in stamps:
|
||||
print("kept:", len([p for p in stamps if p.name in keep]))
|
||||
PY
|
||||
|
||||
# dump 后按实际占用复查:保护本次新批次,旧批次可删;仍超限则保留数据并告警。
|
||||
if run_quota_prune "dump 后复查" --estimate none --protect "$STAMP" --apply; then :; else
|
||||
rc=$?
|
||||
echo "本次备份已完成,但配额仍超出(rc=$rc):新批次保留,请扩容或人工清理" >&2
|
||||
exit "$rc"
|
||||
fi
|
||||
|
||||
if [ -n "$FAILED_DBS" ]; then
|
||||
echo "done(有失败的库): $TARGET | failed: $FAILED_DBS" >&2
|
||||
exit 1
|
||||
|
||||
Executable
+356
@@ -0,0 +1,356 @@
|
||||
#!/usr/bin/env python3
|
||||
"""按字节配额清理整库逻辑备份批次(宿主脚本,**只动平台自己的批次日录**)。
|
||||
|
||||
为什么单独成脚本:配额清理是唯一会删历史备份的动作,必须能离线、确定性地证明
|
||||
「最旧优先、预检保留最新、空间仍不够时零删除、非批次日录不动」。塞进
|
||||
logical-backup.sh 的内联 Python 只能靠跑 docker/psql 才能验证。
|
||||
|
||||
口径:占用用 `du -sB1 <备份根>`,与采集器声明的一致(0.1.408/0.1.409 的对拍口径)。
|
||||
`du` 退出非 0(权限/IO 错误)⇒ 不清理、非 0 退出:绝不拿部分统计去删备份。
|
||||
|
||||
用法:
|
||||
# 预检(dump 前):预留最近一份完整批次的大小,保留最新一份,不动就退出 3
|
||||
python3 prune_backup_batches.py --backup-root /srv/kb-backups \
|
||||
--quota-bytes 53687091200 --estimate latest --keep-latest --apply
|
||||
|
||||
# dump 后复查:保护本次新批次,其余旧批次可删
|
||||
python3 prune_backup_batches.py --backup-root /srv/kb-backups \
|
||||
--quota-bytes 53687091200 --estimate none --protect 20261125T033000Z --apply
|
||||
|
||||
退出码:0 已满足配额(可能删了旧批次);2 du/路径错误,未删除;3 空间仍不够,未删除;
|
||||
4 删除失败(已删的已生效,报错退出)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
from dataclasses import dataclass
|
||||
from typing import Iterable
|
||||
|
||||
STAMP_NAME = re.compile(r"^\d{8}T\d{6}Z$")
|
||||
|
||||
|
||||
class QuotaError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Candidate:
|
||||
name: str
|
||||
path: str
|
||||
size: int
|
||||
|
||||
|
||||
def measure(path: str) -> int:
|
||||
"""`du -sB1` 的实际分配字节;失败即抛错(部分和不能用)。"""
|
||||
try:
|
||||
result = subprocess.run(
|
||||
["du", "-sB1", "--", path], capture_output=True, text=True, check=False
|
||||
)
|
||||
except OSError as error:
|
||||
raise QuotaError(f"du 无法执行:{error}") from error
|
||||
if result.returncode != 0:
|
||||
raise QuotaError(f"du 失败({path}):{(result.stderr or result.stdout).strip()[:300]}")
|
||||
first = result.stdout.strip().splitlines()
|
||||
if not first:
|
||||
raise QuotaError(f"du 没有输出({path})")
|
||||
try:
|
||||
return int(first[0].split()[0])
|
||||
except (IndexError, ValueError) as error:
|
||||
raise QuotaError(f"du 输出无法解析({path}):{first[0]!r}") from error
|
||||
|
||||
|
||||
def _is_regular_file(path: str) -> bool:
|
||||
try:
|
||||
info = os.lstat(path)
|
||||
except OSError:
|
||||
return False
|
||||
return not os.path.islink(path) and os.path.isfile(path)
|
||||
|
||||
|
||||
def candidates(batch_root: str, measure_bytes=measure) -> list[Candidate]:
|
||||
"""只认批次根的直接子目录:名字像 UTC 戳、不是符号链接、含常规 MANIFEST.json。
|
||||
|
||||
`*.incomplete` 名字不匹配,自然排除;符号链接不跟随(否则会删到别处)。
|
||||
"""
|
||||
try:
|
||||
entries = list(os.scandir(batch_root))
|
||||
except OSError as error:
|
||||
raise QuotaError(f"批次根不可读({batch_root}):{error}") from error
|
||||
found: list[Candidate] = []
|
||||
for entry in entries:
|
||||
if not STAMP_NAME.match(entry.name):
|
||||
continue
|
||||
if entry.is_symlink() or not entry.is_dir(follow_symlinks=False):
|
||||
continue
|
||||
if not _is_regular_file(os.path.join(entry.path, "MANIFEST.json")):
|
||||
continue
|
||||
found.append(Candidate(entry.name, entry.path, measure_bytes(entry.path)))
|
||||
found.sort(key=lambda item: item.name)
|
||||
return found
|
||||
|
||||
|
||||
def plan_deletions(
|
||||
usage: int,
|
||||
candidates_oldest_first: Iterable[Candidate],
|
||||
quota: int,
|
||||
estimate: int,
|
||||
protect: set[str],
|
||||
) -> tuple[list[Candidate], int, bool]:
|
||||
"""返回(应删列表、删除后预计占用、是否仍超限)。
|
||||
|
||||
超出配额时从最旧开始删,直到「预计占用 + 预留」装得下;`protect` 里的批次永不删。
|
||||
仍超限时调用方必须**一个都不删**(见 apply)。
|
||||
"""
|
||||
projected = usage
|
||||
planned: list[Candidate] = []
|
||||
for candidate in candidates_oldest_first:
|
||||
if projected + estimate <= quota:
|
||||
break
|
||||
if candidate.name in protect:
|
||||
continue
|
||||
planned.append(candidate)
|
||||
projected -= candidate.size
|
||||
insufficient = projected + estimate > quota
|
||||
return planned, projected, insufficient
|
||||
|
||||
|
||||
def resolve_estimate(value: str, candidates_oldest_first: list[Candidate]) -> int:
|
||||
if value in ("", "none"):
|
||||
return 0
|
||||
if value == "latest":
|
||||
if not candidates_oldest_first:
|
||||
return 0
|
||||
return candidates_oldest_first[-1].size
|
||||
try:
|
||||
number = int(value)
|
||||
except ValueError as error:
|
||||
raise QuotaError(f"--estimate 只接受 latest/none/字节数,收到 {value!r}") from error
|
||||
if number < 0:
|
||||
raise QuotaError("--estimate 不能为负数")
|
||||
return number
|
||||
|
||||
|
||||
def prune(
|
||||
backup_root: str,
|
||||
batch_root: str,
|
||||
quota: int,
|
||||
estimate: int,
|
||||
protect: set[str],
|
||||
keep_latest: bool,
|
||||
apply: bool,
|
||||
measure_bytes=measure,
|
||||
) -> dict:
|
||||
if quota <= 0:
|
||||
raise QuotaError("--quota-bytes 必须是正整数")
|
||||
backup_root = os.path.abspath(backup_root)
|
||||
batch_root = os.path.abspath(batch_root)
|
||||
if batch_root != backup_root and not batch_root.startswith(backup_root.rstrip("/") + "/"):
|
||||
raise QuotaError(f"批次根 {batch_root} 不在备份根 {backup_root} 下")
|
||||
found = candidates(batch_root, measure_bytes)
|
||||
usage = measure_bytes(backup_root)
|
||||
protected = set(protect)
|
||||
if keep_latest and found:
|
||||
protected.add(found[-1].name)
|
||||
planned, projected, insufficient = plan_deletions(usage, found, quota, estimate, protected)
|
||||
result = {
|
||||
"backup_root": backup_root,
|
||||
"batch_root": batch_root,
|
||||
"quota_bytes": quota,
|
||||
"usage_bytes": usage,
|
||||
"estimate_bytes": estimate,
|
||||
"projected_bytes": projected,
|
||||
"protected": sorted(protected),
|
||||
"plan": [item.name for item in planned],
|
||||
"insufficient": insufficient,
|
||||
"applied": False,
|
||||
}
|
||||
if insufficient:
|
||||
return result
|
||||
if not apply:
|
||||
return result
|
||||
for item in planned:
|
||||
target = os.path.abspath(item.path)
|
||||
if os.path.dirname(target) != batch_root:
|
||||
raise QuotaError(f"拒绝删除批次根之外的路径:{target}")
|
||||
if os.path.islink(target) or not os.path.isdir(target):
|
||||
raise QuotaError(f"拒绝删除非目录或符号链接:{target}")
|
||||
try:
|
||||
shutil.rmtree(target)
|
||||
except OSError as error:
|
||||
raise QuotaError(f"删除失败({target}):{error}") from error
|
||||
result["applied"] = True
|
||||
result["usage_after_bytes"] = measure_bytes(backup_root)
|
||||
return result
|
||||
|
||||
|
||||
def _self_test() -> None:
|
||||
base = tempfile.mkdtemp(prefix="backup-quota-test-")
|
||||
try:
|
||||
root = os.path.join(base, "kb-backups")
|
||||
batch_root = os.path.join(root, "rds-logical")
|
||||
os.makedirs(batch_root)
|
||||
es_dir = os.path.join(root, "es-snapshots")
|
||||
os.makedirs(es_dir)
|
||||
with open(os.path.join(es_dir, "index-0"), "wb") as handle:
|
||||
handle.write(b"e" * 8192)
|
||||
|
||||
def make_batch(stamp: str, kib: int) -> str:
|
||||
path = os.path.join(batch_root, stamp)
|
||||
db = os.path.join(path, "weknora.dir")
|
||||
os.makedirs(db)
|
||||
with open(os.path.join(db, "toc.dat"), "wb") as handle:
|
||||
handle.write(b"x" * (kib * 1024))
|
||||
with open(os.path.join(path, "MANIFEST.json"), "w", encoding="utf-8") as handle:
|
||||
handle.write('{"databases":["weknora"]}')
|
||||
return path
|
||||
|
||||
stamps = ["20261101T030000Z", "20261102T030000Z", "20261103T030000Z", "20261104T030000Z"]
|
||||
paths = [make_batch(stamp, 256) for stamp in stamps]
|
||||
# 非批次日录、半成品、指向别处的符号链接都不能进候选/被删。
|
||||
os.makedirs(os.path.join(root, "logs"))
|
||||
with open(os.path.join(root, "logs", "logical-backup.log"), "wb") as handle:
|
||||
handle.write(b"l" * 4096)
|
||||
os.makedirs(os.path.join(batch_root, "notes"))
|
||||
with open(os.path.join(batch_root, "notes", "keep.txt"), "wb") as handle:
|
||||
handle.write(b"n" * 1024)
|
||||
os.makedirs(os.path.join(batch_root, "20261105T030000Z.incomplete"))
|
||||
outside = os.path.join(base, "outside")
|
||||
os.makedirs(outside)
|
||||
with open(os.path.join(outside, "MANIFEST.json"), "w", encoding="utf-8") as handle:
|
||||
handle.write("{}")
|
||||
os.symlink(outside, os.path.join(batch_root, "20261106T030000Z"))
|
||||
|
||||
found = candidates(batch_root)
|
||||
assert [item.name for item in found] == stamps, found
|
||||
usage = measure(root)
|
||||
assert usage > sum(item.size for item in found)
|
||||
newest_size = found[-1].size
|
||||
|
||||
# 1) 预检:需要腾出空间时从最旧删,最新一份永不在计划里。
|
||||
estimate = newest_size
|
||||
quota = usage - found[0].size + estimate
|
||||
planned, projected, insufficient = plan_deletions(
|
||||
usage, found, quota, estimate, {found[-1].name}
|
||||
)
|
||||
assert not insufficient
|
||||
assert [item.name for item in planned] == [found[0].name], planned
|
||||
assert all(item.name != found[-1].name for item in planned)
|
||||
assert projected + estimate <= quota
|
||||
|
||||
# 2) 空间仍不够:一个都不删,目录全部还在。
|
||||
too_tight = max(1, estimate)
|
||||
result = prune(
|
||||
root, batch_root, too_tight, estimate, set(), keep_latest=True, apply=True
|
||||
)
|
||||
assert result["insufficient"] is True and result["applied"] is False, result
|
||||
assert all(os.path.isdir(path) for path in paths)
|
||||
assert os.path.isdir(os.path.join(batch_root, "notes"))
|
||||
assert os.path.isdir(os.path.join(root, "logs"))
|
||||
assert os.path.isdir(os.path.join(root, "es-snapshots"))
|
||||
|
||||
# 3) dump 后:保护新批次,允许删上一份最新;只删计划内、非批次日录不动。
|
||||
new_stamp = "20261109T030000Z"
|
||||
new_path = make_batch(new_stamp, 256)
|
||||
after_usage = measure(root)
|
||||
protect = {new_stamp}
|
||||
result = prune(
|
||||
root,
|
||||
batch_root,
|
||||
after_usage - found[0].size,
|
||||
0,
|
||||
protect,
|
||||
keep_latest=False,
|
||||
apply=True,
|
||||
)
|
||||
assert result["applied"] is True and result["plan"] == [found[0].name], result
|
||||
assert not os.path.exists(found[0].path)
|
||||
assert os.path.isdir(new_path)
|
||||
assert os.path.isdir(found[-1].path)
|
||||
assert os.path.isdir(os.path.join(batch_root, "notes"))
|
||||
assert os.path.isdir(os.path.join(batch_root, "20261105T030000Z.incomplete"))
|
||||
assert os.path.isdir(os.path.join(root, "es-snapshots"))
|
||||
|
||||
# 4) 测量失败必须零删除:注入抛错的 measure。
|
||||
def broken(_path: str) -> int:
|
||||
raise QuotaError("du 失败(注入)")
|
||||
|
||||
try:
|
||||
prune(root, batch_root, 1, 0, set(), keep_latest=True, apply=True, measure_bytes=broken)
|
||||
except QuotaError:
|
||||
pass
|
||||
else:
|
||||
raise AssertionError("测量失败必须中止")
|
||||
assert os.path.isdir(found[-1].path)
|
||||
|
||||
# 5) 批次根逃逸必须拒绝。
|
||||
try:
|
||||
prune(root, os.path.join(base, "outside"), 1 << 40, 0, set(), True, True)
|
||||
except QuotaError:
|
||||
pass
|
||||
else:
|
||||
raise AssertionError("批次根不在备份根下必须拒绝")
|
||||
|
||||
print("prune_backup_batches self-test ok")
|
||||
finally:
|
||||
shutil.rmtree(base, ignore_errors=True)
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(description="按字节配额清理整库备份批次")
|
||||
parser.add_argument("--backup-root", default="", help="备份根(默认 backup.env 的 KB_BACKUP_ROOT)")
|
||||
parser.add_argument("--batch-root", default="", help="批次日录根(默认 <备份根>/rds-logical)")
|
||||
parser.add_argument("--quota-bytes", type=int, default=0)
|
||||
parser.add_argument("--estimate", default="none", help="新批次预留:latest / none / 字节数")
|
||||
parser.add_argument("--protect", action="append", default=[], help="永不删除的批次戳(可重复)")
|
||||
parser.add_argument("--keep-latest", action="store_true", help="预检模式:保留最新一份完整批次")
|
||||
parser.add_argument("--apply", action="store_true", help="真的删除;缺省只打印计划")
|
||||
parser.add_argument("--json", action="store_true")
|
||||
parser.add_argument("--self-test", action="store_true")
|
||||
args = parser.parse_args(argv)
|
||||
if args.self_test:
|
||||
_self_test()
|
||||
return 0
|
||||
try:
|
||||
backup_root = args.backup_root or os.environ.get("KB_BACKUP_ROOT", "") or "/srv/kb-backups"
|
||||
batch_root = args.batch_root or os.path.join(backup_root, "rds-logical")
|
||||
found = candidates(batch_root)
|
||||
estimate = resolve_estimate(args.estimate, found)
|
||||
result = prune(
|
||||
backup_root,
|
||||
batch_root,
|
||||
args.quota_bytes,
|
||||
estimate,
|
||||
set(args.protect),
|
||||
args.keep_latest,
|
||||
args.apply,
|
||||
)
|
||||
except QuotaError as error:
|
||||
print(f"quota prune failed: {error}", file=sys.stderr)
|
||||
return 2
|
||||
if args.json:
|
||||
import json
|
||||
|
||||
print(json.dumps(result, ensure_ascii=False))
|
||||
else:
|
||||
print(
|
||||
f"备份占用 {result['usage_bytes']} / 配额 {result['quota_bytes']}"
|
||||
f"(预留 {result['estimate_bytes']},保护 {result['protected'] or '无'})"
|
||||
)
|
||||
print("删除计划:" + ("、".join(result["plan"]) if result["plan"] else "无"))
|
||||
if result["insufficient"]:
|
||||
print("空间仍不够:未删除任何批次", file=sys.stderr)
|
||||
elif result["applied"]:
|
||||
print(f"已删除 {len(result['plan'])} 个批次,占用 {result['usage_after_bytes']}")
|
||||
if result["insufficient"]:
|
||||
return 3
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -5,7 +5,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import { StorageBackupSummary } from './StorageBackupSummary'
|
||||
import type { BackupInventory, BackupInventoryBatch } from './backupInventory'
|
||||
import type { LibraryStorage } from './librarySnapshots'
|
||||
|
||||
const GIB = 1024 ** 3
|
||||
const TB = 1024 * GIB
|
||||
@@ -66,6 +65,7 @@ const inventory = (overrides: Partial<BackupInventory> = {}): BackupInventory =>
|
||||
},
|
||||
root: '/srv/kb-backups/rds-logical',
|
||||
host_root: '/srv/kb-backups/rds-logical',
|
||||
backup_root: '/srv/kb-backups',
|
||||
source: 'host',
|
||||
observed_at: '2026-11-24T10:18:00Z',
|
||||
measurement: 'host-reported',
|
||||
@@ -86,6 +86,18 @@ const inventory = (overrides: Partial<BackupInventory> = {}): BackupInventory =>
|
||||
available_bytes: 1.2 * TB,
|
||||
used_bytes: 0.8 * TB,
|
||||
},
|
||||
usage: {
|
||||
root: '/srv/kb-backups',
|
||||
measured: true,
|
||||
complete: true,
|
||||
actual_bytes: 40 * GIB,
|
||||
apparent_bytes: 36 * GIB,
|
||||
file_count: 400,
|
||||
dir_count: 20,
|
||||
error: '',
|
||||
},
|
||||
quota_bytes: 50 * GIB,
|
||||
quota_error: '',
|
||||
batches: [batch(0), batch(1, { manifest_state: 'invalid' })],
|
||||
totals: {
|
||||
batch_count: 2,
|
||||
@@ -102,29 +114,6 @@ const inventory = (overrides: Partial<BackupInventory> = {}): BackupInventory =>
|
||||
...overrides,
|
||||
})
|
||||
|
||||
const archive: LibraryStorage = {
|
||||
available: true,
|
||||
archive_root: '/var/lib/knowledge-governance/library',
|
||||
versions: [],
|
||||
content_bytes: 41_231_686_042,
|
||||
blob_file_bytes: 0,
|
||||
blob_allocated_bytes: 0,
|
||||
unreferenced_blobs: 0,
|
||||
unreferenced_bytes: 0,
|
||||
manifest_file_bytes: 0,
|
||||
policy: { keep_versions: 0, keep_days: 0 },
|
||||
capacity: {
|
||||
budget_bytes: 100 * GIB,
|
||||
current_bytes: 41_231_686_042,
|
||||
required_bytes: 0,
|
||||
projected_bytes: 41_231_686_042,
|
||||
configured: true,
|
||||
ok: true,
|
||||
},
|
||||
automatic_cleanup: false,
|
||||
notes: [],
|
||||
}
|
||||
|
||||
let root: Root
|
||||
let container: HTMLDivElement
|
||||
let fetcher: ReturnType<typeof vi.fn<(path: string, init?: RequestInit) => Promise<Response>>>
|
||||
@@ -145,7 +134,7 @@ beforeEach(() => {
|
||||
if (path.endsWith('/inventory')) {
|
||||
return new Response(JSON.stringify({ data: inventory() }), { status: 200 })
|
||||
}
|
||||
return new Response(JSON.stringify(archive), { status: 200 })
|
||||
return new Response('{}', { status: 404 })
|
||||
})
|
||||
vi.stubGlobal('fetch', fetcher)
|
||||
})
|
||||
@@ -158,7 +147,7 @@ afterEach(() => {
|
||||
})
|
||||
|
||||
describe('StorageBackupSummary', () => {
|
||||
it('renders directory, recent outcomes, archive usage, disk and the alert table', async () => {
|
||||
it('renders directory, recent outcomes, backup occupancy, disk and the alert table', async () => {
|
||||
act(() => root.render(<StorageBackupSummary />))
|
||||
await flush()
|
||||
const text = container.textContent || ''
|
||||
@@ -166,9 +155,10 @@ describe('StorageBackupSummary', () => {
|
||||
expect(text).toContain('/srv/kb-backups/rds-logical')
|
||||
expect(text).toContain('最近成功')
|
||||
expect(text).toContain('最近失败')
|
||||
expect(text).toContain('归档占用')
|
||||
expect(text).toContain('38.4 GB')
|
||||
expect(text).toContain('配额 100 GB')
|
||||
expect(text).toContain('备份占用')
|
||||
expect(text).toContain('40 GB')
|
||||
expect(text).toContain('配额 50 GB')
|
||||
expect(text).not.toContain('归档占用')
|
||||
expect(text).toContain('磁盘剩余')
|
||||
expect(text).toContain('1.2 TB')
|
||||
expect(text).toContain('上次上报')
|
||||
@@ -180,12 +170,12 @@ describe('StorageBackupSummary', () => {
|
||||
expect(text).not.toContain('示例')
|
||||
})
|
||||
|
||||
it('asks for both read-only endpoints and refreshes once per 60 seconds while visible', async () => {
|
||||
it('asks for the read-only inventory endpoint and refreshes once per 60 seconds while visible', async () => {
|
||||
vi.useFakeTimers()
|
||||
act(() => root.render(<StorageBackupSummary />))
|
||||
await flush()
|
||||
expect(paths().filter((path) => path.endsWith('/inventory'))).toHaveLength(1)
|
||||
expect(paths().filter((path) => path.endsWith('/library/storage'))).toHaveLength(1)
|
||||
expect(paths().filter((path) => path.endsWith('/library/storage'))).toHaveLength(0)
|
||||
|
||||
await act(async () => {
|
||||
await vi.advanceTimersByTimeAsync(60_000)
|
||||
@@ -215,18 +205,14 @@ describe('StorageBackupSummary', () => {
|
||||
host_root: '',
|
||||
batches: [],
|
||||
capacity: { measured: false, total_bytes: 0, free_bytes: 0, available_bytes: 0, used_bytes: 0 },
|
||||
usage: { ...wired.usage, measured: false, complete: false, actual_bytes: null, error: '' },
|
||||
metadata: { ...wired.metadata, present: false, valid: false, fresh: false, collected_at: '' },
|
||||
},
|
||||
}),
|
||||
{ status: 200 }
|
||||
)
|
||||
}
|
||||
return new Response(
|
||||
JSON.stringify({ ...archive, available: false, capacity: { ...archive.capacity, configured: false } }),
|
||||
{
|
||||
status: 200,
|
||||
}
|
||||
)
|
||||
return new Response('{}', { status: 404 })
|
||||
})
|
||||
act(() => root.render(<StorageBackupSummary />))
|
||||
await flush()
|
||||
@@ -264,7 +250,7 @@ describe('StorageBackupSummary', () => {
|
||||
{ status: 200 }
|
||||
)
|
||||
}
|
||||
return new Response(JSON.stringify(archive), { status: 200 })
|
||||
return new Response('{}', { status: 404 })
|
||||
})
|
||||
act(() => root.render(<StorageBackupSummary />))
|
||||
await flush()
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
// 「系统设置 → 存储与备份」只读摘要页:目录、最近成功/失败、归档占用、磁盘剩余、
|
||||
// 四条容量告警和批次列表。数据只来自宿主每 5 分钟上报的快照与归档库接口,
|
||||
// 本页没有任何写操作;读不到的量显示"主机未上报"或"—",不用 0 占位。
|
||||
// 「系统设置 → 存储与备份」只读摘要页:目录、最近成功/失败、备份占用、磁盘剩余、
|
||||
// 四条容量告警和批次列表。数据只来自宿主采集器上报的快照,本页没有任何写操作;
|
||||
// 读不到的量显示"主机未上报"或"—",不用 0 占位。
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
|
||||
import { fetchBackupInventory } from './backupInventory'
|
||||
import type { BackupInventory } from './backupInventory'
|
||||
import { fetchLibraryStorage } from './librarySnapshots'
|
||||
import type { LibraryStorage } from './librarySnapshots'
|
||||
import {
|
||||
UNKNOWN,
|
||||
batchOutcome,
|
||||
@@ -65,8 +63,6 @@ const hostStateLabel = (state: HostState): string => {
|
||||
|
||||
export function StorageBackupSummary() {
|
||||
const [inventory, setInventory] = useState<BackupInventory | null>(null)
|
||||
const [archive, setArchive] = useState<LibraryStorage | null>(null)
|
||||
const [archiveFailed, setArchiveFailed] = useState(false)
|
||||
const [errors, setErrors] = useState<string[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [visible, setVisible] = useState(BATCH_PAGE)
|
||||
@@ -77,24 +73,15 @@ export function StorageBackupSummary() {
|
||||
const load = useCallback(async () => {
|
||||
if (inFlight.current) return
|
||||
inFlight.current = true
|
||||
const [inventoryResult, archiveResult] = await Promise.allSettled([fetchBackupInventory(), fetchLibraryStorage()])
|
||||
const nextErrors: string[] = []
|
||||
if (inventoryResult.status === 'fulfilled') {
|
||||
setInventory(inventoryResult.value)
|
||||
} else {
|
||||
nextErrors.push(inventoryResult.reason instanceof Error ? inventoryResult.reason.message : '读取备份元数据失败')
|
||||
try {
|
||||
setInventory(await fetchBackupInventory())
|
||||
setErrors([])
|
||||
} catch (error) {
|
||||
setErrors([error instanceof Error ? error.message : '读取备份元数据失败'])
|
||||
} finally {
|
||||
setLoading(false)
|
||||
inFlight.current = false
|
||||
}
|
||||
if (archiveResult.status === 'fulfilled') {
|
||||
setArchive(archiveResult.value)
|
||||
setArchiveFailed(archiveResult.value === null)
|
||||
if (archiveResult.value === null) nextErrors.push('读取归档占用失败')
|
||||
} else {
|
||||
setArchiveFailed(true)
|
||||
nextErrors.push(archiveResult.reason instanceof Error ? archiveResult.reason.message : '读取归档占用失败')
|
||||
}
|
||||
setErrors(nextErrors)
|
||||
setLoading(false)
|
||||
inFlight.current = false
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
@@ -110,8 +97,8 @@ export function StorageBackupSummary() {
|
||||
}, [load])
|
||||
|
||||
const state = hostState(inventory)
|
||||
const alerts = storageAlerts(inventory, archive, archiveFailed)
|
||||
const cards = summaryCards(inventory, archive, archiveFailed)
|
||||
const alerts = storageAlerts(inventory)
|
||||
const cards = summaryCards(inventory)
|
||||
const batches = inventory?.batches ?? []
|
||||
const shown = batches.slice(0, visible)
|
||||
|
||||
|
||||
@@ -43,6 +43,19 @@ const payload = {
|
||||
available_bytes: 48318382080,
|
||||
used_bytes: 206158430208,
|
||||
},
|
||||
backup_root: '/srv/kb-backups',
|
||||
usage: {
|
||||
root: '/srv/kb-backups',
|
||||
measured: true,
|
||||
complete: true,
|
||||
actual_bytes: 24318382080,
|
||||
apparent_bytes: 23000000000,
|
||||
file_count: 900,
|
||||
dir_count: 30,
|
||||
error: '',
|
||||
},
|
||||
quota_bytes: 53687091200,
|
||||
quota_error: '',
|
||||
batches: [
|
||||
{
|
||||
stamp: '20261118T193001Z',
|
||||
@@ -108,6 +121,48 @@ describe('fetchBackupInventory', () => {
|
||||
'/srv/kb-backups/rds-logical/20261118T193001Z/weknora_v090prod.dir'
|
||||
)
|
||||
expect(inventory.batches[0].databases[0].actual_bytes).toBe(720896)
|
||||
expect(inventory.backup_root).toBe('/srv/kb-backups')
|
||||
expect(inventory.usage.measured).toBe(true)
|
||||
expect(inventory.usage.actual_bytes).toBe(24318382080)
|
||||
expect(inventory.quota_bytes).toBe(53687091200)
|
||||
expect(inventory.quota_error).toBe('')
|
||||
})
|
||||
|
||||
it('旧采集器缺 usage/quota 时显式未上报,不用批次和冒充占用', async () => {
|
||||
const legacy = JSON.parse(JSON.stringify(payload))
|
||||
delete legacy.data.backup_root
|
||||
delete legacy.data.usage
|
||||
delete legacy.data.quota_bytes
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn(() => Promise.resolve({ ok: true, json: () => Promise.resolve(legacy) }))
|
||||
)
|
||||
const inventory = await fetchBackupInventory()
|
||||
expect(inventory.usage.measured).toBe(false)
|
||||
expect(inventory.usage.actual_bytes).toBeNull()
|
||||
expect(inventory.usage.error).toContain('未上报')
|
||||
expect(inventory.quota_bytes).toBeNull()
|
||||
expect(inventory.quota_error).toContain('未上报')
|
||||
expect(inventory.totals.actual_bytes).toBe(1500000000)
|
||||
})
|
||||
|
||||
it('不完整占用即使带部分字节也不展示', async () => {
|
||||
const partial = JSON.parse(JSON.stringify(payload))
|
||||
partial.data.usage = {
|
||||
...partial.data.usage,
|
||||
measured: true,
|
||||
complete: false,
|
||||
actual_bytes: 123,
|
||||
error: '备份根占用未知:遍历失败',
|
||||
}
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn(() => Promise.resolve({ ok: true, json: () => Promise.resolve(partial) }))
|
||||
)
|
||||
const inventory = await fetchBackupInventory()
|
||||
expect(inventory.usage.measured).toBe(false)
|
||||
expect(inventory.usage.actual_bytes).toBeNull()
|
||||
expect(inventory.usage.error).toContain('遍历失败')
|
||||
})
|
||||
|
||||
it('响应缺 wired 时整块报错,不默认成未接线', async () => {
|
||||
|
||||
@@ -39,6 +39,18 @@ export interface BackupInventoryCapacity {
|
||||
error?: string
|
||||
}
|
||||
|
||||
// 备份根累计占用:配额约束的对象。measured=false 时字节全为 null,页面不得用 0 冒充。
|
||||
export interface BackupInventoryUsage {
|
||||
root: string
|
||||
measured: boolean
|
||||
complete: boolean
|
||||
actual_bytes: number | null
|
||||
apparent_bytes: number | null
|
||||
file_count: number | null
|
||||
dir_count: number | null
|
||||
error: string
|
||||
}
|
||||
|
||||
export interface BackupInventoryDatabase {
|
||||
name: string
|
||||
dir_name: string
|
||||
@@ -84,12 +96,16 @@ export interface BackupInventory {
|
||||
metadata: BackupInventoryMetadata
|
||||
root: string
|
||||
host_root: string
|
||||
backup_root: string
|
||||
source: string
|
||||
observed_at: string
|
||||
error?: string
|
||||
measurement: string
|
||||
mount: BackupInventoryMount
|
||||
capacity: BackupInventoryCapacity
|
||||
usage: BackupInventoryUsage
|
||||
quota_bytes: number | null
|
||||
quota_error: string
|
||||
batches: BackupInventoryBatch[]
|
||||
totals: {
|
||||
batch_count: number
|
||||
@@ -115,6 +131,22 @@ const asNumberOrNull = (value: unknown): number | null =>
|
||||
const asBool = (value: unknown): boolean => value === true
|
||||
const asList = (value: unknown): unknown[] => (Array.isArray(value) ? value : [])
|
||||
|
||||
const usageProjection = (value: unknown): BackupInventoryUsage => {
|
||||
const entry = record(value) ? value : {}
|
||||
const complete = asBool(entry.complete)
|
||||
const measured = asBool(entry.measured) && complete && asNumberOrNull(entry.actual_bytes) !== null
|
||||
return {
|
||||
root: asString(entry.root),
|
||||
measured,
|
||||
complete,
|
||||
actual_bytes: measured ? asNumberOrNull(entry.actual_bytes) : null,
|
||||
apparent_bytes: measured ? asNumberOrNull(entry.apparent_bytes) : null,
|
||||
file_count: measured ? asNumberOrNull(entry.file_count) : null,
|
||||
dir_count: measured ? asNumberOrNull(entry.dir_count) : null,
|
||||
error: asString(entry.error) || (measured ? '' : '采集器未上报备份根占用(需要升级采集器)'),
|
||||
}
|
||||
}
|
||||
|
||||
const manifestState = (value: unknown): BackupManifestState =>
|
||||
value === 'ok' || value === 'missing' || value === 'invalid' ? value : 'invalid'
|
||||
|
||||
@@ -186,10 +218,16 @@ function inventoryProjection(value: unknown): BackupInventory {
|
||||
},
|
||||
root: asString(value.root),
|
||||
host_root: asString(value.host_root),
|
||||
backup_root: asString(value.backup_root),
|
||||
source: asString(value.source),
|
||||
observed_at: asString(value.observed_at),
|
||||
error: asString(value.error),
|
||||
measurement: asString(value.measurement),
|
||||
usage: usageProjection(value.usage),
|
||||
quota_bytes: asNumberOrNull(value.quota_bytes),
|
||||
quota_error:
|
||||
asString(value.quota_error) ||
|
||||
(asNumberOrNull(value.quota_bytes) === null ? '采集器未上报备份配额(需要升级采集器)' : ''),
|
||||
mount: {
|
||||
container_root: asString(mount.container_root),
|
||||
mount_verified: asBool(mount.mount_verified),
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import type { BackupInventory, BackupInventoryBatch } from './backupInventory'
|
||||
import type { LibraryStorage } from './librarySnapshots'
|
||||
import {
|
||||
DISK_CRITICAL_AVAILABLE_PERCENT,
|
||||
batchOutcome,
|
||||
@@ -70,6 +69,7 @@ export const inventory = (overrides: Partial<BackupInventory> = {}): BackupInven
|
||||
},
|
||||
root: '/srv/kb-backups/rds-logical',
|
||||
host_root: '/srv/kb-backups/rds-logical',
|
||||
backup_root: '/srv/kb-backups',
|
||||
source: 'host',
|
||||
observed_at: '2026-11-24T10:18:00Z',
|
||||
measurement: 'host-reported',
|
||||
@@ -90,6 +90,18 @@ export const inventory = (overrides: Partial<BackupInventory> = {}): BackupInven
|
||||
available_bytes: 1.2 * TB,
|
||||
used_bytes: 0.8 * TB,
|
||||
},
|
||||
usage: {
|
||||
root: '/srv/kb-backups',
|
||||
measured: true,
|
||||
complete: true,
|
||||
actual_bytes: 22.65 * GIB,
|
||||
apparent_bytes: 20 * GIB,
|
||||
file_count: 1000,
|
||||
dir_count: 40,
|
||||
error: '',
|
||||
},
|
||||
quota_bytes: 50 * GIB,
|
||||
quota_error: '',
|
||||
batches: [batch()],
|
||||
totals: {
|
||||
batch_count: 1,
|
||||
@@ -106,30 +118,6 @@ export const inventory = (overrides: Partial<BackupInventory> = {}): BackupInven
|
||||
...overrides,
|
||||
})
|
||||
|
||||
export const archive = (overrides: Partial<LibraryStorage> = {}): LibraryStorage => ({
|
||||
available: true,
|
||||
archive_root: '/var/lib/knowledge-governance/library',
|
||||
versions: [],
|
||||
content_bytes: 41_231_686_042,
|
||||
blob_file_bytes: 0,
|
||||
blob_allocated_bytes: 0,
|
||||
unreferenced_blobs: 0,
|
||||
unreferenced_bytes: 0,
|
||||
manifest_file_bytes: 0,
|
||||
policy: { keep_versions: 0, keep_days: 0 },
|
||||
capacity: {
|
||||
budget_bytes: 100 * GIB,
|
||||
current_bytes: 41_231_686_042,
|
||||
required_bytes: 0,
|
||||
projected_bytes: 41_231_686_042,
|
||||
configured: true,
|
||||
ok: true,
|
||||
},
|
||||
automatic_cleanup: false,
|
||||
notes: [],
|
||||
...overrides,
|
||||
})
|
||||
|
||||
const unreported = (): BackupInventory =>
|
||||
inventory({
|
||||
wired: false,
|
||||
@@ -151,6 +139,19 @@ const unreported = (): BackupInventory =>
|
||||
},
|
||||
root: '',
|
||||
host_root: '',
|
||||
backup_root: '',
|
||||
usage: {
|
||||
root: '',
|
||||
measured: false,
|
||||
complete: false,
|
||||
actual_bytes: null,
|
||||
apparent_bytes: null,
|
||||
file_count: null,
|
||||
dir_count: null,
|
||||
error: '采集器未上报备份根占用(需要升级采集器)',
|
||||
},
|
||||
quota_bytes: null,
|
||||
quota_error: '采集器未上报备份配额(需要升级采集器)',
|
||||
capacity: { measured: false, total_bytes: 0, free_bytes: 0, available_bytes: 0, used_bytes: 0 },
|
||||
batches: [],
|
||||
totals: {
|
||||
@@ -230,48 +231,57 @@ describe('recentOutcome', () => {
|
||||
})
|
||||
|
||||
describe('summaryCards', () => {
|
||||
it('shows real values when the host reported and the archive is available', () => {
|
||||
const cards = summaryCards(inventory(), archive(), false)
|
||||
it('shows real values from the host snapshot for backup occupancy and quota', () => {
|
||||
const cards = summaryCards(inventory())
|
||||
const byKey = Object.fromEntries(cards.map((card) => [card.key, card.value]))
|
||||
expect(byKey.root).toBe('/srv/kb-backups/rds-logical')
|
||||
expect(byKey.success).toBe(formatWhen('2026-11-24T02:00:00Z'))
|
||||
expect(byKey.failure).toBe('无')
|
||||
expect(byKey.archive).toBe('38.4 GB')
|
||||
expect(byKey.backup).toBe(formatSize(22.65 * GIB))
|
||||
expect(byKey.disk).toBe('1.2 TB')
|
||||
expect(cards.find((card) => card.key === 'archive')?.note).toBe('配额 100 GB')
|
||||
expect(cards.find((card) => card.key === 'backup')?.note).toBe('配额 50 GB')
|
||||
expect(cards.some((card) => card.label === '归档占用')).toBe(false)
|
||||
})
|
||||
|
||||
it('shows 主机未上报 with the last report time instead of 0 when the host never reported', () => {
|
||||
const cards = summaryCards(unreported(), archive({ available: false }), false)
|
||||
for (const key of ['root', 'success', 'failure', 'disk']) {
|
||||
const cards = summaryCards(unreported())
|
||||
for (const key of ['root', 'success', 'failure', 'backup', 'disk']) {
|
||||
const card = cards.find((item) => item.key === key)!
|
||||
expect(card.value).toBe('主机未上报')
|
||||
expect(card.note).toBe('上次上报 —')
|
||||
}
|
||||
expect(cards.find((card) => card.key === 'archive')?.value).toBe('—')
|
||||
expect(cards.some((card) => card.value === '0 B')).toBe(false)
|
||||
})
|
||||
|
||||
it('keeps paths readable but leaves sizes empty for an incomplete report', () => {
|
||||
const cards = summaryCards(inventory({ metadata: { ...inventory().metadata, complete: false } }), archive(), false)
|
||||
const cards = summaryCards(
|
||||
inventory({
|
||||
metadata: { ...inventory().metadata, complete: false },
|
||||
usage: {
|
||||
...inventory().usage,
|
||||
measured: false,
|
||||
complete: false,
|
||||
actual_bytes: null,
|
||||
error: '备份根占用未知:遍历失败',
|
||||
},
|
||||
})
|
||||
)
|
||||
expect(cards.find((card) => card.key === 'root')?.value).toBe('/srv/kb-backups/rds-logical')
|
||||
expect(cards.find((card) => card.key === 'backup')?.value).toBe('—')
|
||||
expect(cards.find((card) => card.key === 'backup')?.note).toBe('备份根占用未知:遍历失败')
|
||||
expect(cards.find((card) => card.key === 'disk')?.value).toBe('—')
|
||||
expect(cards.find((card) => card.key === 'disk')?.note).toBe('本次上报不完整')
|
||||
})
|
||||
})
|
||||
|
||||
describe('storageAlerts', () => {
|
||||
it('judges disk and quota independently and counts pending rows', () => {
|
||||
const healthy = storageAlerts(inventory(), archive(), false)
|
||||
it('judges disk and backup quota independently and counts pending rows', () => {
|
||||
const healthy = storageAlerts(inventory())
|
||||
expect(healthy.map((row) => row.conclusion)).toEqual(['正常', '正常', '正常', '正常'])
|
||||
expect(pendingAlertCount(healthy)).toBe(0)
|
||||
|
||||
const nearQuota = storageAlerts(
|
||||
inventory(),
|
||||
archive({
|
||||
capacity: { ...archive().capacity, current_bytes: 95 * GIB, budget_bytes: 100 * GIB },
|
||||
}),
|
||||
false
|
||||
inventory({ usage: { ...inventory().usage, actual_bytes: 45 * GIB }, quota_bytes: 50 * GIB })
|
||||
)
|
||||
expect(nearQuota.find((row) => row.key === 'quota_low')?.tone).toBe('warn')
|
||||
expect(nearQuota.find((row) => row.key === 'both_low')?.conclusion).toBe('正常')
|
||||
@@ -288,9 +298,9 @@ describe('storageAlerts', () => {
|
||||
available_bytes: 0.01 * TB,
|
||||
used_bytes: 1.99 * TB,
|
||||
},
|
||||
}),
|
||||
archive({ capacity: { ...archive().capacity, current_bytes: 100 * GIB, budget_bytes: 100 * GIB } }),
|
||||
false
|
||||
usage: { ...inventory().usage, actual_bytes: 100 * GIB },
|
||||
quota_bytes: 100 * GIB,
|
||||
})
|
||||
)
|
||||
expect(tight.find((row) => row.key === 'disk_low')?.tone).toBe('bad')
|
||||
expect(tight.find((row) => row.key === 'both_low')?.conclusion).toBe('需处理')
|
||||
@@ -300,7 +310,7 @@ describe('storageAlerts', () => {
|
||||
})
|
||||
|
||||
it('never claims a conclusion without numbers', () => {
|
||||
const alerts = storageAlerts(unreported(), null, true)
|
||||
const alerts = storageAlerts(unreported())
|
||||
expect(alerts.every((row) => row.conclusion === '未知')).toBe(true)
|
||||
expect(alerts.find((row) => row.key === 'disk_low')?.value).toBe('主机未上报')
|
||||
expect(alerts.some((row) => row.value.includes('无法判定'))).toBe(false)
|
||||
|
||||
+43
-50
@@ -1,9 +1,7 @@
|
||||
// 「存储与备份」只读摘要的纯逻辑:数据源只有两个只读接口——
|
||||
// /api/v1/backup-schedule/inventory (宿主每 5 分钟上报的元数据快照)
|
||||
// /api/v1/library/storage (归档库自身的占用与配额)
|
||||
// 「存储与备份」只读摘要的纯逻辑:唯一数据源是宿主采集器快照
|
||||
// /api/v1/backup-schedule/inventory (批次、备份根占用、配额与文件系统容量)
|
||||
// 页面不提供任何写操作。读不到的量一律留空("主机未上报" / "—"),不用 0 冒充。
|
||||
import type { BackupInventory, BackupInventoryBatch } from './backupInventory'
|
||||
import type { LibraryStorage } from './librarySnapshots'
|
||||
|
||||
// 阈值(与 docs/STORAGE_BACKUP_READONLY_API.md 的「页面口径」一致):
|
||||
// 磁盘:可用空间 < 5% 红,< 10% 黄
|
||||
@@ -159,11 +157,7 @@ export interface SummaryCard {
|
||||
const lastReportNote = (inventory: BackupInventory): string =>
|
||||
`上次上报 ${formatWhen(inventory.metadata.collected_at) || UNKNOWN}`
|
||||
|
||||
export function summaryCards(
|
||||
inventory: BackupInventory | null,
|
||||
archive: LibraryStorage | null,
|
||||
archiveFailed: boolean
|
||||
): SummaryCard[] {
|
||||
export function summaryCards(inventory: BackupInventory | null): SummaryCard[] {
|
||||
const state = hostState(inventory)
|
||||
const facts = state === 'ready' || state === 'incomplete'
|
||||
const sizes = state === 'ready'
|
||||
@@ -181,7 +175,20 @@ export function summaryCards(
|
||||
const diskKnown = sizes && Boolean(capacity?.measured) && (capacity?.total_bytes ?? 0) > 0
|
||||
const availablePercent = diskKnown ? Math.round((capacity!.available_bytes / capacity!.total_bytes) * 100) : 0
|
||||
|
||||
const archiveKnown = Boolean(archive?.available) && !archiveFailed
|
||||
const usage = inventory?.usage
|
||||
const usageKnown =
|
||||
facts && Boolean(usage?.measured) && usage?.actual_bytes !== null && usage?.actual_bytes !== undefined
|
||||
const quotaBytes = inventory?.quota_bytes
|
||||
const quotaKnown = usageKnown && (quotaBytes ?? 0) > 0
|
||||
const backupNote = !pending
|
||||
? UNKNOWN
|
||||
: !facts
|
||||
? hostNote
|
||||
: usageKnown
|
||||
? quotaKnown
|
||||
? `配额 ${formatSize(quotaBytes)}`
|
||||
: inventory!.quota_error || '配额未上报'
|
||||
: usage?.error || '本次上报不完整'
|
||||
|
||||
return [
|
||||
{
|
||||
@@ -207,17 +214,11 @@ export function summaryCards(
|
||||
unknown: !recent,
|
||||
},
|
||||
{
|
||||
key: 'archive',
|
||||
label: '归档占用',
|
||||
value: archiveKnown ? formatSize(archive!.capacity.current_bytes) : UNKNOWN,
|
||||
note: archiveFailed
|
||||
? '归档读取失败'
|
||||
: !archive || !archive.available
|
||||
? '归档不可用'
|
||||
: archive.capacity.configured
|
||||
? `配额 ${formatSize(archive.capacity.budget_bytes)}`
|
||||
: '配额未设置',
|
||||
unknown: !archiveKnown,
|
||||
key: 'backup',
|
||||
label: '备份占用',
|
||||
value: usageKnown ? formatSize(usage!.actual_bytes) : facts ? UNKNOWN : hostValue,
|
||||
note: backupNote,
|
||||
unknown: !usageKnown,
|
||||
},
|
||||
{
|
||||
key: 'disk',
|
||||
@@ -244,23 +245,21 @@ export interface SummaryAlert {
|
||||
export interface StorageFacts {
|
||||
diskAvailableBytes: number | null
|
||||
diskTotalBytes: number | null
|
||||
archiveUsedBytes: number | null
|
||||
archiveBudgetBytes: number | null
|
||||
backupUsedBytes: number | null
|
||||
backupQuotaBytes: number | null
|
||||
}
|
||||
|
||||
export function storageFacts(
|
||||
inventory: BackupInventory | null,
|
||||
archive: LibraryStorage | null,
|
||||
archiveFailed: boolean
|
||||
): StorageFacts {
|
||||
export function storageFacts(inventory: BackupInventory | null): StorageFacts {
|
||||
const capacity = inventory?.capacity
|
||||
const diskKnown = hostState(inventory) === 'ready' && Boolean(capacity?.measured) && (capacity?.total_bytes ?? 0) > 0
|
||||
const archiveCapacity = archive?.available && !archiveFailed ? archive.capacity : null
|
||||
const usage = inventory?.usage
|
||||
const used = usage?.measured && usage.actual_bytes !== null ? usage.actual_bytes : null
|
||||
const quota = inventory?.quota_bytes ?? null
|
||||
return {
|
||||
diskAvailableBytes: diskKnown ? capacity!.available_bytes : null,
|
||||
diskTotalBytes: diskKnown ? capacity!.total_bytes : null,
|
||||
archiveUsedBytes: archiveCapacity ? archiveCapacity.current_bytes : null,
|
||||
archiveBudgetBytes: archiveCapacity?.configured ? archiveCapacity.budget_bytes : null,
|
||||
backupUsedBytes: used,
|
||||
backupQuotaBytes: quota !== null && quota > 0 ? quota : null,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -270,13 +269,9 @@ const tonePercent = (value: number, warn: number, critical: number): Tone =>
|
||||
const conclusionText = (tone: Tone): string =>
|
||||
tone === 'ok' ? '正常' : tone === 'warn' ? '注意' : tone === 'bad' ? '需处理' : UNKNOWN_STATE
|
||||
|
||||
export function storageAlerts(
|
||||
inventory: BackupInventory | null,
|
||||
archive: LibraryStorage | null,
|
||||
archiveFailed: boolean
|
||||
): SummaryAlert[] {
|
||||
export function storageAlerts(inventory: BackupInventory | null): SummaryAlert[] {
|
||||
const state = hostState(inventory)
|
||||
const facts = storageFacts(inventory, archive, archiveFailed)
|
||||
const facts = storageFacts(inventory)
|
||||
const diskKnown = facts.diskAvailableBytes !== null && (facts.diskTotalBytes ?? 0) > 0
|
||||
const availablePercent = diskKnown ? Math.round((facts.diskAvailableBytes! / facts.diskTotalBytes!) * 100) : 0
|
||||
const diskTone: Tone = diskKnown
|
||||
@@ -287,16 +282,16 @@ export function storageAlerts(
|
||||
: 'ok'
|
||||
: 'none'
|
||||
|
||||
const quotaKnown = facts.archiveUsedBytes !== null && (facts.archiveBudgetBytes ?? 0) > 0
|
||||
const usedPercent = quotaKnown ? Math.round((facts.archiveUsedBytes! / facts.archiveBudgetBytes!) * 100) : 0
|
||||
const quotaKnown = facts.backupUsedBytes !== null && (facts.backupQuotaBytes ?? 0) > 0
|
||||
const usedPercent = quotaKnown ? Math.round((facts.backupUsedBytes! / facts.backupQuotaBytes!) * 100) : 0
|
||||
const quotaTone: Tone = quotaKnown
|
||||
? tonePercent(usedPercent, QUOTA_WARN_USED_PERCENT, QUOTA_CRITICAL_USED_PERCENT)
|
||||
: 'none'
|
||||
const bothTone: Tone =
|
||||
diskTone === 'none' || quotaTone === 'none' ? 'none' : diskTone !== 'ok' && quotaTone !== 'ok' ? 'bad' : 'ok'
|
||||
const overPhysical: Tone =
|
||||
diskKnown && facts.archiveBudgetBytes !== null
|
||||
? facts.archiveBudgetBytes > facts.diskAvailableBytes!
|
||||
diskKnown && facts.backupQuotaBytes !== null
|
||||
? facts.backupQuotaBytes > facts.diskAvailableBytes!
|
||||
? 'bad'
|
||||
: 'ok'
|
||||
: 'none'
|
||||
@@ -315,12 +310,10 @@ export function storageAlerts(
|
||||
key: 'quota_low',
|
||||
label: '配额不足',
|
||||
value: quotaKnown
|
||||
? `${formatSize(facts.archiveUsedBytes)} / ${formatSize(facts.archiveBudgetBytes)}(${usedPercent}%)`
|
||||
: archiveFailed
|
||||
? UNKNOWN
|
||||
: archive?.available
|
||||
? '配额未设置'
|
||||
: UNKNOWN,
|
||||
? `${formatSize(facts.backupUsedBytes)} / ${formatSize(facts.backupQuotaBytes)}(${usedPercent}%)`
|
||||
: inventory?.quota_error
|
||||
? '配额未上报'
|
||||
: UNKNOWN,
|
||||
tone: quotaTone,
|
||||
conclusion: quotaKnown ? conclusionText(quotaTone) : UNKNOWN_STATE,
|
||||
},
|
||||
@@ -335,11 +328,11 @@ export function storageAlerts(
|
||||
key: 'quota_over_physical',
|
||||
label: '配额超出物理空闲',
|
||||
value:
|
||||
diskKnown && facts.archiveBudgetBytes !== null
|
||||
? `配额 ${formatSize(facts.archiveBudgetBytes)} · 可用 ${formatSize(facts.diskAvailableBytes)}`
|
||||
diskKnown && facts.backupQuotaBytes !== null
|
||||
? `配额 ${formatSize(facts.backupQuotaBytes)} · 可用 ${formatSize(facts.diskAvailableBytes)}`
|
||||
: UNKNOWN,
|
||||
tone: overPhysical,
|
||||
conclusion: diskKnown && facts.archiveBudgetBytes !== null ? conclusionText(overPhysical) : UNKNOWN_STATE,
|
||||
conclusion: diskKnown && facts.backupQuotaBytes !== null ? conclusionText(overPhysical) : UNKNOWN_STATE,
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user