#!/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._-]+$") class CollectError(Exception): pass 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 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, ) -> dict[str, Any]: root = os.path.abspath(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, "complete": True, "errors": [], "filesystem": {}, "incomplete_count": 0, "skipped": [], "truncated": False, "batches": [], } errors: list[str] = snapshot["errors"] 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] 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("--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: snapshot = collect( args.root, source=args.source, host=args.host or None, max_batches=max(1, args.max_batches), ) 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"], "collected_at": snapshot["collected_at"], "output": args.output, } print(json.dumps(summary, ensure_ascii=False)) return 0 if snapshot["complete"] else 2 if __name__ == "__main__": raise SystemExit(main())