feat: scope recovery manifests while verifying complete backups

This commit is contained in:
阿白叔 committed 2026-11-02 19:32:07 +08:00
1 parent 877e3b4c76
commit 29c154d2ca
5 files changed
+789 -105

No files matched your search

+30 -105
View File
@@ -3,12 +3,8 @@
This restores project data for an existing library entry. It is not a native
cross-library import and does not delete library records or shared symbols.
"""
from contextlib import ExitStack
from concurrent.futures import ThreadPoolExecutor
from dataclasses import asdict, replace
import hashlib
import json
import os
from pathlib import Path
import re
import shutil
@@ -16,105 +12,22 @@ import stat
from uuid import uuid4
from .verify_runner import VerifyResult, preflight
from .scoped_manifest import (ManifestScope, build_manifest, copy_verified,
hash_file as _hash, scan_tree as _scan)
def _hash(path):
digest = hashlib.sha256()
with path.open('rb') as stream:
for data in iter(lambda: stream.read(1024 * 1024), b''):
digest.update(data)
return digest.hexdigest()
def _manifest(root, *, scope=None, exclude=None, progress=None):
return build_manifest(root, scope=scope, exclude=exclude, progress=progress, hash_function=_hash)
def _scan(root):
if root.lstat().st_file_attributes & stat.FILE_ATTRIBUTE_REPARSE_POINT:
raise ValueError(f'不支持通过目录链接恢复:{root}')
entries = {}
folders = [root]
while folders:
with os.scandir(folders.pop()) as scanned:
for entry in scanned:
metadata = entry.stat(follow_symlinks=False)
if metadata.st_file_attributes & stat.FILE_ATTRIBUTE_REPARSE_POINT:
raise ValueError(f'目录含文件或目录链接,停止恢复:{entry.path}')
path = Path(entry.path)
entries[path] = metadata
if stat.S_ISDIR(metadata.st_mode):
folders.append(path)
return dict(sorted(entries.items()))
def _copy_verified(source, destination, *, scope=None, progress=None):
return copy_verified(source, destination, scope=scope, progress=progress, hash_function=_hash)
def _paths(root):
return list(_scan(root))
def _manifest(root, *, exclude=None):
entries = _scan(root)
paths = [path for path in entries
if exclude is None or not path.is_relative_to(exclude)]
def entry(path):
return str(path.relative_to(root)), _hash(path) if stat.S_ISREG(entries[path].st_mode) else None
with ThreadPoolExecutor(max_workers=8) as pool:
return dict(pool.map(entry, paths))
def _copy_verified(source, destination, *, progress=None):
"""Copy every file, refusing links and changed files; lock native databases."""
import win32con, win32file
entries = _scan(source)
paths = list(entries)
destination.mkdir(parents=True, exist_ok=False)
record = {}
with ExitStack() as stack:
locks = {}
for path in paths:
if stat.S_ISREG(entries[path].st_mode) and (path.name.casefold() == 'icdb.dat' or path.suffix.casefold() == '.lmc'):
handle = win32file.CreateFile(str(path), win32con.GENERIC_READ, 0, None,
win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None)
stack.callback(handle.Close)
locks[path] = handle
files = []
for path in paths:
relative = str(path.relative_to(source))
copied = destination / relative
if stat.S_ISDIR(entries[path].st_mode):
copied.mkdir(parents=True, exist_ok=True)
record[relative] = None
continue
files.append(path)
def copy_file(path):
relative = str(path.relative_to(source))
copied = destination / relative
before = entries[path]
copied.parent.mkdir(parents=True, exist_ok=True)
if path in locks:
with copied.open('wb') as stream:
while True:
_, data = win32file.ReadFile(locks[path], 1024 * 1024)
if not data:
break
stream.write(data)
shutil.copystat(path, copied)
digest = _hash(copied)
else:
digest = _hash(path)
shutil.copy2(path, copied)
if _hash(copied) != digest:
raise OSError(f'副本校验失败:{path}')
after = path.stat()
if (before.st_size, before.st_mtime_ns) != (after.st_size, after.st_mtime_ns):
raise OSError(f'复制期间文件变化:{path}')
return relative, digest
with ThreadPoolExecutor(max_workers=8) as pool:
for count, (relative, digest) in enumerate(pool.map(copy_file, files), 1):
record[relative] = digest
if progress and (count % 256 == 0 or count == len(files)):
progress(count, len(files))
if _manifest(source) != record:
raise OSError(f'复制期间目录内容变化:{source}')
return record
def _idle_check(library, project, pcb):
from .mentor_adapter import pcb_processes, _process_details
from .icdb_ownership import unreleased_addresses
@@ -213,9 +126,15 @@ def recover_from_backup(request, source, *, progress=None, verifier=None, idle_c
record = {'operation': 'same_cbb_complete_project_restore', 'source': str(source),
'library': str(library), 'block': request.block_name, 'installed': False,
'validation_library': str(validation_dir/library.name)}
def emit(stage, message):
def emit(stage, message, **details):
if progress:
progress({'stage': stage, 'block': request.block_name, 'message': message})
progress({'stage': stage, 'block': request.block_name, 'message': message, **details})
def copy_progress(stage, message):
def report(event):
details = {key: value for key, value in event.items() if key != 'stage'}
emit(stage, f'{message} {event["copied_files"]} / {event["total_files"]}',
manifest_stage=event['stage'], **details)
return report
def save(result):
record.update({'installed': installed, 'result': asdict(result)})
root.mkdir(parents=True, exist_ok=True)
@@ -245,13 +164,16 @@ def recover_from_backup(request, source, *, progress=None, verifier=None, idle_c
raise ValueError('磁盘空间不足:需要容纳中心库回退副本和验证副本。')
(root/'recovery-request.json').write_text(json.dumps(record, ensure_ascii=False, indent=2), encoding='utf-8')
emit('backup', '正在保留完整中心库副本…')
original_manifest = _copy_verified(library_root, root/'library-before', progress=lambda n, total:
emit('backup', f'正在保留中心库副本:{n} / {total} 个文件…'))
library_scope = ManifestScope.library(request.block_name, library.name)
original_manifest = _copy_verified(library_root, root/'library-before', scope=library_scope,
progress=copy_progress('backup', '正在保留中心库副本:'))
(root/'library-before-manifest.json').write_text(json.dumps(original_manifest, indent=2), encoding='utf-8')
emit('prepare_source', '正在准备备份验证副本…')
source_manifest = _copy_verified(source.parent, root/'source-before')
_copy_verified(root/'library-before', validation_dir, progress=lambda n, total:
emit('prepare_source', f'正在准备验证库:{n} / {total} 个文件…'))
source_manifest = _copy_verified(source.parent, root/'source-before',
progress=copy_progress('prepare_source', '正在保留备份工程副本:'))
(root/'source-before-manifest.json').write_text(json.dumps(source_manifest, indent=2), encoding='utf-8')
_copy_verified(root/'library-before', validation_dir, scope=library_scope,
progress=copy_progress('prepare_source', '正在准备验证库:'))
staged_library = validation_dir/library.name
staged_work = staged_library.parent/'ReusableBlocksLP'/request.block_name/'Work'
# Both paths are newly created private copies; originals are retained.
@@ -259,7 +181,8 @@ def recover_from_backup(request, source, *, progress=None, verifier=None, idle_c
if not resolved_work.is_relative_to(validation_dir.resolve()):
raise ValueError('验证副本工程路径越界。')
shutil.rmtree(resolved_work)
_copy_verified(root/'source-before', staged_work)
_copy_verified(root/'source-before', staged_work,
progress=copy_progress('prepare_source', '正在准备备份验证工程:'))
staged_project = staged_work/source.name
staged_pcb = staged_work/source_pcb.relative_to(source.parent)
_align_library(staged_project, staged_pcb, staged_library)
@@ -277,15 +200,17 @@ def recover_from_backup(request, source, *, progress=None, verifier=None, idle_c
'备份校验未通过,目标未更改。\n' + (source_result.stderr or source_result.library_flag_detail)))
idle_check(library, project, pcb)
idle_check(staged_library, staged_project, staged_pcb)
if _manifest(source.parent) != source_manifest:
raise ValueError('备份来源在验证期间发生变化,目标未更改。')
token = root.name.removeprefix('backup-restore-')
work = project.parent.resolve()
incoming = work.with_name('Work.restore-' + token)
retained = work.with_name('Work.before-restore-' + token)
_copy_verified(staged_work, incoming)
_copy_verified(staged_work, incoming,
progress=copy_progress('prepare_source', '正在准备恢复工程:'))
_align_library(incoming/source.name, incoming/source_pcb.relative_to(source.parent), library)
if _manifest(library_root, exclude=incoming.resolve()) != original_manifest:
idle_check(library, source, source_pcb)
if _manifest(source.parent) != source_manifest:
raise ValueError('备份来源在验证期间发生变化,目标未更改。')
if _manifest(library_root, scope=library_scope, exclude=incoming.resolve()) != original_manifest:
raise ValueError('目标中心库在验证期间发生变化,停止恢复。')
emit('install', '备份已通过验证,正在保留原工程并恢复…')
work.rename(retained)
+265
View File
@@ -0,0 +1,265 @@
"""Complete, metadata-verified snapshots with scoped semantic SHA256 manifests.
Unknown engineering files are primary. Only explicit runtime, history and
generated categories are ignored by semantic comparisons; they are still copied
and their membership/size/mtime must remain stable throughout the snapshot.
"""
from concurrent.futures import ThreadPoolExecutor
from contextlib import ExitStack
from dataclasses import asdict, dataclass
import hashlib
import os
from pathlib import Path
import shutil
import stat
MANIFEST_VERSION = 1
_NONPRIMARY_DIRECTORIES = frozenset({
'log', 'logs', 'temp', 'tmp', '__pycache__', 'backup', 'backups',
'output', 'outputs', 'report', 'reports', 'gerber', 'gerbers', 'odb++',
})
_NONPRIMARY_SUFFIXES = frozenset({
'.log', '.tmp', '.temp', '.lck', '.lock', '.bak', '.backup', '.pdf',
})
@dataclass(frozen=True)
class ManifestScope:
"""Project root by default; library selects one CBB and shared dependencies."""
kind: str = 'project'
block_name: str = ''
library_name: str = ''
def __post_init__(self):
if self.kind not in ('project', 'library'):
raise ValueError('Unknown manifest scope')
if self.kind == 'library':
for value in (self.block_name, self.library_name):
if not value or value in ('.', '..') or any(c in value for c in '/\\:'):
raise ValueError('Library scope requires single-component block/library names')
@classmethod
def library(cls, block_name, library_name):
return cls('library', block_name, library_name)
def includes_directory(self, relative):
parts = tuple(part.casefold() for part in Path(relative).parts)
if any(part in _NONPRIMARY_DIRECTORIES or part.startswith('work.before-restore-')
for part in parts):
return False
if self.kind == 'project' or parts[0] != 'reusableblockslp':
return True
return ((len(parts) < 2 or parts[1] == self.block_name.casefold())
and (len(parts) < 3 or parts[2] in ('work', 'cert')))
def classify(self, relative):
"""Return a semantic scope label or None; paths are relative to the root."""
parts = tuple(part.casefold() for part in Path(relative).parts)
if (any(part in _NONPRIMARY_DIRECTORIES or part.startswith('work.before-restore-')
for part in parts[:-1])
or Path(parts[-1]).suffix in _NONPRIMARY_SUFFIXES
or parts[-1] == 'saddress.adr' or parts[-1].startswith('~$')):
return None
if self.kind == 'project':
return 'project'
if parts[0] == 'reusableblockslp':
if len(parts) < 4 or parts[1] != self.block_name.casefold():
return None
return {'work': 'target_work', 'cert': 'target_cert'}.get(parts[2])
if len(parts) == 1:
if Path(parts[0]).suffix == '.lmc' and parts[0] != self.library_name.casefold():
return None
return 'library_config'
# Shared DB/config/dependency trees are conservative: new dependency
# directory names remain primary without adding them to an allowlist.
return 'shared_dependency'
def hash_file(path):
digest = hashlib.sha256()
with Path(path).open('rb') as stream:
for data in iter(lambda: stream.read(1024 * 1024), b''):
digest.update(data)
return digest.hexdigest()
def scan_tree(root, *, scope=None, exclude=None):
"""Refuse links/special files; optionally prune trees outside semantic scope.
Copies always call this without a scope, validating complete membership.
Later semantic scans avoid entering runtime or unrelated CBB directories.
"""
root = Path(root)
if root.lstat().st_file_attributes & stat.FILE_ATTRIBUTE_REPARSE_POINT:
raise ValueError(f'不支持通过目录链接恢复:{root}')
entries = {}
folders = [root]
while folders:
with os.scandir(folders.pop()) as scanned:
for entry in scanned:
path = Path(entry.path)
if exclude is not None and path.is_relative_to(exclude):
continue
if scope is not None:
relative = path.relative_to(root)
if entry.is_dir(follow_symlinks=False):
if not scope.includes_directory(relative):
continue
elif scope.classify(relative) is None:
continue
metadata = entry.stat(follow_symlinks=False)
if metadata.st_file_attributes & stat.FILE_ATTRIBUTE_REPARSE_POINT:
raise ValueError(f'目录含文件或目录链接,停止恢复:{entry.path}')
if not (stat.S_ISDIR(metadata.st_mode) or stat.S_ISREG(metadata.st_mode)):
raise ValueError(f'不支持的特殊文件:{entry.path}')
entries[path] = metadata
if stat.S_ISDIR(metadata.st_mode):
folders.append(path)
return dict(sorted(entries.items()))
def _metadata_record(root, entries):
return {path.relative_to(root).as_posix():
('file', info.st_size, info.st_mtime_ns) if stat.S_ISREG(info.st_mode) else ('dir',)
for path, info in entries.items()}
def _manifest(scope, files):
return {'version': MANIFEST_VERSION, 'scope': asdict(scope), 'files': dict(sorted(files.items()))}
def _emit(progress, stage, hashed_files, hashed_bytes, **extra):
if progress:
progress({'stage': stage, 'hashed_files': hashed_files, 'hashed_bytes': hashed_bytes, **extra})
def build_manifest(root, *, scope=None, exclude=None, progress=None, hash_function=hash_file):
"""Hash primary files only. Excluded subtrees are for private incoming Work.
The returned dict is versioned, JSON-compatible and relocatable. Equality
compares primary path membership, size, hash and scope, never runtime mtimes.
"""
root = Path(root)
scope = scope or ManifestScope()
entries = scan_tree(root, scope=scope, exclude=exclude)
selected = {path: scope.classify(path.relative_to(root)) for path, info in entries.items()
if stat.S_ISREG(info.st_mode)}
selected = {path: label for path, label in selected.items() if label is not None}
def hashed(path):
digest = hash_function(path)
after = path.stat()
before = entries[path]
if (before.st_size, before.st_mtime_ns) != (after.st_size, after.st_mtime_ns):
raise OSError(f'计算哈希期间文件变化:{path}')
return path.relative_to(root).as_posix(), {
'size': before.st_size, 'sha256': digest, 'scope': selected[path]}
files = {}
hashed_bytes = 0
_emit(progress, 'hash', 0, 0, total_files=len(selected))
with ThreadPoolExecutor(max_workers=8) as pool:
for count, (relative, item) in enumerate(pool.map(hashed, selected), 1):
files[relative] = item
hashed_bytes += item['size']
if count % 256 == 0 or count == len(selected):
_emit(progress, 'hash', count, hashed_bytes, total_files=len(selected))
# Check primary membership and metadata again after every hash completed.
# Runtime files can change/add/disappear without a semantic conflict.
after = scan_tree(root, scope=scope, exclude=exclude)
before_primary = {p: entries[p] for p in selected}
after_primary = {p: info for p, info in after.items() if stat.S_ISREG(info.st_mode)
and (exclude is None or not p.is_relative_to(exclude))
and scope.classify(p.relative_to(root)) is not None}
if _metadata_record(root, before_primary) != _metadata_record(root, after_primary):
raise OSError(f'计算哈希期间主要文件变化:{root}')
return _manifest(scope, files)
def copy_verified(source, destination, *, scope=None, progress=None, hash_function=hash_file):
"""Copy the whole tree, validate all metadata, SHA256 only scoped primary files.
Native icdb.dat/LMC files are held with exclusive read handles for the copy.
Their expected SHA256 comes from the source read stream, independently of
hashing destination bytes. Failures retain the partial destination evidence.
Progress receives one dict with stage, hashed_files/bytes and copied_files.
"""
import win32con
import win32file
source, destination = Path(source), Path(destination)
scope = scope or ManifestScope()
if destination.resolve().is_relative_to(source.resolve()):
raise ValueError('复制目标不能位于源目录内。')
entries = scan_tree(source)
expected_metadata = _metadata_record(source, entries)
destination.mkdir(parents=True, exist_ok=False)
files = [path for path, info in entries.items() if stat.S_ISREG(info.st_mode)]
record = {}
hashed_count = hashed_bytes = 0
_emit(progress, 'copy', 0, 0, copied_files=0, total_files=len(files))
with ExitStack() as stack:
locks = {}
for path in files:
if path.name.casefold() == 'icdb.dat' or path.suffix.casefold() == '.lmc':
handle = win32file.CreateFile(str(path), win32con.GENERIC_READ, 0, None,
win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None)
stack.callback(handle.Close)
locks[path] = handle
for path, info in entries.items():
if stat.S_ISDIR(info.st_mode):
(destination/path.relative_to(source)).mkdir(parents=True, exist_ok=True)
def copy_file(path):
relative = path.relative_to(source)
copied = destination/relative
copied.parent.mkdir(parents=True, exist_ok=True)
label = scope.classify(relative)
digest = None
if path in locks:
stream_hash = hashlib.sha256() if label is not None else None
with copied.open('wb') as stream:
while True:
_, data = win32file.ReadFile(locks[path], 1024 * 1024)
if not data:
break
if stream_hash is not None:
stream_hash.update(data)
stream.write(data)
shutil.copystat(path, copied)
if stream_hash is not None:
digest = stream_hash.hexdigest()
else:
if label is not None:
digest = hash_function(path)
shutil.copy2(path, copied)
before, after = entries[path], path.stat()
if (before.st_size, before.st_mtime_ns) != (after.st_size, after.st_mtime_ns):
raise OSError(f'复制期间文件变化:{path}')
return relative.as_posix(), digest, label
with ThreadPoolExecutor(max_workers=8) as pool:
for count, (relative, digest, label) in enumerate(pool.map(copy_file, files), 1):
if label is not None:
size = entries[source/relative].st_size
record[relative] = {'size': size, 'sha256': digest, 'scope': label}
hashed_count += 1
hashed_bytes += size
if count % 256 == 0 or count == len(files):
_emit(progress, 'copy', hashed_count, hashed_bytes,
copied_files=count, total_files=len(files))
def validate_bytes(relative):
item = record[relative]
path = source/relative
if path not in locks and hash_function(path) != item['sha256']:
raise OSError(f'复制期间主要文件内容变化:{path}')
if hash_function(destination/relative) != item['sha256']:
raise OSError(f'复制内容校验失败:{path}')
with ThreadPoolExecutor(max_workers=8) as pool:
list(pool.map(validate_bytes, record))
if _metadata_record(source, scan_tree(source)) != expected_metadata:
raise OSError(f'复制期间目录内容变化:{source}')
if _metadata_record(destination, scan_tree(destination)) != expected_metadata:
raise OSError(f'复制目标目录或文件元数据不一致:{destination}')
return _manifest(scope, record)