- 采集器上报 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:
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())
|
||||
Reference in New Issue
Block a user