fix: 遇到损坏目录项时不再崩溃,只跳过并记录
- 根因:损坏目录项里读出的时间戳是垃圾值(负值/越界),_add_problem 里 time.localtime 抛 OSError(22),异常从单文件兜底里逃出去,导致整次备份中断(用户 F: 盘 19406 个文件只备到一半) - _fmt_ns:时间戳格式化失败不再抛异常,改为输出"无效时间戳(xxx)" - 源目录名非法(目录项损坏):直接跳过整棵子树并记录"已跳过",不再改名造空目录 - 枚举得到却打不开的条目(FileNotFoundError):记为"源目录项损坏",单独计数,不中断 - 存在损坏目录时本轮跳过清理阶段,保护备份里已有的副本不被误删 - 打不开的条目不进源盘快照,避免下一轮又报"源文件消失" - 问题清单/日志/GUI 汇总新增"损坏的目录项 N 处(建议 chkdsk /f)" - 新增 5 项损坏目录项测试(共 62 项)
This commit is contained in:
1 parent
c860d3d504
commit
d477d5d10a
4 files changed
+167
-9
No files matched your search
@@ -2,7 +2,7 @@
|
||||
|
||||
一款 Windows 平台的开源 U 盘备份工具,带图形界面(GUI),支持全量镜像备份与增量复制。
|
||||
|
||||
> **v2.2.0 加固版**:针对"多次备份后备份数据崩坏 / 备份内容过期 / 备份文件被误删"重写了备份引擎,
|
||||
> **v2.2.1 加固版**:针对"多次备份后备份数据崩坏 / 备份内容过期 / 备份文件被误删"重写了备份引擎,
|
||||
> 详见 [ANALYSIS.md](ANALYSIS.md)(含 F: 盘现场取证与 5 个已复现缺陷)。
|
||||
|
||||
## 功能特性
|
||||
@@ -81,6 +81,7 @@ powershell -ExecutionPolicy Bypass -File tools\build_exe.ps1
|
||||
| 单个文件复制异常 | 记账后继续,最后汇总;有失败时不做清理 |
|
||||
| 源文件被别的程序改动(备份期间) | 备份后复查大小/时间,记入问题清单,不覆盖备份 |
|
||||
| 源文件"没改却变了"(介质损坏) | 开启快照比对后报"源文件可疑",**保留旧备份不覆盖**,直到人工处理 |
|
||||
| 源盘目录项损坏(名字非法 / 枚举得到却打不开) | 跳过该条并记入问题清单(`源目录项损坏`),**不崩溃、不中断**;存在损坏目录时本轮不做清理 |
|
||||
| 文件名只有大小写不同 | 就地改名同步,不删除重建 |
|
||||
|
||||
## 测试
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""损坏目录项(FAT32 半坏)时的行为:不崩溃、只跳过、不误删备份。"""
|
||||
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
ROOT = os.path.dirname(HERE)
|
||||
sys.path.insert(0, ROOT)
|
||||
|
||||
import usb_backup as ub # noqa: E402
|
||||
|
||||
|
||||
def write(path, data=b"x", mtime=None):
|
||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||
with open(path, "wb") as f:
|
||||
f.write(data)
|
||||
if mtime is not None:
|
||||
os.utime(path, (mtime, mtime))
|
||||
|
||||
|
||||
class Base(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.base = tempfile.mkdtemp(prefix="corrupt-")
|
||||
self.src = os.path.join(self.base, "src")
|
||||
self.dst = os.path.join(self.base, "dst")
|
||||
os.makedirs(self.src)
|
||||
os.makedirs(self.dst)
|
||||
|
||||
def tearDown(self):
|
||||
shutil.rmtree(self.base, ignore_errors=True)
|
||||
|
||||
def run_engine(self, **kw):
|
||||
kw.setdefault("log_callback", lambda m: None)
|
||||
return ub.BackupEngine(self.src, self.dst, **kw).run()
|
||||
|
||||
|
||||
class TestTimestampFormat(unittest.TestCase):
|
||||
def test_garbage_timestamps_do_not_raise(self):
|
||||
for ns in (None, 0, -1, -2 ** 63, 2 ** 63 - 1, 10 ** 30):
|
||||
out = ub.BackupEngine._fmt_ns(ns)
|
||||
self.assertIsInstance(out, str)
|
||||
|
||||
def test_normal_timestamp(self):
|
||||
self.assertEqual(ub.BackupEngine._fmt_ns(1600000000 * 10 ** 9),
|
||||
"2020-09-13 20:26:40")
|
||||
|
||||
|
||||
class TestCorruptFileEntry(Base):
|
||||
def test_unreadable_entry_reported_not_fatal(self):
|
||||
write(os.path.join(self.src, "good.txt"), b"good")
|
||||
write(os.path.join(self.src, "ghost.bin"), b"ghost")
|
||||
real_copy = ub.BackupEngine._copy_one
|
||||
|
||||
def ghost(self_, src, dst, size, mtime_ns):
|
||||
if os.path.basename(src) == "ghost.bin":
|
||||
raise FileNotFoundError(2, "系统找不到指定的文件", src)
|
||||
return real_copy(self_, src, dst, size, mtime_ns)
|
||||
|
||||
with mock.patch.object(ub.BackupEngine, "_copy_one", ghost):
|
||||
ok, stats = self.run_engine()
|
||||
self.assertFalse(ok) # 备份不完整,必须报出来
|
||||
self.assertEqual(stats["corrupt"], 1)
|
||||
actions = [p["action"] for p in stats["problems"]]
|
||||
self.assertIn("源目录项损坏", actions)
|
||||
with open(os.path.join(self.dst, "good.txt"), "rb") as f:
|
||||
self.assertEqual(f.read(), b"good")
|
||||
|
||||
|
||||
class TestCorruptDirEntry(Base):
|
||||
def test_corrupt_dir_skipped_and_cleanup_disabled(self):
|
||||
# 源里有一棵"名字非法"的目录(真实场景是目录项被写坏)
|
||||
write(os.path.join(self.src, "keep.txt"), b"keep")
|
||||
eng = ub.BackupEngine(self.src, self.dst, log_callback=lambda m: None)
|
||||
real_scan = eng._scan
|
||||
|
||||
def scan_with_corrupt_dir():
|
||||
files, dirs = real_scan()
|
||||
dirs.append('bad?dir')
|
||||
return files, dirs
|
||||
|
||||
eng._scan = scan_with_corrupt_dir
|
||||
ok, stats = eng.run() # 不能抛异常
|
||||
self.assertEqual(stats["corrupt"], 1)
|
||||
self.assertTrue(any(p["action"] == "已跳过" and "目录项" in p["reason"]
|
||||
for p in stats["problems"]))
|
||||
# 损坏目录不会在备份里造出空目录
|
||||
self.assertFalse(any(n.startswith("bad") for n in os.listdir(self.dst)))
|
||||
# 关键:源盘有坏条目时,不能在备份里做删除(保护已有备份)
|
||||
self.assertEqual(stats["quarantined"], 0)
|
||||
self.assertEqual(stats["deleted"], 0)
|
||||
|
||||
def test_existing_backup_copies_are_kept(self):
|
||||
write(os.path.join(self.src, "keep.txt"), b"keep")
|
||||
write(os.path.join(self.dst, "old.txt"), b"old") # 之前备份里已有、这次源里没有
|
||||
eng = ub.BackupEngine(self.src, self.dst, log_callback=lambda m: None)
|
||||
real_scan = eng._scan
|
||||
|
||||
def scan_with_corrupt_dir():
|
||||
files, dirs = real_scan()
|
||||
dirs.append('bad?dir')
|
||||
return files, dirs
|
||||
|
||||
eng._scan = scan_with_corrupt_dir
|
||||
eng.run()
|
||||
self.assertTrue(os.path.isfile(os.path.join(self.dst, "old.txt")))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main(verbosity=2)
|
||||
@@ -1,7 +1,7 @@
|
||||
VSVersionInfo(
|
||||
ffi=FixedFileInfo(
|
||||
filevers=(2, 2, 0, 0),
|
||||
prodvers=(2, 2, 0, 0),
|
||||
filevers=(2, 2, 1, 0),
|
||||
prodvers=(2, 2, 1, 0),
|
||||
mask=0x3f,
|
||||
flags=0x0,
|
||||
OS=0x40004,
|
||||
@@ -14,12 +14,12 @@ VSVersionInfo(
|
||||
StringTable('080404B0', [
|
||||
StringStruct('CompanyName', 'Udisk Backup'),
|
||||
StringStruct('FileDescription', 'U盘备份工具 - 增量/镜像备份,复制后 SHA-256 校验'),
|
||||
StringStruct('FileVersion', '2.2.0.0'),
|
||||
StringStruct('FileVersion', '2.2.1.0'),
|
||||
StringStruct('InternalName', 'usb_backup'),
|
||||
StringStruct('LegalCopyright', 'MIT License'),
|
||||
StringStruct('OriginalFilename', 'U盘备份工具.exe'),
|
||||
StringStruct('ProductName', 'U盘备份工具'),
|
||||
StringStruct('ProductVersion', '2.2.0.0')
|
||||
StringStruct('ProductVersion', '2.2.1.0')
|
||||
])
|
||||
]),
|
||||
VarFileInfo([VarStruct('Translation', [2052, 1200])])
|
||||
|
||||
+47
-4
@@ -35,7 +35,7 @@ from tkinter import ttk, messagebox, filedialog
|
||||
|
||||
# ==================== 常量 ====================
|
||||
APP_NAME = "U盘备份工具"
|
||||
APP_VERSION = "2.2.0"
|
||||
APP_VERSION = "2.2.1"
|
||||
BACKUP_ROOT_FALLBACK = "U盘备份" # 首次运行且找不到合适盘符时,建在可用空间最大的固定盘
|
||||
BUF_SIZE = 4 * 1024 * 1024 # 4MB 复制缓冲区
|
||||
HASH_BUF = 4 * 1024 * 1024
|
||||
@@ -376,7 +376,7 @@ class BackupEngine:
|
||||
"files_scanned": 0, "dirs_scanned": 0, "planned": 0, "copied": 0,
|
||||
"skipped": 0, "verified": 0, "deleted": 0, "quarantined": 0,
|
||||
"renamed": 0, "skipped_bad": 0, "problems": 0,
|
||||
"source_suspect": 0, "source_vanished": 0, "source_modified": 0,
|
||||
"source_suspect": 0, "source_vanished": 0, "source_modified": 0, "corrupt": 0,
|
||||
"bytes": 0, "failed": 0, "duration": 0.0,
|
||||
}
|
||||
self._written = set()
|
||||
@@ -385,6 +385,8 @@ class BackupEngine:
|
||||
self._used_targets = set() # 本轮已占用的目标相对路径(normcase)
|
||||
self._saved_map = {} # 上次备份留下的改名映射(源相对路径 -> 目标相对路径)
|
||||
self.problems = [] # 需要人工排查的条目(改名/跳过/失败),导出 CSV
|
||||
self._corrupt_dirs = [] # 源盘上目录项已损坏、整棵跳过的目录
|
||||
self._bad_src = set() # 打不开的源文件(目录项损坏),不参与复查/快照
|
||||
self.report_csv = None # 本次导出的问题清单 CSV 路径
|
||||
self._hashes = {} # normcase(源相对路径) -> sha256(本轮算出来的)
|
||||
self._prev_index = {} # 上一轮源盘快照
|
||||
@@ -400,6 +402,16 @@ class BackupEngine:
|
||||
self.failures.append(msg)
|
||||
self._log(" [失败] " + msg)
|
||||
|
||||
@staticmethod
|
||||
def _fmt_ns(mtime_ns):
|
||||
"""把 ns 时间戳格式化成可读时间;损坏目录项里的垃圾值不能让程序崩。"""
|
||||
if not mtime_ns:
|
||||
return ""
|
||||
try:
|
||||
return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(mtime_ns / 1e9))
|
||||
except (OSError, ValueError, OverflowError):
|
||||
return "无效时间戳(%s)" % mtime_ns
|
||||
|
||||
def _add_problem(self, kind, src_rel, dst_rel, action, reason, size=None, mtime_ns=None):
|
||||
"""记录一条"需要人工看一眼"的条目,最后导出 CSV。"""
|
||||
self.problems.append({
|
||||
@@ -409,8 +421,7 @@ class BackupEngine:
|
||||
"action": action, # 已改名 / 已跳过 / 复制失败
|
||||
"reason": " ".join(str(reason).split()),
|
||||
"size": "" if size is None else size,
|
||||
"mtime": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(mtime_ns / 1e9))
|
||||
if mtime_ns else "",
|
||||
"mtime": self._fmt_ns(mtime_ns),
|
||||
})
|
||||
|
||||
def _warn(self, msg):
|
||||
@@ -660,7 +671,11 @@ class BackupEngine:
|
||||
stamp = time.strftime("%Y%m%d-%H%M%S")
|
||||
rel = _rel(path, self.dest)
|
||||
target = os.path.join(self._quarantine_root(), stamp, rel)
|
||||
try:
|
||||
os.makedirs(_long(os.path.dirname(target)), exist_ok=True)
|
||||
except (OSError, ValueError) as e:
|
||||
self._fail("隔离区目录创建失败 %s: %s" % (rel, e))
|
||||
return False
|
||||
try:
|
||||
if os.path.isdir(_long(path)) and not os.path.islink(_long(path)):
|
||||
if os.path.exists(_long(target)):
|
||||
@@ -720,6 +735,9 @@ class BackupEngine:
|
||||
if self.cancelled:
|
||||
self._warn("已取消,跳过清理阶段")
|
||||
return
|
||||
if self._corrupt_dirs:
|
||||
self._warn("源盘存在损坏的目录项,跳过清理阶段(不删除备份里的任何文件)")
|
||||
return
|
||||
|
||||
self._log("[全量备份] 正在比对多余文件...")
|
||||
# 用"改名后"的相对路径比较,否则被改名的文件会被当成多余文件清掉
|
||||
@@ -834,6 +852,16 @@ class BackupEngine:
|
||||
|
||||
def _prepare_one_dir(self, rel):
|
||||
"""创建目标目录;名字建不出来时按策略改名,仍失败则整棵子树跳过。"""
|
||||
hard, why = name_problem(self._rel_base(rel))
|
||||
if hard:
|
||||
# 源盘的目录项已经坏了:改名只会造出一个空目录,直接跳过整棵子树
|
||||
self._corrupt_dirs.append(rel)
|
||||
self.dead_dirs.append(rel)
|
||||
self.stats["corrupt"] += 1
|
||||
self._warn("跳过损坏目录: %s(%s)" % (rel, why))
|
||||
self._add_problem("目录", rel, "", "已跳过",
|
||||
"源目录名非法(%s):目录项很可能已损坏,整棵子树未备份" % why)
|
||||
return False
|
||||
dst_rel = self._resolve_rel(rel)
|
||||
dst = os.path.join(self.dest, dst_rel)
|
||||
try:
|
||||
@@ -991,6 +1019,8 @@ class BackupEngine:
|
||||
for abs_p, rel, size, mtime_ns in files:
|
||||
if size < 0 or name_problem(self._rel_base(rel))[0]:
|
||||
continue # 扫描时就读不到/名字非法的,不参与本次复查
|
||||
if os.path.normcase(rel) in self._bad_src:
|
||||
continue # 本轮已确认打不开(目录项损坏)
|
||||
st = _safe_stat(abs_p)
|
||||
why = None
|
||||
if st is None:
|
||||
@@ -1013,6 +1043,8 @@ class BackupEngine:
|
||||
index = {}
|
||||
for _abs_p, rel, size, mtime_ns in files:
|
||||
key = os.path.normcase(rel)
|
||||
if key in self._bad_src:
|
||||
continue # 打不开的条目不进快照,免得下一轮又报"消失"
|
||||
entry = {"rel": rel, "size": size, "mtime_ns": mtime_ns}
|
||||
digest = self._hashes.get(key)
|
||||
if not digest:
|
||||
@@ -1138,6 +1170,15 @@ class BackupEngine:
|
||||
self.stats["copied"] += 1
|
||||
self.stats["bytes"] += size
|
||||
except (OSError, ValueError, BackupError) as e:
|
||||
if isinstance(e, FileNotFoundError) or getattr(e, "errno", None) == 2:
|
||||
# 枚举得到、却打不开:目录项坏了(交叉链接/首簇丢失)
|
||||
self.stats["corrupt"] += 1
|
||||
self._bad_src.add(key)
|
||||
self._fail("源目录项损坏 %s:磁盘上打不开(%s)" % (rel, e))
|
||||
self._add_problem("文件", rel, dst_rel, "源目录项损坏",
|
||||
"枚举得到但打不开,目录项可能损坏/交叉链接: %s" % e,
|
||||
size, mtime_ns)
|
||||
else:
|
||||
new_rel = None
|
||||
if self.on_bad_name == "rename" and self._bad_name_error(e):
|
||||
new_rel = self._rename_file(rel, e, size, mtime_ns)
|
||||
@@ -1252,6 +1293,8 @@ class BackupEngine:
|
||||
"校验 %d,失败 %d,用时 %.1fs"
|
||||
% (head, s["copied"], s["skipped"], s["renamed"], s["skipped_bad"],
|
||||
s["quarantined"], s["deleted"], s["verified"], s["failed"], s["duration"]))
|
||||
if s["corrupt"]:
|
||||
self._log(" [源盘] 损坏的目录项 %d 处(已跳过,建议对该盘执行 chkdsk /f)" % s["corrupt"])
|
||||
if s["source_suspect"] or s["source_vanished"] or s["source_modified"]:
|
||||
self._log(" [源盘] 内容可疑 %d,消失 %d,备份期间被改动 %d"
|
||||
% (s["source_suspect"], s["source_vanished"], s["source_modified"]))
|
||||
|
||||
Reference in new issue
Block a user