feat: integrate native diagnostics and coordinated CBB transactions
This commit is contained in:
1 parent
9e230e1a46
commit
da67de026f
91 files changed
+14370
-435
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,114 +12,72 @@ 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
|
||||
if pcb_processes() or any(_process_details(name) for name in (
|
||||
'LibraryManager.exe', 'viewdraw.exe')):
|
||||
raise ValueError('请先正常关闭 PCB、Library Manager 和原理图编辑器,再恢复备份。')
|
||||
from .mentor_adapter import _process_details
|
||||
from .icdb_ownership import database_directories, unreleased_addresses
|
||||
from contextlib import ExitStack
|
||||
import win32con, win32file
|
||||
directories = database_directories(library, project, pcb)
|
||||
scope = (Path(project).parent, *directories)
|
||||
for name in ('ExpeditionPCB.exe', 'LibraryManager.exe', 'viewdraw.exe',
|
||||
'iCDBProjectBackup.exe', 'ReuseBlockImporter.exe'):
|
||||
for pid, executable, command, parent in _process_details(name):
|
||||
match = _native_scope_match(command, roots=scope, files=(library, project, pcb))
|
||||
if match is True:
|
||||
raise ValueError(f'TARGET_NATIVE_OWNER_ACTIVE: 目标工程或共享库有原生会话,PID={pid}')
|
||||
if match is None:
|
||||
raise ValueError(f'TARGET_NATIVE_OWNER_UNCONFIRMED: 无法确认原生会话所属工程,PID={pid}')
|
||||
addresses = unreleased_addresses(library, project, pcb)
|
||||
if addresses:
|
||||
raise ValueError(f'数据库会话尚未释放,停止恢复:{addresses}')
|
||||
raise ValueError(f'TARGET_DATABASE_ADDRESS_UNCONFIRMED: 地址记录需原生确认;未据此判定正在占用:{addresses}')
|
||||
with ExitStack() as stack:
|
||||
paths = [Path(library), Path(pcb).parent/'Layout/LayoutDB.lyt',
|
||||
*(directory/'icdb.dat' for directory in directories)]
|
||||
for path in dict.fromkeys(paths):
|
||||
if path.is_file():
|
||||
handle = win32file.CreateFile(str(path), win32con.GENERIC_READ, 0, None,
|
||||
win32con.OPEN_EXISTING, 0, None)
|
||||
stack.callback(handle.Close)
|
||||
|
||||
|
||||
def _native_scope_match(command, *, roots=(), files=()):
|
||||
"""Match complete native path arguments; a missing identity remains unknown."""
|
||||
from .failed_session import _command_args
|
||||
if not command:
|
||||
return None
|
||||
expected_files = {Path(path).resolve() for path in files}
|
||||
expected_roots = tuple(Path(path).resolve() for path in roots)
|
||||
identities = []
|
||||
for arg in _command_args(command)[1:]:
|
||||
value = arg.split('=', 1)[-1].strip('"')
|
||||
path = Path(value)
|
||||
if not path.is_absolute():
|
||||
continue
|
||||
key = arg.split('=', 1)[0].lstrip('-/').casefold() if '=' in arg else ''
|
||||
if (path.suffix.casefold() in ('.prj', '.pcb', '.lmc')
|
||||
or path.name.casefold() in ('database', '__reusableblockssymb', 'icdb.dat')
|
||||
or key in ('project', 'icdb', 'database', 'db', 'lmc', 'prj', 'pcb')):
|
||||
identities.append(path.resolve())
|
||||
if not identities:
|
||||
return None
|
||||
return any(path in expected_files or any(path == root or path.is_relative_to(root)
|
||||
for root in expected_roots) for path in identities)
|
||||
|
||||
|
||||
def _project_text(path):
|
||||
@@ -173,17 +127,18 @@ def _source_check(source, name, original):
|
||||
|
||||
|
||||
def _align_library(project, pcb, library):
|
||||
from .mentor_adapter import ensure_project_central_library, ensure_pcb_central_library
|
||||
for path in (project, pcb.parent/'pcb.prj'):
|
||||
from .mentor_adapter import ensure_project_central_library
|
||||
from .maintenance_entry import maintenance_project_files
|
||||
projects = maintenance_project_files(project, pcb)
|
||||
for path in projects:
|
||||
if not re.findall(r'^KEY CentralLibrary "([^"]*)"', _project_text(path), re.M):
|
||||
raise ValueError('备份工程缺少 CentralLibrary 引用。')
|
||||
def already_references(path):
|
||||
return all((path.parent/value).resolve() == Path(library).resolve()
|
||||
for value in re.findall(r'^KEY CentralLibrary "([^"]*)"', _project_text(path), re.M))
|
||||
if not already_references(project):
|
||||
ensure_project_central_library(project, library)
|
||||
if not already_references(pcb.parent/'pcb.prj'):
|
||||
ensure_pcb_central_library(pcb, library)
|
||||
for path in projects:
|
||||
if not already_references(path):
|
||||
ensure_project_central_library(path, library)
|
||||
|
||||
|
||||
def recover_from_backup(request, source, *, progress=None, verifier=None, idle_check=None):
|
||||
@@ -209,25 +164,40 @@ def recover_from_backup(request, source, *, progress=None, verifier=None, idle_c
|
||||
return VerifyResult('BLOCKED', stderr='本机验证目录不能位于目标库或备份工程内。')
|
||||
mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795')
|
||||
acquired = False
|
||||
library_lock = None
|
||||
release_confirmed = True
|
||||
installed = False
|
||||
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):
|
||||
'validation_library': str(validation_dir/library.name), 'backup_policy': 'manual'}
|
||||
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)
|
||||
report = root/'recovery-result.json'
|
||||
report.write_text(json.dumps(record, ensure_ascii=False, default=str, indent=2), encoding='utf-8')
|
||||
try:
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
report.write_text(json.dumps(record, ensure_ascii=False, default=str, indent=2), encoding='utf-8')
|
||||
except OSError as error:
|
||||
return replace(result, stderr=(result.stderr+'\n恢复报告写入失败:'+str(error)).strip())
|
||||
return replace(result, evidence_path=report)
|
||||
pythoncom.CoInitialize()
|
||||
from .com_runtime import initialize_com, uninitialize_com
|
||||
initialized = initialize_com()
|
||||
try:
|
||||
acquired = win32event.WaitForSingleObject(mutex, 0) in (
|
||||
win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED)
|
||||
if not acquired:
|
||||
return VerifyResult('BLOCKED', stderr='已有 CBB 任务运行,请等待结束。', safe_to_continue=False)
|
||||
from .library_lock import LibraryLock
|
||||
library_lock = LibraryLock(library, safe_to_release=lambda: release_confirmed)
|
||||
library_lock.__enter__()
|
||||
if source.is_relative_to(library_root):
|
||||
raise ValueError('请选择目标中心库之外的独立备份工程。')
|
||||
project, pcb = preflight(replace(request, lmc_file=library))
|
||||
@@ -239,19 +209,17 @@ def recover_from_backup(request, source, *, progress=None, verifier=None, idle_c
|
||||
library_size = sum(info.st_size for info in _scan(library_root).values() if stat.S_ISREG(info.st_mode))
|
||||
source_size = sum(info.st_size for info in _scan(source.parent).values() if stat.S_ISREG(info.st_mode))
|
||||
same_drive = root.anchor.casefold() == validation_dir.anchor.casefold()
|
||||
required = library_size * (2 if same_drive else 1) + source_size * 3
|
||||
required = (library_size + source_size * 2) if same_drive else 0
|
||||
if (shutil.disk_usage(root).free < required
|
||||
or shutil.disk_usage(validation_base).free < library_size + source_size * 2):
|
||||
raise ValueError('磁盘空间不足:需要容纳中心库回退副本和验证副本。')
|
||||
or shutil.disk_usage(validation_base).free < library_size + source_size * 2
|
||||
or shutil.disk_usage(library_root).free < source_size):
|
||||
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} 个文件…'))
|
||||
(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} 个文件…'))
|
||||
emit('prepare_source', '正在准备隔离验证库;应用不自动创建回退备份…')
|
||||
library_scope = ManifestScope.library(request.block_name, library.name)
|
||||
original_manifest = _copy_verified(library_root, validation_dir, scope=library_scope,
|
||||
progress=copy_progress('prepare_source', '正在准备验证库:'))
|
||||
(root/'library-baseline-manifest.json').write_text(json.dumps(original_manifest, indent=2), encoding='utf-8')
|
||||
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 +227,9 @@ 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)
|
||||
source_manifest = _copy_verified(source.parent, staged_work,
|
||||
progress=copy_progress('prepare_source', '正在准备备份验证工程:'))
|
||||
(root/'source-manifest.json').write_text(json.dumps(source_manifest, indent=2), encoding='utf-8')
|
||||
staged_project = staged_work/source.name
|
||||
staged_pcb = staged_work/source_pcb.relative_to(source.parent)
|
||||
_align_library(staged_project, staged_pcb, staged_library)
|
||||
@@ -269,7 +239,9 @@ def recover_from_backup(request, source, *, progress=None, verifier=None, idle_c
|
||||
native_lm_verify=False, interactive_input=False)
|
||||
preflight(validation)
|
||||
emit('validate_source', '正在副本中打开备份工程并执行原生校验…')
|
||||
release_confirmed = False
|
||||
source_result = verifier(validation, progress=progress, flag_reader=read_library_flag_if_available)
|
||||
release_confirmed = source_result.safe_to_continue
|
||||
record['source_validation'] = asdict(source_result)
|
||||
if (source_result.status != 'PASS' or source_result.library_flag != 'GREEN'
|
||||
or not source_result.safe_to_continue):
|
||||
@@ -277,15 +249,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)
|
||||
@@ -297,19 +271,25 @@ def recover_from_backup(request, source, *, progress=None, verifier=None, idle_c
|
||||
installed = True
|
||||
record['retained_work'] = str(retained)
|
||||
emit('verify_target', '正在重新打开恢复后的目标工程并校验…')
|
||||
release_confirmed = False
|
||||
final = verifier(replace(request, lmc_file=library, evidence_dir=root/'target-verify',
|
||||
auto_repair=False, native_lm_verify=False, interactive_input=False),
|
||||
progress=progress, flag_reader=read_library_flag_if_available)
|
||||
release_confirmed = final.safe_to_continue
|
||||
if final.status == 'PASS' and (final.library_flag != 'GREEN' or not final.safe_to_continue):
|
||||
final = replace(final, status='FAIL', stderr='目标工程恢复后的 Ready 状态未确认。')
|
||||
if final.status != 'PASS':
|
||||
final = replace(final, stderr=(final.stderr + '\n原工程和完整库副本已保留,请查看恢复记录。').strip())
|
||||
final = replace(final, stderr=(final.stderr + '\n原 Work 已改名保留;应用未创建完整库备份,请查看恢复记录并使用手动备份。').strip())
|
||||
return save(final)
|
||||
except Exception as error:
|
||||
return save(VerifyResult('FAIL' if installed else 'BLOCKED', stderr=str(error),
|
||||
safe_to_continue=False))
|
||||
safe_to_continue=release_confirmed))
|
||||
finally:
|
||||
if acquired:
|
||||
win32event.ReleaseMutex(mutex)
|
||||
mutex.Close()
|
||||
pythoncom.CoUninitialize()
|
||||
try:
|
||||
if library_lock is not None:
|
||||
library_lock.__exit__(None, None, None)
|
||||
finally:
|
||||
if acquired:
|
||||
win32event.ReleaseMutex(mutex)
|
||||
mutex.Close()
|
||||
uninitialize_com(initialized)
|
||||
Reference in new issue
Block a user