feat: scope recovery manifests while verifying complete backups
This commit is contained in:
1 parent
877e3b4c76
commit
29c154d2ca
5 files changed
+789
-105
No files matched your search
@@ -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)
|
||||
|
||||
Reference in new issue
Block a user