6539a6b77c
build / build (push) Successful in 3m10s
为什么:批次根只读时,shutil.rmtree 先删完子项、最后删目录才失败,调用方只看得到 rc≠0, 旧批次内容已经被清空一半,而 logical-backup.sh 还打印「旧备份未被删除」。 改法: - prune_backup_batches.py 的删除拆成三段:逐目录可写性检查 + 同父目录改名探针(不动内容) → 全部改名成 .prune-<pid>-<戳> 隔离(原子、不进批次候选)→ 才真删。预检或改名失败整体 回滚、零删除(新退出码 5);真删阶段才失败报隔离路径(rc=4),不再谎称旧备份完好。 - logical-backup.sh 的轮转改用 --rotate,与配额清理共用同一份预检/隔离/回滚,删除第二份内联 rmtree;按 rc 区分提示文案。 验证: - --self-test 新增预检零删除、改名失败回滚、只读批次根、轮转、遗留隔离目录用例,全部通过; go test ./internal/backuphost/ 通过。 - 用 QA 夹具(8 批 + 1 个 .incomplete,批次根 0555,quota=49140352)对拍:旧脚本把 20261118T193001Z 清成 0 文件、占用 119140352→105500672 后 rc=2;新脚本 rc=5、 8 个 MANIFEST 全在、占用仍 119140352。 - 子目录只读(批次根可写)同样 rc=5 零删除;可写树正常删两批、无隔离残留。
683 lines
28 KiB
Python
Executable File
683 lines
28 KiB
Python
Executable File
#!/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
|
||
|
||
删除为什么要分「预检 → 同父目录改名隔离 → 真删」三段:`shutil.rmtree` 先删子项、最后删
|
||
目录,父目录只读时失败发生在内容**已经清空之后**,调用方只看得到 rc≠0,旧备份却已经毁了
|
||
一半。rename 只要求父目录可写,能在删掉任何一个字节之前暴露这类问题;改名是原子的,任一
|
||
批次改名失败就把已挪动的批次全部挪回去,保证「失败 ⇒ 零删除」。
|
||
|
||
退出码:0 已满足配额(可能删了旧批次);2 du/路径错误,未删除;3 空间仍不够,未删除;
|
||
4 删除阶段失败(已隔离的批次可能被部分删除,报错退出并给出隔离路径);
|
||
5 删除前预检未通过,**零删除**。
|
||
"""
|
||
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$")
|
||
# 隔离名不以 UTC 戳开头,因此不会被 candidates() 认成批次;同父目录下改名是原子操作。
|
||
QUARANTINE_PREFIX = ".prune-"
|
||
|
||
|
||
class QuotaError(Exception):
|
||
pass
|
||
|
||
|
||
class PrecheckRefused(QuotaError):
|
||
"""删除前预检未通过:一个字节都没删。"""
|
||
|
||
|
||
class DeleteFailed(QuotaError):
|
||
"""配额已提交(批次已改名隔离),但真删阶段失败:可能已有内容被删。"""
|
||
|
||
|
||
@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 _tree_problems(path: str) -> list[str]:
|
||
"""列出会让 `rmtree` 中途失败的目录(只读、不可执行、挂载点)。
|
||
|
||
删一个子项要求它的**父目录**可写可执行,而不是文件本身;所以只看目录。挂载点要单独拒:
|
||
rmtree 会顺着删到另一个文件系统里去。
|
||
"""
|
||
problems: list[str] = []
|
||
if os.path.ismount(path):
|
||
return [f"{path} 是挂载点,拒绝删除"]
|
||
if not os.access(path, os.W_OK | os.X_OK):
|
||
return [f"{path} 不可写(rmtree 会先删完内容再删目录失败)"]
|
||
for current, _dirs, _files in os.walk(path, onerror=lambda err: problems.append(str(err))):
|
||
if os.path.ismount(current):
|
||
problems.append(f"{current} 是挂载点,拒绝删除")
|
||
elif not os.access(current, os.W_OK | os.X_OK):
|
||
problems.append(f"{current} 不可写")
|
||
return problems
|
||
|
||
|
||
def _rename_probe(path: str) -> None:
|
||
"""在同一个父目录里把批次改名再改回:验证「父目录可写」而不动任何内容。"""
|
||
batch_root = os.path.dirname(path)
|
||
probe = os.path.join(batch_root, f"{QUARANTINE_PREFIX}probe-{os.getpid()}-{os.path.basename(path)}")
|
||
os.rename(path, probe)
|
||
try:
|
||
os.rename(probe, path)
|
||
except OSError as error:
|
||
raise QuotaError(
|
||
f"批次 {os.path.basename(path)} 已改名为 {probe} 且改回失败(内容未删);"
|
||
f"请人工 mv 回原名:{error}"
|
||
) from error
|
||
|
||
|
||
def delete_batches(
|
||
batch_root: str,
|
||
planned: list[Candidate],
|
||
tree_check=_tree_problems,
|
||
probe=_rename_probe,
|
||
rename=os.rename,
|
||
) -> list[str]:
|
||
"""预检通过才删;返回真正删掉的批次名。
|
||
|
||
预检覆盖两类失败:批次根不可写(改名探针)与批次内部有不可删目录(逐目录检查)。
|
||
提交点是「全部改名成功」——之后才真删,所以中途失败不会出现「一半删掉、一半还在」
|
||
的可见状态;改名失败则整体回滚,零删除。
|
||
"""
|
||
if not planned:
|
||
return []
|
||
problems: list[str] = []
|
||
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}")
|
||
problems.extend(tree_check(target))
|
||
if not problems:
|
||
for item in planned:
|
||
try:
|
||
probe(item.path)
|
||
except OSError as error:
|
||
problems.append(
|
||
f"{item.path}: 无法在批次根内改名(父目录不可写?未删除任何内容):"
|
||
f"{error.strerror or error}"
|
||
)
|
||
break
|
||
if problems:
|
||
raise PrecheckRefused("删除前预检未通过,未删除任何批次:" + ";".join(problems))
|
||
|
||
quarantined: list[tuple[Candidate, str]] = []
|
||
try:
|
||
for item in planned:
|
||
target = os.path.join(batch_root, f"{QUARANTINE_PREFIX}{os.getpid()}-{item.name}")
|
||
if os.path.lexists(target):
|
||
raise OSError(f"隔离路径已存在:{target}")
|
||
rename(item.path, target)
|
||
quarantined.append((item, target))
|
||
except OSError as error:
|
||
for item, target in reversed(quarantined):
|
||
try:
|
||
rename(target, item.path)
|
||
except OSError as undo_error:
|
||
raise DeleteFailed(
|
||
f"回滚失败:批次 {item.name} 停在 {target}(内容未删);请人工 mv 回原名:{undo_error}"
|
||
) from error
|
||
raise PrecheckRefused(
|
||
f"隔离改名失败({error}),已把 {[item.name for item, _ in quarantined]} 改回原名,未删除任何批次"
|
||
) from error
|
||
|
||
deleted: list[str] = []
|
||
failures: list[str] = []
|
||
for item, target in quarantined:
|
||
try:
|
||
shutil.rmtree(target)
|
||
except OSError as error:
|
||
failures.append(f"{item.name}(隔离在 {target},内容可能已被部分删除):{error}")
|
||
continue
|
||
deleted.append(item.name)
|
||
if failures:
|
||
raise DeleteFailed("删除阶段失败:" + ";".join(failures))
|
||
return deleted
|
||
|
||
|
||
def plan_rotation(
|
||
candidates_oldest_first: list[Candidate], keep_daily: int, keep_months: int
|
||
) -> list[Candidate]:
|
||
"""保留最近 keep_daily 份 + 最近 keep_months 个自然月各一份,其余待删。"""
|
||
newest_first = list(reversed(candidates_oldest_first))
|
||
keep = {item.name for item in newest_first[: max(keep_daily, 0)]}
|
||
months: list[str] = []
|
||
for item in newest_first:
|
||
month = item.name[:6]
|
||
if month not in months:
|
||
months.append(month)
|
||
keep.add(item.name)
|
||
if len(months) >= keep_months:
|
||
break
|
||
return [item for item in candidates_oldest_first if item.name not in keep]
|
||
|
||
|
||
def stale_quarantine(batch_root: str) -> list[str]:
|
||
"""上次删到一半留下的隔离目录:不认成批次,但要报出来让人决定恢复还是清掉。"""
|
||
try:
|
||
entries = list(os.scandir(batch_root))
|
||
except OSError:
|
||
return []
|
||
return sorted(
|
||
entry.name
|
||
for entry in entries
|
||
if entry.name.startswith(QUARANTINE_PREFIX) and entry.is_dir(follow_symlinks=False)
|
||
)
|
||
|
||
|
||
def rotate(
|
||
backup_root: str,
|
||
batch_root: str,
|
||
keep_daily: int,
|
||
keep_months: int,
|
||
apply: bool,
|
||
measure_bytes=measure,
|
||
) -> dict:
|
||
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)
|
||
planned = plan_rotation(found, keep_daily, keep_months)
|
||
result = {
|
||
"mode": "rotate",
|
||
"backup_root": backup_root,
|
||
"batch_root": batch_root,
|
||
"keep_daily": keep_daily,
|
||
"keep_months": keep_months,
|
||
"kept": len(found) - len(planned),
|
||
"plan": [item.name for item in planned],
|
||
"deleted": [],
|
||
"stale_quarantine": stale_quarantine(batch_root),
|
||
"applied": False,
|
||
}
|
||
if apply:
|
||
result["deleted"] = delete_batches(batch_root, planned)
|
||
result["applied"] = True
|
||
return result
|
||
|
||
|
||
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,
|
||
"deleted": [],
|
||
"stale_quarantine": stale_quarantine(batch_root),
|
||
"applied": False,
|
||
}
|
||
if insufficient:
|
||
return result
|
||
if not apply:
|
||
return result
|
||
result["deleted"] = delete_batches(batch_root, planned)
|
||
result["applied"] = True
|
||
result["usage_after_bytes"] = measure_bytes(backup_root)
|
||
return result
|
||
|
||
|
||
def _self_test_quota() -> 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 _self_test_delete_safety() -> None:
|
||
"""删除安全网:预检拒绝零删除、改名失败整体回滚、轮转、隔离目录不进候选。"""
|
||
import contextlib
|
||
import io
|
||
|
||
base = tempfile.mkdtemp(prefix="backup-quota-delete-test-")
|
||
try:
|
||
root = os.path.join(base, "kb-backups")
|
||
batch_root = os.path.join(root, "rds-logical")
|
||
os.makedirs(batch_root)
|
||
|
||
def make_batch(stamp: str, kib: int) -> str:
|
||
path = os.path.join(batch_root, stamp)
|
||
os.makedirs(os.path.join(path, "weknora.dir"))
|
||
with open(os.path.join(path, "weknora.dir", "180000.dat.gz"), "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 = ["20261201T030000Z", "20261215T030000Z", "20270101T030000Z", "20270115T030000Z"]
|
||
paths = [make_batch(stamp, 128) for stamp in stamps]
|
||
found = candidates(batch_root)
|
||
|
||
def sizes() -> dict[str, int]:
|
||
return {path: measure(path) for path in paths}
|
||
|
||
before = sizes()
|
||
# 1) 预检报告问题时一个都不删(旧实现会先 rmtree 掉第一批再失败)。
|
||
for inject in ({"tree_check": lambda _path: ["注入:目录不可写"]},
|
||
{"probe": _refuse_probe}):
|
||
try:
|
||
delete_batches(batch_root, found[:2], **inject)
|
||
except PrecheckRefused:
|
||
pass
|
||
else:
|
||
raise AssertionError("预检拒绝时不得删除")
|
||
assert sizes() == before, (inject, sizes())
|
||
assert all(os.path.exists(path) for path in paths)
|
||
|
||
# 2) 改名提交阶段失败:已挪动的批次必须改回原名,零删除。
|
||
calls = {"n": 0}
|
||
real_rename = os.rename
|
||
|
||
def flaky_rename(src, dst):
|
||
calls["n"] += 1
|
||
if calls["n"] == 2:
|
||
raise OSError("注入:改名失败")
|
||
return real_rename(src, dst)
|
||
|
||
try:
|
||
delete_batches(batch_root, found[:2], rename=flaky_rename)
|
||
except PrecheckRefused:
|
||
pass
|
||
else:
|
||
raise AssertionError("改名失败必须整体回滚")
|
||
assert sorted(os.listdir(batch_root)) == stamps, os.listdir(batch_root)
|
||
assert sizes() == before
|
||
|
||
# 3) 真删只在预检通过后发生,并且只删计划内批次。
|
||
deleted = delete_batches(batch_root, found[:2])
|
||
assert deleted == [stamps[0], stamps[1]], deleted
|
||
assert sorted(os.listdir(batch_root)) == stamps[2:], os.listdir(batch_root)
|
||
assert os.path.isdir(paths[2]) and os.path.isdir(paths[3])
|
||
|
||
# 4) 只读批次根(root 下 os.access 恒为真,跳过)。
|
||
if os.geteuid() != 0:
|
||
quota = measure(root) - measure(paths[2])
|
||
os.chmod(batch_root, 0o555)
|
||
try:
|
||
buffer = io.StringIO()
|
||
with contextlib.redirect_stderr(buffer):
|
||
code = main([
|
||
"--backup-root", root, "--batch-root", batch_root,
|
||
"--quota-bytes", str(quota), "--estimate", "none", "--apply",
|
||
])
|
||
assert code == 5, (code, buffer.getvalue())
|
||
assert "预检未通过" in buffer.getvalue(), buffer.getvalue()
|
||
finally:
|
||
os.chmod(batch_root, 0o755)
|
||
assert sorted(os.listdir(batch_root)) == stamps[2:], os.listdir(batch_root)
|
||
assert measure(paths[2]) > 0 and measure(paths[3]) > 0
|
||
|
||
# 5) 轮转:保留最近 keep_daily 份 + 最近 keep_months 个自然月各一份。
|
||
for stamp in ["20270201T030000Z", "20270215T030000Z"]:
|
||
make_batch(stamp, 128)
|
||
rotated = rotate(root, batch_root, keep_daily=2, keep_months=2, apply=False)
|
||
assert rotated["plan"] == ["20270101T030000Z"], rotated
|
||
assert rotated["kept"] == 3, rotated
|
||
rotated = rotate(root, batch_root, keep_daily=2, keep_months=2, apply=True)
|
||
assert rotated["deleted"] == ["20270101T030000Z"], rotated
|
||
assert sorted(os.listdir(batch_root)) == ["20270115T030000Z", "20270201T030000Z", "20270215T030000Z"], os.listdir(batch_root)
|
||
|
||
# 6) 上次失败留下的隔离目录:不算批次、不被当垃圾清掉、要报出来。
|
||
stale = os.path.join(batch_root, f"{QUARANTINE_PREFIX}999-20270101T030000Z")
|
||
os.makedirs(os.path.join(stale, "weknora.dir"))
|
||
with open(os.path.join(stale, "MANIFEST.json"), "w", encoding="utf-8") as handle:
|
||
handle.write("{}")
|
||
assert [item.name for item in candidates(batch_root)] == [
|
||
"20270115T030000Z", "20270201T030000Z", "20270215T030000Z"
|
||
]
|
||
result = rotate(root, batch_root, keep_daily=2, keep_months=2, apply=True)
|
||
assert result["stale_quarantine"] == [os.path.basename(stale)], result
|
||
assert os.path.isdir(stale), "隔离目录不能自动删"
|
||
|
||
print("prune delete-safety self-test ok")
|
||
finally:
|
||
for current, dirs, _files in os.walk(base):
|
||
for name in dirs:
|
||
os.chmod(os.path.join(current, name), 0o755)
|
||
shutil.rmtree(base, ignore_errors=True)
|
||
|
||
|
||
def _refuse_probe(_path: str) -> None:
|
||
raise OSError("注入:改名预检失败")
|
||
|
||
|
||
def _self_test() -> None:
|
||
_self_test_quota()
|
||
_self_test_delete_safety()
|
||
|
||
|
||
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("--rotate", action="store_true", help="按份数/月份轮转(忽略配额)")
|
||
parser.add_argument("--keep-daily", type=int, default=7, help="轮转:保留最近几份")
|
||
parser.add_argument("--keep-months", type=int, default=3, 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")
|
||
if args.rotate:
|
||
result = rotate(
|
||
backup_root,
|
||
batch_root,
|
||
args.keep_daily,
|
||
args.keep_months,
|
||
args.apply,
|
||
)
|
||
else:
|
||
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 PrecheckRefused as error:
|
||
print(f"quota prune refused: {error}", file=sys.stderr)
|
||
return 5
|
||
except DeleteFailed as error:
|
||
print(f"quota prune failed: {error}", file=sys.stderr)
|
||
return 4
|
||
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))
|
||
elif args.rotate:
|
||
print(f"保留 {result['kept']} 份(每日 {result['keep_daily']} / 每月 {result['keep_months']})")
|
||
if result["applied"]:
|
||
for name in result["deleted"]:
|
||
print("rotated out:", name)
|
||
else:
|
||
print("待删:" + ("、".join(result["plan"]) if result["plan"] else "无"))
|
||
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['deleted'])} 个批次,占用 {result['usage_after_bytes']}")
|
||
if result.get("stale_quarantine"):
|
||
print(
|
||
"注意:发现上次删除失败留下的隔离目录(内容可能不完整,未计入批次):"
|
||
+ "、".join(result["stale_quarantine"]),
|
||
file=sys.stderr,
|
||
)
|
||
if result.get("insufficient"):
|
||
return 3
|
||
return 0
|
||
|
||
|
||
if __name__ == "__main__":
|
||
raise SystemExit(main()) |