Merge pull request #38 from hifox-agent/rin/CYWL-28
build / build (push) Successful in 3m57s
build / build (push) Successful in 3m57s
This commit was merged in pull request #38.
This commit is contained in:
@@ -1,5 +1,21 @@
|
||||
# Changelog
|
||||
|
||||
## 开发快照 0.1.424(存储与备份:删批次前预检,失败零删除)
|
||||
|
||||
### Fixed
|
||||
|
||||
- **配额清理会把旧批次删一半再失败**:`shutil.rmtree` 先删子项、最后删目录,批次根只读时
|
||||
失败发生在内容已清空之后,调用方只看到非 0 退出却打印「旧备份未被删除」。现在删除分三段:
|
||||
逐目录可写性检查 + 同父目录改名探针(不动内容)→ 全部改名成 `.prune-<pid>-<戳>` 隔离
|
||||
(原子、不进批次候选)→ 才真删。任一预检或改名失败整体回滚、**零删除**(新退出码 `5`);
|
||||
真删阶段才失败时报隔离路径(`rc=4`),`logical-backup.sh` 按 `rc` 区分提示,不再误报。
|
||||
|
||||
### Changed
|
||||
|
||||
- 轮转(`KEEP_DAILY`/`KEEP_MONTHS`)改由 `scripts/prune_backup_batches.py --rotate` 实现,
|
||||
与配额清理共用同一套预检/隔离/回滚,删掉 `logical-backup.sh` 里的第二份内联 `rmtree`。
|
||||
self-test 增加预检零删除、改名失败回滚、只读批次根、轮转与遗留隔离目录用例。
|
||||
|
||||
## 开发快照 0.1.423(存储与备份:配额改按备份根占用)
|
||||
|
||||
### Fixed
|
||||
|
||||
@@ -104,6 +104,15 @@ python3 scripts/restore_drill.py --snapshot-dir $KB_BACKUP_ROOT/target-kb-snapsh
|
||||
- dump 后复查:保护本次新批次,允许删旧(含上一份);仍超限则保留新备份并告警退出。
|
||||
- 只删 `rds-logical/<UTC>` 完整批次(含常规 `MANIFEST.json`、非符号链接);
|
||||
`es-snapshots`/`target-kb-snapshots`/`logs` 与 `*.incomplete` 永不删。
|
||||
- **删除分三段(预检 → 改名隔离 → 真删)**:`rmtree` 会先删内容、最后删目录,父目录只读时
|
||||
失败发生在内容已清空之后,调用方只看得到非 0 退出。所以先逐目录检查可写性并对每个计划内
|
||||
批次做同父目录改名探针(只验证父目录可写,不动内容),再全部改名成 `.prune-<pid>-<戳>`
|
||||
(原子、不进批次候选),最后才真删。任一预检失败或改名失败 ⇒ **零删除**;真删阶段才失败时
|
||||
报隔离路径(`mv` 回原名即可恢复剩余内容)。
|
||||
- 轮转(`KEEP_DAILY`/`KEEP_MONTHS`)与配额清理走同一份实现(`--rotate`),不再有第二份内联
|
||||
`rmtree`。
|
||||
- 退出码:`0` 已满足(可能删过)、`2` du/路径错误、`3` 空间仍不够、`4` 真删阶段失败、
|
||||
`5` 预检未通过(零删除)。
|
||||
- 现场对账:`du -sB1 -- $KB_BACKUP_ROOT` 与页面「备份占用」应一致(≤1%);
|
||||
`bash scripts/install_backup_schedule.sh --show` 也会打印根占用/配额。
|
||||
- 凭据:容器内只读挂载 `secrets/backup-host/{ssh_config,id_ed25519,known_hosts}`(0600),
|
||||
|
||||
+16
-22
@@ -142,7 +142,11 @@ echo "配额 : $QUOTA_BYTES 字节(备份根 $QUOTA_ROOT)"
|
||||
# 真正删除旧批次放在凭据/库列表校验之后:连不上库时不应该先清历史备份。
|
||||
if run_quota_prune "预检" --estimate latest --keep-latest --apply; then :; else
|
||||
rc=$?
|
||||
echo "配额预检未通过(rc=$rc):本次备份取消,旧备份未被删除" >&2
|
||||
# rc=4 说明批次已改名隔离、真删阶段才失败,内容可能被部分删除 —— 不能再说「旧备份未被删除」。
|
||||
case "$rc" in
|
||||
4) echo "配额预检的删除阶段失败(rc=4):已隔离的批次可能已被部分删除(见上面的隔离路径),本次备份取消" >&2 ;;
|
||||
*) echo "配额预检未通过(rc=$rc):本次备份取消,旧备份未被删除" >&2 ;;
|
||||
esac
|
||||
exit "$rc"
|
||||
fi
|
||||
|
||||
@@ -241,31 +245,21 @@ docker run --rm -v "$PWD:/backup" postgres:17.9-alpine \
|
||||
- 这份备份**不能替代按时间点恢复(PITR)**:它只能回到"备份那一刻"。
|
||||
MD
|
||||
|
||||
# 轮转:保留最近 KEEP_DAILY 份,另在最近 KEEP_MONTHS 个自然月各留一份
|
||||
python3 - "$BACKUP_ROOT" "$KEEP_DAILY" "$KEEP_MONTHS" <<'PY'
|
||||
import pathlib, re, shutil, sys
|
||||
root = pathlib.Path(sys.argv[1]); keep_daily = int(sys.argv[2]); keep_months = int(sys.argv[3])
|
||||
stamps = sorted([p for p in root.iterdir() if p.is_dir() and re.fullmatch(r"\d{8}T\d{6}Z", p.name)], reverse=True)
|
||||
keep = {p.name for p in stamps[:keep_daily]}
|
||||
months = []
|
||||
for path in stamps:
|
||||
month = path.name[:6]
|
||||
if month not in months:
|
||||
months.append(month)
|
||||
keep.add(path.name)
|
||||
if len(months) >= keep_months:
|
||||
break
|
||||
for path in stamps:
|
||||
if path.name not in keep:
|
||||
shutil.rmtree(path)
|
||||
print("rotated out:", path.name)
|
||||
print("kept:", len([p for p in stamps if p.name in keep]))
|
||||
PY
|
||||
# 轮转:保留最近 KEEP_DAILY 份,另在最近 KEEP_MONTHS 个自然月各留一份。
|
||||
# 与配额清理共用同一份实现:删除前的 rename 预检、失败零删除回滚、只认完整批次,
|
||||
# 避免这里的内联 rmtree 又变成「先清空内容、再删目录失败」的第二条路径。
|
||||
python3 "$PRUNE_TOOL" \
|
||||
--backup-root "$QUOTA_ROOT" \
|
||||
--batch-root "$BACKUP_ROOT" \
|
||||
--rotate --keep-daily "$KEEP_DAILY" --keep-months "$KEEP_MONTHS" --apply
|
||||
|
||||
# dump 后按实际占用复查:保护本次新批次,旧批次可删;仍超限则保留数据并告警。
|
||||
if run_quota_prune "dump 后复查" --estimate none --protect "$STAMP" --apply; then :; else
|
||||
rc=$?
|
||||
echo "本次备份已完成,但配额仍超出(rc=$rc):新批次保留,请扩容或人工清理" >&2
|
||||
case "$rc" in
|
||||
4) echo "本次备份已完成,但删除阶段失败(rc=4):见上面的隔离路径;新批次保留" >&2 ;;
|
||||
*) echo "本次备份已完成,但配额仍超出(rc=$rc):新批次保留,请扩容或人工清理" >&2 ;;
|
||||
esac
|
||||
exit "$rc"
|
||||
fi
|
||||
|
||||
|
||||
+352
-25
@@ -17,8 +17,14 @@ logical-backup.sh 的内联 Python 只能靠跑 docker/psql 才能验证。
|
||||
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 删除失败(已删的已生效,报错退出)。
|
||||
4 删除阶段失败(已隔离的批次可能被部分删除,报错退出并给出隔离路径);
|
||||
5 删除前预检未通过,**零删除**。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -33,12 +39,22 @@ 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
|
||||
@@ -136,6 +152,171 @@ def resolve_estimate(value: str, candidates_oldest_first: list[Candidate]) -> in
|
||||
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,
|
||||
@@ -168,28 +349,21 @@ def prune(
|
||||
"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
|
||||
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["deleted"] = delete_batches(batch_root, planned)
|
||||
result["applied"] = True
|
||||
result["usage_after_bytes"] = measure_bytes(backup_root)
|
||||
return result
|
||||
|
||||
|
||||
def _self_test() -> None:
|
||||
def _self_test_quota() -> None:
|
||||
base = tempfile.mkdtemp(prefix="backup-quota-test-")
|
||||
try:
|
||||
root = os.path.join(base, "kb-backups")
|
||||
@@ -301,6 +475,128 @@ def _self_test() -> None:
|
||||
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)")
|
||||
@@ -310,6 +606,9 @@ def main(argv: list[str] | None = None) -> int:
|
||||
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)
|
||||
@@ -319,17 +618,32 @@ def main(argv: list[str] | None = None) -> int:
|
||||
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,
|
||||
)
|
||||
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
|
||||
@@ -337,6 +651,13 @@ def main(argv: list[str] | None = None) -> int:
|
||||
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']}"
|
||||
@@ -346,8 +667,14 @@ def main(argv: list[str] | None = None) -> int:
|
||||
if result["insufficient"]:
|
||||
print("空间仍不够:未删除任何批次", file=sys.stderr)
|
||||
elif result["applied"]:
|
||||
print(f"已删除 {len(result['plan'])} 个批次,占用 {result['usage_after_bytes']}")
|
||||
if result["insufficient"]:
|
||||
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
|
||||
|
||||
|
||||
Reference in New Issue
Block a user