#!/usr/bin/env python3 """备份目录的**单次宿主元数据采集器**(只读)。 为什么不在 API 里遍历:备份目录通常是 root:root 0700,API 容器用户没有进入权限; 容器里再 df/du 也证明不了宿主的盘。这个脚本在备份主机上由有读权限的宿主进程 (root 或备份所有者)运行,只做 stat/du 和读 MANIFEST.json,产出原子快照 JSON; API 只读快照,不接触备份目录,也不借用 SSH 或容器特权。 不读取任何数据库内容文件:只对目录项 lstat、统计 st_size/st_blocks,并读 MANIFEST.json(元数据)。输出用同目录临时文件 + fsync + os.replace 原子替换。 用法(宿主): python3 collect_backup_metadata.py \ --root /srv/kb-backups/rds-logical \ --output /var/lib/knowledge-governance/backup-metadata/metadata.json \ --source weknora-test:/srv/kb-backups/rds-logical 退出码:0 完整;2 已写快照但采集不完整/有错误;1 连快照都没写成。 """ from __future__ import annotations import argparse import datetime as dt import errno import json import os import re import socket import stat import sys import tempfile import uuid from typing import Any, Callable, Iterable SCHEMA_VERSION = 1 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})" return f"{type(error).__name__}: {error}" def _append_error(errors: list[str], text: str) -> None: if len(errors) < MAX_ERRORS and text not in errors: errors.append(text) def _unescape_mount(text: str) -> str: return re.sub(r"\\([0-7]{3})", lambda m: chr(int(m.group(1), 8)), text) def mount_info(root: str) -> dict[str, Any]: """从 /proc/self/mountinfo 找覆盖 root 的最长挂载点(只读文件,不碰备份内容)。""" best: dict[str, Any] | None = None try: with open("/proc/self/mountinfo", "r", encoding="utf-8", errors="replace") as handle: for line in handle: before, sep, after = line.partition(" - ") if not sep: continue fields = before.split() tail = after.split() if len(fields) < 6 or len(tail) < 3: continue mount_point = _unescape_mount(fields[4]) if root == mount_point or root.startswith(mount_point.rstrip("/") + "/"): if best is None or len(mount_point) > len(best["mount_point"]): best = { "mount_point": mount_point, "mount_source": _unescape_mount(tail[1]), "fs_type": tail[0], "read_only": "ro" in fields[5].split(","), } except OSError: return {} return best or {} def capacity(root: str) -> tuple[dict[str, Any], list[str]]: errors: list[str] = [] info = mount_info(root) try: stats = os.statvfs(root) block = stats.f_frsize or stats.f_bsize info.update( { "total_bytes": stats.f_blocks * block, "free_bytes": stats.f_bfree * block, "available_bytes": stats.f_bavail * block, } ) if "read_only" not in info: flags = getattr(stats, "f_flag", 0) info["read_only"] = bool(flags & getattr(os, "ST_RDONLY", 1)) except OSError as error: _append_error(errors, "statvfs: " + _error_text(error)) return info, errors def _read_manifest(path: str) -> tuple[str, str, dict[str, Any]]: # MANIFEST 只接受目录内的常规文件:lstat 拒绝符号链接,open 再带 O_NOFOLLOW, # 防止采集器被一个指向别处的清单带跑(只读,也不会跟随到归档内容)。 try: info = os.lstat(path) except FileNotFoundError: return "missing", "", {} except OSError as error: return "invalid", "清单不可读:" + _error_text(error), {} if stat.S_ISLNK(info.st_mode) or not stat.S_ISREG(info.st_mode): return "invalid", "清单不是目录内的常规文件(拒绝符号链接)", {} if info.st_size > MAX_MANIFEST_BYTES: return "invalid", f"清单超过 {MAX_MANIFEST_BYTES} 字节读取上限", {} flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) try: descriptor = os.open(path, flags) except OSError as error: return "invalid", "清单不可读:" + _error_text(error), {} try: with os.fdopen(descriptor, "rb") as handle: opened = os.fstat(handle.fileno()) if not stat.S_ISREG(opened.st_mode): return "invalid", "清单在打开后不是常规文件", {} raw = handle.read(MAX_MANIFEST_BYTES + 1) except OSError as error: return "invalid", "清单不可读:" + _error_text(error), {} if len(raw) > MAX_MANIFEST_BYTES: return "invalid", f"清单超过 {MAX_MANIFEST_BYTES} 字节读取上限", {} try: value = json.loads(raw.decode("utf-8")) except (UnicodeDecodeError, json.JSONDecodeError) as error: return "invalid", "清单无法解析:" + str(error), {} if not isinstance(value, dict): return "invalid", "清单不是对象", {} return "ok", "", value def measure_tree(path: str, scan: Callable[[str], Iterable[Any]] = os.scandir, max_files: int = 500_000) -> dict[str, Any]: """只 stat 目录项;口径与 `du -sB1` 一致。 - 目录自身也计入(st_size + st_blocks),不只求和文件; - 子树完整遍历,任何 lstat/scandir 错误置 complete=false; - 常规文件硬链接按 (dev, ino) 只算一次(单库/整批各自独立去重); - 符号链接、设备等非目录/非普通文件不跟随、不计入(与参考 du 口径一致)。 scan 可注入,self-test 用它模拟 PermissionError;生产默认 os.scandir。 """ apparent = actual = files = dirs = 0 seen: set[tuple[int, int]] = set() errors: list[str] = [] complete = True stack = [path] while stack: current = stack.pop() try: info = os.lstat(current) except OSError as error: complete = False _append_error(errors, "stat 失败:" + _error_text(error)) continue if stat.S_ISDIR(info.st_mode): dirs += 1 apparent += int(info.st_size) actual += int(getattr(info, "st_blocks", 0)) * 512 try: entries = list(scan(current)) except OSError as error: complete = False _append_error(errors, "遍历失败:" + _error_text(error)) continue entries.sort(key=lambda entry: entry.name) for entry in entries: try: child = entry.stat(follow_symlinks=False) except OSError as error: complete = False _append_error(errors, "stat 失败:" + _error_text(error)) continue if stat.S_ISDIR(child.st_mode): stack.append(entry.path) continue if not stat.S_ISREG(child.st_mode): continue # symlink/设备不跟随,du 默认也不计目标 if int(getattr(child, "st_nlink", 0)) > 1: key = (int(child.st_dev), int(child.st_ino)) if key in seen: continue # du 只算一次 seen.add(key) if files >= max_files: complete = False _append_error(errors, f"文件数超过采集上限 {max_files}") stack.clear() break apparent += int(child.st_size) actual += int(getattr(child, "st_blocks", 0)) * 512 files += 1 return { "apparent_bytes": apparent, "actual_bytes": actual, "file_count": files, "dir_count": dirs, "complete": complete, "errors": errors, } 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 = "", host: str | None = None, 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, "collector_version": COLLECTOR_VERSION, "generation": f"{collected_at.strftime('%Y%m%dT%H%M%SZ')}-{uuid.uuid4().hex[:12]}", "collected_at": collected_at.isoformat().replace("+00:00", "Z"), "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": {}, "incomplete_count": 0, "skipped": [], "truncated": False, "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}") entries = list(os.scandir(root)) except OSError as error: _append_error(errors, "无法列出备份根:" + _error_text(error)) snapshot["complete"] = False snapshot["filesystem"], capacity_errors = capacity(root) for item in capacity_errors: _append_error(errors, item) return snapshot fs_info, capacity_errors = capacity(root) snapshot["filesystem"] = fs_info for item in capacity_errors: _append_error(errors, item) dirs: list[str] = [] for entry in entries: name = entry.name if name.endswith(".incomplete"): snapshot["incomplete_count"] += 1 continue if not STAMP_NAME.match(name) or "/" in name or "\\" in name: snapshot["skipped"].append({"name": name, "reason": "目录名不合法"}) continue try: if entry.is_symlink(): snapshot["skipped"].append({"name": name, "reason": "符号链接不跟随"}) continue if not entry.is_dir(follow_symlinks=False): snapshot["skipped"].append({"name": name, "reason": "不是批次目录"}) continue except OSError as error: _append_error(errors, "批次项不可读:" + _error_text(error)) continue dirs.append(name) dirs.sort(reverse=True) if len(dirs) > max_batches: dirs = dirs[:max_batches] snapshot["truncated"] = True for name in dirs: snapshot["batches"].append(_collect_batch(root, name, scan)) snapshot["complete"] = ( not errors and not snapshot["truncated"] and all(batch["complete"] for batch in snapshot["batches"]) ) return snapshot def _collect_batch(root: str, name: str, scan: Callable[[str], Iterable[Any]]) -> dict[str, Any]: batch_path = os.path.join(root, name) state, manifest_error, manifest = _read_manifest(os.path.join(batch_path, "MANIFEST.json")) tree = measure_tree(batch_path, scan) errors = list(tree["errors"]) manifest_databases = [ item for item in (manifest.get("databases") or []) if isinstance(item, str) ] if isinstance(manifest.get("databases"), list) else [] raw_failed = manifest.get("failed_databases") failed_values: list[Any] = raw_failed if isinstance(raw_failed, list) else [] failed = {item for item in failed_values if isinstance(item, str)} actual_dirs: set[str] = set() try: for entry in scan(batch_path): db_name = entry.name[: -len(".dir")] if entry.name.endswith(".dir") else "" if not db_name or not STAMP_NAME.match(db_name): continue try: info = entry.stat(follow_symlinks=False) except OSError as error: _append_error(errors, "子库目录不可读:" + _error_text(error)) continue if not stat.S_ISDIR(info.st_mode) or stat.S_ISLNK(info.st_mode): continue actual_dirs.add(db_name) except OSError as error: _append_error(errors, "批次目录不可读:" + _error_text(error)) names = sorted(set(manifest_databases) | actual_dirs) databases: list[dict[str, Any]] = [] for db in names: if not db or not STAMP_NAME.match(db): continue dir_name = db + ".dir" path = os.path.join(batch_path, dir_name) present = db in actual_dirs if state == "ok" and db in manifest_databases and not present: _append_error(errors, f"清单列出 {db} 但 {dir_name} 不存在") measured = measure_tree(path, scan) if present else None db_complete = bool(measured is not None and measured["complete"]) if measured is not None and not measured["complete"]: _append_error(errors, f"子库 {db} 遍历不完整") databases.append( { "name": db, "dir_name": dir_name, "path": path, "present": present, "failed": db in failed, "in_manifest": db in manifest_databases, "apparent_bytes": measured["apparent_bytes"] if measured is not None and db_complete else None, "actual_bytes": measured["actual_bytes"] if measured is not None and db_complete else None, "file_count": measured["file_count"] if measured is not None and db_complete else None, "dir_count": measured["dir_count"] if measured is not None and db_complete else None, "complete": db_complete, "errors": measured["errors"] if measured is not None else [], } ) complete = tree["complete"] and all(database["complete"] for database in databases) and not errors manifest_total = manifest.get("total_bytes") if state == "ok" else 0 if state == "ok" and not isinstance(manifest_total, int): manifest_total = 0 duration = manifest.get("duration_seconds") if state == "ok" else 0 if not isinstance(duration, int): duration = 0 batch = { "stamp": name, "path": batch_path, "manifest_state": state, "manifest_error": manifest_error, "kind": manifest.get("kind", "") if state == "ok" else "", "created_at": manifest.get("created_at", "") if state == "ok" else "", "started_at": manifest.get("started_at", "") if state == "ok" else "", "duration_seconds": duration, "manifest_total_bytes": int(manifest_total) if state == "ok" else None, "complete": complete, "errors": errors, "apparent_bytes": (int(manifest_total) if state == "ok" and manifest_total else tree["apparent_bytes"]) if complete else None, "actual_bytes": tree["actual_bytes"] if complete else None, "file_count": tree["file_count"] if complete else None, "dir_count": tree["dir_count"] if complete else None, "databases": databases if complete else [ {**database, "apparent_bytes": None, "actual_bytes": None, "file_count": None, "dir_count": None} for database in databases ], } return batch def write_snapshot(output: str, snapshot: dict[str, Any]) -> None: directory = os.path.dirname(os.path.abspath(output)) os.makedirs(directory, mode=0o755, exist_ok=True) fd, temporary = tempfile.mkstemp(prefix=".metadata-", dir=directory) try: with os.fdopen(fd, "w", encoding="utf-8") as handle: json.dump(snapshot, handle, ensure_ascii=False, sort_keys=True, indent=2) handle.write("\n") handle.flush() os.fsync(handle.fileno()) os.chmod(temporary, 0o644) os.replace(temporary, output) dir_fd = os.open(directory, os.O_DIRECTORY) try: os.fsync(dir_fd) finally: os.close(dir_fd) except BaseException: try: os.unlink(temporary) except OSError: pass raise def _self_test() -> None: import shutil import sys as _sys base = tempfile.mkdtemp(prefix="backup-metadata-test-") try: root = os.path.join(base, "rds-logical") stamp = "20261118T193001Z" batch = os.path.join(root, stamp) os.makedirs(os.path.join(batch, "weknora_test.dir"), mode=0o700) payload = "x" * 100 with open(os.path.join(batch, "weknora_test.dir", "toc.dat"), "w", encoding="utf-8") as handle: handle.write(payload) manifest = { "kind": "rds-logical-backup", "created_at": stamp, "duration_seconds": 53, "databases": ["weknora_test"], "failed_databases": [], "total_bytes": len(payload), "files": [{"file": "weknora_test.dir/toc.dat", "bytes": len(payload)}], } with open(os.path.join(batch, "MANIFEST.json"), "w", encoding="utf-8") as handle: json.dump(manifest, handle) fixed = dt.datetime(2026, 11, 20, 1, 2, 3, tzinfo=dt.timezone.utc) snapshot = collect(root, "weknora-test:" + root, "weknora-test", now=fixed) assert snapshot["complete"] is True, snapshot assert snapshot["schema_version"] == SCHEMA_VERSION assert snapshot["batches"][0]["manifest_state"] == "ok" assert snapshot["batches"][0]["databases"][0]["name"] == "weknora_test" assert snapshot["batches"][0]["actual_bytes"] >= len(payload) assert snapshot["filesystem"]["total_bytes"] > 0 def denied_scan(target: str): if target.endswith(".dir"): raise PermissionError(errno.EACCES, "Permission denied", target) return os.scandir(target) denied = collect(root, scan=denied_scan, now=fixed) assert denied["complete"] is False assert denied["batches"][0]["complete"] is False assert denied["batches"][0]["actual_bytes"] is None assert denied["batches"][0]["databases"][0]["actual_bytes"] is None assert any("Permission denied" in item for item in denied["batches"][0]["errors"]) # 与参考 host-backup-inventory.sh 同口径:目录自身计入、树内硬链接去重、 # 单库与整批各自独立测量,各自与自身的 du -sB1 一致。 import subprocess if shutil.which("du"): def du_bytes(target: str) -> int: result = subprocess.run( ["du", "-sB1", target], capture_output=True, text=True, check=True ) return int(result.stdout.split()[0]) link_root = os.path.join(base, "hardlink-root") plain_root = os.path.join(base, "single-hardlink-root") plain_batch = os.path.join(plain_root, "20261114T193001Z") plain_db = os.path.join(plain_batch, "weknora_v090prod.dir") os.makedirs(plain_db) with open(os.path.join(plain_db, "base.tar"), "wb") as handle: handle.write(b"x" * 5000) os.link(os.path.join(plain_db, "base.tar"), os.path.join(plain_db, "base.tar.link")) with open(os.path.join(plain_batch, "MANIFEST.json"), "w", encoding="utf-8") as handle: json.dump({"databases": ["weknora_v090prod"]}, handle) plain = collect(plain_root, now=fixed) plain_db_info = plain["batches"][0]["databases"][0] plain_batch_info = plain["batches"][0] assert plain_db_info["actual_bytes"] == du_bytes(plain_db), plain_db_info assert plain_batch_info["actual_bytes"] == du_bytes(plain_batch), plain_batch_info assert plain_db_info["file_count"] == 1, plain_db_info link_batch = os.path.join(link_root, "20261116T193001Z") db_a = os.path.join(link_batch, "weknora_a.dir") db_b = os.path.join(link_batch, "weknora_b.dir") os.makedirs(db_a) os.makedirs(db_b) with open(os.path.join(db_a, "one.dat"), "wb") as handle: handle.write(b"x" * 5000) os.link(os.path.join(db_a, "one.dat"), os.path.join(db_a, "alias.dat")) with open(os.path.join(db_b, "two.dat"), "wb") as handle: handle.write(b"y" * 3000) # 跨子库硬链接:整批 du 只算一次,单库 du 各自算一次。 os.link(os.path.join(db_a, "one.dat"), os.path.join(db_b, "shared.dat")) with open(os.path.join(link_batch, "globals.sql"), "wb") as handle: handle.write(b"z" * 1000) with open(os.path.join(link_batch, "MANIFEST.json"), "w", encoding="utf-8") as handle: json.dump({"kind": "rds-logical-backup", "databases": ["weknora_a", "weknora_b"]}, handle) linked = collect(link_root, now=fixed) linked_batch = linked["batches"][0] assert linked["complete"] is True, linked by_name = {item["name"]: item for item in linked_batch["databases"]} assert by_name["weknora_a"]["actual_bytes"] == du_bytes(db_a), by_name["weknora_a"] assert by_name["weknora_b"]["actual_bytes"] == du_bytes(db_b), by_name["weknora_b"] assert linked_batch["actual_bytes"] == du_bytes(link_batch), linked_batch # 逻辑文件数:one/alias/shared 同一 inode 只计一次,再加 two.dat、globals.sql、MANIFEST assert by_name["weknora_a"]["file_count"] == 1, by_name["weknora_a"] assert by_name["weknora_b"]["file_count"] == 2, by_name["weknora_b"] assert linked_batch["file_count"] == 4, linked_batch assert linked_batch["actual_bytes"] >= 5000 + 3000 + 1000 # MANIFEST 只接受批次目录内的常规文件:指向别处的符号链接必须 invalid,不能被跟随。 symlink_root = os.path.join(base, "symlink-root") symlink_batch = os.path.join(symlink_root, "20261115T193001Z") os.makedirs(os.path.join(symlink_batch, "weknora_x.dir")) outside = os.path.join(base, "outside-manifest.json") with open(outside, "w", encoding="utf-8") as handle: json.dump({"databases": ["weknora_x"]}, handle) os.symlink(outside, os.path.join(symlink_batch, "MANIFEST.json")) symlinked = collect(symlink_root, now=fixed) assert symlinked["batches"][0]["manifest_state"] == "invalid" assert "常规文件" in symlinked["batches"][0]["manifest_error"] incomplete_dir = os.path.join(root, "20261117T193001Z.incomplete") os.makedirs(incomplete_dir) with open(os.path.join(incomplete_dir, "MANIFEST.json"), "w", encoding="utf-8") as handle: handle.write("{}") ignored = collect(root, now=fixed) 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: reloaded = json.load(handle) assert reloaded["batches"][0]["stamp"] == stamp assert not [name for name in os.listdir(os.path.dirname(output)) if name.startswith(".metadata-")] print("collect_backup_metadata self-test ok") _sys.stdout.flush() finally: shutil.rmtree(base, ignore_errors=True) def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(description="备份目录只读元数据采集器") parser.add_argument("--root", required=False, help="宿主机上的 rds-logical 目录") parser.add_argument("--output", required=False, help="原子写出的 metadata.json") 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: _self_test() return 0 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: print(f"collect failed: {error}", file=sys.stderr) return 1 summary = { "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)) healthy = bool(snapshot["complete"] and snapshot["usage"].get("complete") and not snapshot["quota_error"]) return 0 if healthy else 2 if __name__ == "__main__": raise SystemExit(main())