feat(backup): 配额改按备份根占用并在超限时清理最旧批次
build / build (push) Successful in 3m22s

- 采集器上报 backup_root/usage/quota(加性字段),API 用 BACKUP_HOST_ROOT 校验并分别降级占用/配额
- 页面配额行改为备份占用 X / 配额 50 GB,4 条告警改用备份口径,解除本页归档依赖
- logical-backup.sh 预检按字节清理(保留最新、空间不足零删除),dump 后复查保护新批次
- backup_layout 写入 KB_BACKUP_QUOTA_BYTES;--show 输出根占用;新增 prune 工具与自检
This commit is contained in:
Zhero & Rin
2026-11-25 22:45:35 +08:00
committed by 姚章浩
parent 65476750b0
commit 144b49cb53
20 changed files with 1124 additions and 178 deletions
+14
View File
@@ -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
+163 -1
View File
@@ -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__":
+4 -1
View File
@@ -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
+57 -3
View File
@@ -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
+356
View File
@@ -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())