fix: prevent iCDB disconnects and recover failed projects
This commit is contained in:
1 parent
8a517d6f38
commit
2490067b2d
19 files changed
+1117
-60
No files matched your search
@@ -0,0 +1,182 @@
|
||||
"""Backed-up, single-attempt recovery through the installed native tool."""
|
||||
from dataclasses import dataclass
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from uuid import uuid4
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class RepairTarget:
|
||||
project: Path
|
||||
database: Path
|
||||
|
||||
|
||||
def select_repair_target(request, diagnosis):
|
||||
from .verify_runner import preflight
|
||||
if diagnosis.get('error_code') != 'ICDB_REPAIR_REQUIRED' or not diagnosis.get('session'):
|
||||
raise ValueError('REPAIR_TARGET_UNCONFIRMED: 缺少原生失联会话信息')
|
||||
if diagnosis.get('scope') == 'central_library':
|
||||
raise ValueError('SHARED_DATABASE_REPAIR_UNSUPPORTED: 当前原生 Repair 入口要求 PRJ,不能改修无关的 Work 工程')
|
||||
project, pcb = preflight(request)
|
||||
try:
|
||||
reported = Path(diagnosis.get('database_path', '')).resolve(strict=True)
|
||||
except OSError as error:
|
||||
raise ValueError(f'REPAIR_TARGET_UNCONFIRMED: 报错数据库路径不可用:{error}') from error
|
||||
for candidate in (project, pcb.parent/'pcb.prj'):
|
||||
database = candidate.parent/'database'
|
||||
if (candidate.is_file() and database.resolve() == reported
|
||||
and reported.is_relative_to(project.parent.resolve())):
|
||||
if not (reported/'icdb.dat').is_file():
|
||||
raise ValueError('REPAIR_TARGET_UNCONFIRMED: 未找到目标 icdb.dat')
|
||||
return RepairTarget(candidate.resolve(), reported)
|
||||
raise ValueError('REPAIR_TARGET_UNCONFIRMED: 报错数据库不属于本次工程,未猜测或改写路径')
|
||||
|
||||
|
||||
def _hash(path):
|
||||
digest = hashlib.sha256()
|
||||
with path.open('rb') as stream:
|
||||
for chunk in iter(lambda: stream.read(1024*1024), b''):
|
||||
digest.update(chunk)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def backup_project(target, destination):
|
||||
"""Keep every original file, holding icdb.dat exclusively during the copy."""
|
||||
import win32con, win32file, pywintypes
|
||||
source = target.project.parent.resolve()
|
||||
destination = Path(destination).resolve()
|
||||
if destination.is_relative_to(source) or source.is_relative_to(destination):
|
||||
raise ValueError('REPAIR_BACKUP_INVALID: 备份与源工程不能相互包含')
|
||||
paths = list(source.rglob('*'))
|
||||
if any(path.is_symlink() or path.is_junction() for path in paths):
|
||||
raise ValueError('REPAIR_BACKUP_INVALID: 工程包含目录链接,不能完整备份')
|
||||
if (source/'backup-manifest.json').exists():
|
||||
raise ValueError('REPAIR_BACKUP_INVALID: 原工程含同名备份清单')
|
||||
database_file = target.database/'icdb.dat'
|
||||
try:
|
||||
handle = win32file.CreateFile(str(database_file), win32con.GENERIC_READ, 0, None,
|
||||
win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None)
|
||||
except pywintypes.error as error:
|
||||
raise OSError(f'REPAIR_DATABASE_IN_USE: 无法独占读取数据库:{error}') from error
|
||||
try:
|
||||
destination.mkdir(parents=True, exist_ok=False)
|
||||
files = {}
|
||||
for path in paths:
|
||||
relative = path.relative_to(source)
|
||||
copied = destination/relative
|
||||
if path.is_dir():
|
||||
copied.mkdir(parents=True, exist_ok=True)
|
||||
continue
|
||||
before = path.stat()
|
||||
copied.parent.mkdir(parents=True, exist_ok=True)
|
||||
if path == database_file:
|
||||
with copied.open('wb') as stream:
|
||||
while True:
|
||||
try:
|
||||
_, data = win32file.ReadFile(handle, 1024*1024)
|
||||
except pywintypes.error as error:
|
||||
if error.winerror == 38: # ERROR_HANDLE_EOF
|
||||
break
|
||||
raise
|
||||
if not data:
|
||||
break
|
||||
stream.write(data)
|
||||
os.utime(copied, ns=(before.st_atime_ns, before.st_mtime_ns))
|
||||
digest = _hash(copied)
|
||||
else:
|
||||
digest = _hash(path)
|
||||
shutil.copy2(path, copied)
|
||||
if _hash(copied) != digest:
|
||||
raise OSError(f'REPAIR_BACKUP_CHANGED: 文件副本校验失败:{path}')
|
||||
after = path.stat()
|
||||
if (before.st_size, before.st_mtime_ns) != (after.st_size, after.st_mtime_ns):
|
||||
raise OSError(f'REPAIR_BACKUP_CHANGED: 备份期间源文件变化:{path}')
|
||||
files[str(relative)] = {'size': before.st_size, 'sha256': digest}
|
||||
record = {'complete': True, 'source': str(source), 'files': files}
|
||||
(destination/'backup-manifest.json').write_text(json.dumps(record, ensure_ascii=False, indent=2),
|
||||
encoding='utf-8')
|
||||
return record
|
||||
finally:
|
||||
handle.Close()
|
||||
|
||||
|
||||
def attempt_recovery(request, diagnosis, evidence_root, *, progress=None):
|
||||
root = Path(evidence_root)/'native-repair'
|
||||
root.mkdir(exist_ok=True)
|
||||
marker = root/'attempt.json'
|
||||
if marker.exists():
|
||||
return {'status': 'BLOCKED', 'detail': 'REPAIR_ALREADY_ATTEMPTED', 'evidence': str(root)}
|
||||
record = {'status': 'BLOCKED', 'evidence': str(root)}
|
||||
try:
|
||||
process_record = Path(evidence_root)/'content-check-process.json'
|
||||
if process_record.is_file():
|
||||
state = json.loads(process_record.read_text('utf-8')).get('status')
|
||||
if state in {'RUNNING', 'RETAINED'}:
|
||||
raise ValueError('IMPORTER_RELEASE_UNCONFIRMED: 内容检查客户端仍占有数据库,未尝试 Repair')
|
||||
with marker.open('x', encoding='utf-8') as stream:
|
||||
json.dump({'status': 'PREPARING', 'diagnosis': diagnosis}, stream, ensure_ascii=False)
|
||||
target = select_repair_target(request, diagnosis)
|
||||
if progress:
|
||||
progress({'stage': 'native_repair_start', 'block': request.block_name,
|
||||
'detail': '正在备份并尝试原生数据库修复', 'project': str(target.project)})
|
||||
from .mentor_adapter import pcb_processes, _process_details
|
||||
if pcb_processes() or _process_details('LibraryManager.exe'):
|
||||
raise ValueError('REPAIR_DATABASE_IN_USE: 原生 PCB/Library Manager 会话尚未退出')
|
||||
for _pid, _exe, command, _parent in _process_details('cscript.exe'):
|
||||
if str(target.project).casefold() in str(command).casefold():
|
||||
raise ValueError('REPAIR_DATABASE_IN_USE: 目标的保存/关闭助手尚未退出')
|
||||
callback = (lambda event: progress({'block': request.block_name, **event})) if progress else None
|
||||
record = run_native_repair(target, root, mentor_bin=request.mentor_bin,
|
||||
timeout_seconds=max(60, request.timeout_seconds), progress=callback)
|
||||
except Exception as error:
|
||||
record['detail'] = str(error)
|
||||
marker.write_text(json.dumps(record, ensure_ascii=False, indent=2), encoding='utf-8')
|
||||
return record
|
||||
|
||||
|
||||
def run_native_repair(target, root, *, mentor_bin='', timeout_seconds=300, progress=None):
|
||||
"""Supervise the GUI on its own desktop; a repair timeout never kills it."""
|
||||
from .desktop_worker import DesktopWorker
|
||||
root = Path(root)
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
job_path = root/'repair-request.json'
|
||||
cancel = root/'cancel-repair.signal'
|
||||
job_path.write_text(json.dumps({'project': str(target.project), 'database': str(target.database),
|
||||
'root': str(root), 'mentor_bin': str(mentor_bin or ''), 'timeout': timeout_seconds,
|
||||
'cancel_signal': str(cancel), 'supervisor_pid': os.getpid()}, ensure_ascii=False), encoding='utf-8')
|
||||
command = ([sys.executable] if getattr(sys, 'frozen', False) else
|
||||
[sys.executable, '-m', 'cbb_refresh_verify']) + ['--repair-worker', str(job_path)]
|
||||
desktop = 'CbbRepair_'+uuid4().hex[:12]
|
||||
worker = DesktopWorker(command, desktop)
|
||||
worker.bind_cancellation(cancel)
|
||||
deadline = time.monotonic()+max(1, float(timeout_seconds))+5
|
||||
event_count = 0
|
||||
try:
|
||||
while worker.poll() is None and time.monotonic()<deadline:
|
||||
event_file = root/'repair-events.jsonl'
|
||||
if progress and event_file.is_file():
|
||||
lines = event_file.read_text('utf-8').splitlines()
|
||||
for line in lines[event_count:]:
|
||||
try:
|
||||
progress(json.loads(line))
|
||||
except json.JSONDecodeError:
|
||||
break
|
||||
event_count += 1
|
||||
time.sleep(.2)
|
||||
outcome = root/'repair-result.json'
|
||||
if worker.poll() is None or not outcome.is_file():
|
||||
worker.request_stop()
|
||||
return {'status': 'RETAINED', 'worker_pid': worker.pid, 'desktop': desktop,
|
||||
'detail': '原生修复尚未确认结束,保留操作并停止批次', 'evidence': str(root)}
|
||||
result = json.loads(outcome.read_text('utf-8'))
|
||||
if worker.returncode != 0 and result.get('status') == 'REPAIRED':
|
||||
result['status'] = 'UNCONFIRMED'
|
||||
return {**result, 'evidence': str(root)}
|
||||
finally:
|
||||
worker.close()
|
||||
Reference in new issue
Block a user