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