fix: prevent iCDB disconnects and recover failed projects

This commit is contained in:
阿白叔 committed 2026-10-27 17:51:53 +08:00
1 parent 8a517d6f38
commit 2490067b2d
19 files changed
+1117 -60

No files matched your search

+55 -33
View File
@@ -62,6 +62,7 @@ class VerifyRequest:
# it before launching Library Manager/PCB.
mapped_drive: str = ''
mapped_remote_root: str = ''
auto_repair: bool = True
@dataclass(frozen=True)
@@ -80,6 +81,7 @@ class VerifyResult:
bridge_attempts: tuple[dict, ...] = ()
timings_seconds: dict[str, float] = field(default_factory=dict)
incomplete_timing_phases: tuple[str, ...] = ()
recovery_attempts: tuple[dict, ...] = ()
def resolve_importer(mentor_bin: str | None = None) -> Path:
@@ -198,38 +200,18 @@ def preflight_skip_reason(lmc_file, block_name):
return ''
def _run_process(command, timeout_seconds, cwd):
"""Run the importer, draining both pipes while it works (no pipe deadlock)."""
process = subprocess.Popen(command, cwd=str(cwd), stdout=subprocess.PIPE, stderr=subprocess.PIPE,
creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0))
try:
stdout, stderr = process.communicate(timeout=timeout_seconds)
return process.returncode, stdout.decode('utf-8', errors='replace'), stderr.decode('utf-8', errors='replace'), False
except subprocess.TimeoutExpired:
# A timed-out importer may have spawned a child that still owns the
# pipes. Bound both tree termination and the final drain so a hung
# helper cannot turn a 30-second item timeout into an unbounded wait.
try:
subprocess.run([str(Path(os.environ.get('WINDIR', r'C:\Windows'))/'System32'/'taskkill.exe'), '/PID', str(process.pid), '/T', '/F'],
capture_output=True, timeout=5,
creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0))
except (OSError, subprocess.TimeoutExpired):
pass
try:
process.kill()
except OSError:
pass
try:
stdout, stderr = process.communicate(timeout=5)
except subprocess.TimeoutExpired:
stdout, stderr = b'', b''
return None, stdout.decode('utf-8', errors='replace'), stderr.decode('utf-8', errors='replace'), True
def _run_process(command, timeout_seconds, cwd, *, evidence_root=None):
from .content_check import run_content_check
return run_content_check(command, timeout_seconds, cwd, evidence_root=evidence_root)
def _stop_worker(process, *, timeout=5):
"""Stop automation clients; native database owners are preserved."""
try:
process.kill()
if hasattr(process, 'request_stop'):
process.request_stop()
else:
process.kill()
except Exception:
pass
try:
@@ -532,10 +514,33 @@ def run_verify(request, *, progress=None, flag_reader=None, process_runner=None,
if not acquired:
return VerifyResult('BLOCKED', stderr='已有 CBB 校验任务运行,请等待结束。',
safe_to_continue=False)
return _run_verify_serialized(
result = _run_verify_serialized(
request, progress=progress, flag_reader=flag_reader,
process_runner=process_runner, port_check=port_check,
dialog_supervisor_factory=dialog_supervisor_factory)
if (request.auto_repair and result.status not in {'TIMEOUT', 'BLOCKED'}
and result.error_category == 'ICDB_REPAIR_REQUIRED'
and result.evidence_path):
from .native_repair import attempt_recovery
try:
diagnosis = json.loads((result.evidence_path.parent/'diagnostics/icdb-recovery.json').read_text('utf-8'))
original = result
recovery = attempt_recovery(request, diagnosis, result.evidence_path.parent, progress=progress)
recovery = {**recovery, 'original_error': original.stderr,
'original_evidence': str(original.evidence_path)}
if recovery.get('status') == 'REPAIRED':
result = _run_verify_serialized(
replace(request, auto_repair=False), progress=progress, flag_reader=flag_reader,
process_runner=process_runner, port_check=port_check,
dialog_supervisor_factory=dialog_supervisor_factory)
result = replace(result, recovery_attempts=(recovery,))
result.evidence_path.write_text(json.dumps({'block_name': request.block_name, **asdict(result)},
ensure_ascii=False, default=str, indent=2), encoding='utf-8')
except Exception as error:
result = replace(result, status='FAIL' if result.status == 'PASS' else result.status,
safe_to_continue=False,
stderr=(result.stderr+f'\nREPAIR_UNCONFIRMED: {error}').strip())
return result
finally:
if acquired:
win32event.ReleaseMutex(mutex)
@@ -630,7 +635,8 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
progress({'stage': 'runtime_fingerprint', 'block': request.block_name,
**fingerprint})
result_path = root/'result.json'
runner = process_runner or _run_process
runner = process_runner or (lambda command, timeout, cwd:
_run_process(command, timeout, cwd, evidence_root=root))
def finish(result):
# Only reclaim auxiliary backups after confirmed success. Failed runs
@@ -652,6 +658,17 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
finally:
timing.end('preflight')
from .icdb_ownership import unreleased_addresses
try:
addresses = unreleased_addresses(request.lmc_file, project, pcb)
if addresses:
return finish(VerifyResult('BLOCKED', safe_to_continue=False,
stderr='ICDB_SESSION_UNCONFIRMED: 原生数据库所有权未释放,未开始内容检查或校验:'
+ '; '.join(addresses)))
except OSError as error:
return finish(VerifyResult('BLOCKED', safe_to_continue=False,
stderr=f'ICDB_SESSION_UNCONFIRMED: 无法确认数据库所有权:{error}'))
content_check_enabled = bool(str(request.libspec).strip() and str(request.dms_login_config).strip())
if content_check_enabled:
try:
@@ -679,7 +696,8 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
# A contents failure or an unusable DMS must block before touching the PCB.
return finish(VerifyResult(status if status in ('FAIL', 'TIMEOUT') else 'BLOCKED',
stderr=combined.strip() or f'内容检查结果未知(退出码 {exit_code})',
stdout=stdout, report_path=report, content_check_exit_code=exit_code))
stdout=stdout, report_path=report, content_check_exit_code=exit_code,
safe_to_continue=not timed_out))
if progress:
progress({'stage': 'content_check_done', 'block': request.block_name, 'status': 'PASS'})
@@ -703,6 +721,7 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
'interactive_input': bool(request.interactive_input),
'native_lm_verify': bool(request.native_lm_verify),
'desktop': 'CbbVerify_' + uuid4().hex[:12],
'cancel_signal': str(root/'cancel-worker.signal'),
'start_gate': str(root/'start-worker.signal')}
job_path = root/'request.json'
job_path.write_text(json.dumps(job, ensure_ascii=False), encoding='utf-8')
@@ -733,6 +752,8 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
worker_command(job_path), None, interactive_input=True)
else:
process = DesktopWorker(worker_command(job_path), job['desktop'])
if hasattr(process, 'bind_cancellation'):
process.bind_cancellation(job['cancel_signal'])
deadline = ActivityDeadline(request.timeout_seconds)
last_activity_key = None
phase = DialogPhase.PCB_STARTING
@@ -917,10 +938,11 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
except Exception as error:
release_result = {'safe_to_continue': False, 'error': str(error)}
try:
address = Path(project).parent / 'database/cdbsvr/sAddress.adr'
if address.exists():
from .icdb_ownership import unreleased_addresses
addresses = unreleased_addresses(request.lmc_file, project, pcb)
if addresses:
release_result = {**(release_result or {}), 'safe_to_continue': False,
'icdb_address': str(address)}
'icdb_address': addresses[0], 'icdb_addresses': addresses}
except OSError as error:
close_errors.append(str(error))
if close_errors: