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

+4
View File
@@ -46,6 +46,7 @@ def resolve_data_root(cli_value: Path | None) -> Path:
def main(argv: Sequence[str] | None = None) -> int:
parser = argparse.ArgumentParser(prog="CbbRefreshVerify")
parser.add_argument('--verify-worker', type=Path, help=argparse.SUPPRESS)
parser.add_argument('--repair-worker', type=Path, help=argparse.SUPPRESS)
parser.add_argument('--dialog-agent', type=Path, help=argparse.SUPPRESS)
parser.add_argument('--collect-failure-logs', type=Path, help=argparse.SUPPRESS)
parser.add_argument('--batch-lmc', type=Path, help=argparse.SUPPRESS)
@@ -55,6 +56,9 @@ def main(argv: Sequence[str] | None = None) -> int:
parser.add_argument('--mentor-bin', default='', help=argparse.SUPPRESS)
parser.add_argument("--smoke-test", action="store_true", help=argparse.SUPPRESS); parser.add_argument("--data-root", type=Path, help=argparse.SUPPRESS)
args = parser.parse_args(list(argv) if argv is not None else None)
if args.repair_worker:
from .native_repair_ui import repair_worker_main
return repair_worker_main(args.repair_worker)
if args.collect_failure_logs:
from .verify_diagnostics import failure_logs_main
return failure_logs_main(args.collect_failure_logs)
@@ -0,0 +1,29 @@
Option Explicit
Dim app, doc, pi, licensing, token, closed, remaining
Set app = GetObject(, "MGCPCB.Application")
Set doc = app.ActiveDocument
If doc Is Nothing Then WScript.Quit 3
Set pi = doc.ProjectIntegration
If LCase(pi.ProjectFile) <> LCase(WScript.Arguments(0)) Then WScript.Quit 2
If LCase(doc.Name) <> LCase(WScript.Arguments(1)) Then WScript.Quit 2
Set pi = Nothing
WScript.Echo "FAILURE_IDENTITY_OK"
Set licensing = CreateObject("MGCPCBAutomationLicensing.Application")
token = licensing.GetToken(doc.Validate(0))
doc.Validate token
WScript.Echo "FAILURE_CLOSE_START"
closed = doc.Close(False)
If Not closed Then WScript.Quit 4
WScript.Echo "FAILURE_CLOSE_OK"
Set doc = Nothing
Set licensing = Nothing
Set remaining = app.ActiveDocument
If Not remaining Is Nothing Then
Set remaining = Nothing
WScript.Echo "FAILURE_APP_RETAINED"
WScript.Quit 5
End If
Set remaining = Nothing
app.Quit
WScript.Echo "FAILURE_QUIT_OK"
Set app = Nothing
+46
View File
@@ -0,0 +1,46 @@
"""Run the native importer without aborting database owners on timeout."""
import json
import os
from pathlib import Path
import subprocess
import tempfile
import threading
def run_content_check(command, timeout_seconds, cwd, *, evidence_root=None):
root = (Path(evidence_root) if evidence_root is not None else
Path(tempfile.mkdtemp(prefix='cbb-content-check-')))
root.mkdir(parents=True, exist_ok=True)
stdout_path, stderr_path = root/'content-check.stdout.log', root/'content-check.stderr.log'
record_path = root/'content-check-process.json'
with stdout_path.open('wb') as stdout, stderr_path.open('wb') as stderr:
process = subprocess.Popen(command, cwd=str(cwd), stdout=stdout, stderr=stderr,
creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0))
record = {'pid': process.pid, 'command': list(command), 'cwd': str(cwd),
'stdout': str(stdout_path), 'stderr': str(stderr_path)}
def save_record(**fields):
try:
record_path.write_text(json.dumps({**record, **fields}, ensure_ascii=False, indent=2),
encoding='utf-8')
except OSError:
pass
save_record(status='RUNNING')
try:
process.wait(timeout=max(.1, float(timeout_seconds)))
except subprocess.TimeoutExpired:
# Never kill this client or its descendants. The importer can own the
# shared symbol database even though contents checking sounds read-only.
# Files avoid pipe backpressure/BrokenPipe if the supervisor exits.
save_record(status='RETAINED', safe_to_continue=False)
def observe_exit():
process.wait()
save_record(status='EXITED', returncode=process.returncode,
note='Importer exit alone does not prove native database release.')
threading.Thread(target=observe_exit, name='retained-content-check', daemon=True).start()
return (None, stdout_path.read_bytes().decode('utf-8', errors='replace'),
stderr_path.read_bytes().decode('utf-8', errors='replace') +
f'\nIMPORTER_RELEASE_UNCONFIRMED: pid={process.pid}; '
f'内容检查超时,保留原生操作并停止批次;进程记录:{record_path}', True)
save_record(status='EXITED', returncode=process.returncode)
return (process.returncode, stdout_path.read_bytes().decode('utf-8', errors='replace'),
stderr_path.read_bytes().decode('utf-8', errors='replace'), False)
+20 -3
View File
@@ -1,6 +1,7 @@
"""Launch automation on a private Windows desktop, never the input desktop."""
import subprocess
import os
from pathlib import Path
import threading
import win32con
import win32event
@@ -21,7 +22,7 @@ def launch_save_helper(command, **kwargs):
return helper
def start_supervisor_watchdog(supervisor_pid):
def start_supervisor_watchdog(supervisor_pid, *, cancel_path=None):
"""A crashed supervisor must not leave unsupervised automation writing.
Stop only this Python worker and its registered automation clients. Native
@@ -33,6 +34,11 @@ def start_supervisor_watchdog(supervisor_pid):
def watch():
try:
win32event.WaitForSingleObject(parent, win32event.INFINITE)
if cancel_path is not None:
# Let native calls finish before the worker closes its exact
# document. Killing a pending automation client can abandon it.
Path(cancel_path).touch()
return
with _automation_clients_lock:
for helper in _automation_clients:
try:
@@ -42,7 +48,8 @@ def start_supervisor_watchdog(supervisor_pid):
pass
finally:
parent.Close()
os._exit(75)
if cancel_path is None:
os._exit(75)
thread = threading.Thread(target=watch, name='supervisor-watchdog', daemon=True)
thread.start()
@@ -139,6 +146,16 @@ class DesktopWorker:
except Exception:
pass
def bind_cancellation(self, path):
self.cancel_path = Path(path)
def request_stop(self):
if not hasattr(self, 'cancel_path'):
# Compatibility for diagnostic workers without the Verify protocol.
self.kill()
return
self.cancel_path.touch()
def wait(self, timeout=5):
if win32event.WaitForSingleObject(self.handle, int(timeout*1000)) != win32con.WAIT_OBJECT_0:
raise TimeoutError('Automation worker did not exit')
@@ -148,7 +165,7 @@ class DesktopWorker:
# Releasing Python resources must not kill native database owners.
try:
if self.poll() is None:
self.kill()
self.request_stop()
except Exception:
pass
for companion in self.companions:
+30
View File
@@ -0,0 +1,30 @@
"""Close only an idle document whose native identity was already established."""
import json
import os
from pathlib import Path
import time
def close_failed_document(job, *, emit=lambda **event: None, timeout_seconds=30):
from .desktop_worker import launch_save_helper
root = Path(job['root'])
log_path = root/'failure-close.log'
command = [str(Path(os.environ.get('WINDIR', r'C:\Windows'))/'SysWOW64/cscript.exe'),
'//nologo', str(Path(__file__).with_name('close_failed_block.vbs')),
job['project'], Path(job['pcb']).name]
with log_path.open('w', encoding='utf-8') as log:
process = launch_save_helper(command, stdout=log, stderr=log)
emit(stage='failure_close_started', helper_pid=process.pid)
deadline = time.monotonic()+max(.1, float(timeout_seconds))
while process.poll() is None and time.monotonic() < deadline:
time.sleep(.2)
# A slow native Close can still be flushing. Retain the helper as well as
# PCB/iCDB; never force it to abandon the native call at this deadline.
text = log_path.read_text('utf-8', errors='replace')
result = {'status': ('CLOSED' if process.poll() == 0 and
all(marker in text.splitlines() for marker in ('FAILURE_CLOSE_OK', 'FAILURE_QUIT_OK'))
else 'RETAINED' if process.poll() is None else 'UNCONFIRMED'),
'helper_pid': process.pid, 'returncode': process.poll(), 'log': str(log_path)}
(root/'failure-close.json').write_text(json.dumps(result, indent=2), encoding='utf-8')
emit(stage='failure_close_result', **result)
return result
+16
View File
@@ -0,0 +1,16 @@
"""Known native database owners touched by a CBB verification operation."""
from pathlib import Path
def database_directories(lmc_file, project, pcb):
return tuple(dict.fromkeys((
Path(project).parent/'database',
Path(pcb).parent/'database',
Path(lmc_file).parent/'SymbolLibs/__ReusableBlocksSymb',
)))
def unreleased_addresses(lmc_file, project, pcb):
return [str(path/'cdbsvr/sAddress.adr')
for path in database_directories(lmc_file, project, pcb)
if (path/'cdbsvr/sAddress.adr').exists()]
+28 -13
View File
@@ -633,12 +633,13 @@ def execute_job(job, emit):
emit(stage='backup_done', status=backup.get('status'), detail=backup.get('detail'))
# Backup is evidence only, never a prerequisite for launching PCB. Volatile
# database/log directories are intentionally excluded to avoid file locks.
icdb_address = prepare_icdb_address(
Path(job['project']).parent / 'database', root, emit=emit)
if icdb_address.get('status') != 'ABSENT':
raise RuntimeError(
'ICDB_SESSION_UNCONFIRMED: 数据库存在服务器地址记录,无法确认独占使用;'
'已保留地址文件,请先检查原 PCB/iCDB 会话。' + str(icdb_address))
from .icdb_ownership import database_directories, unreleased_addresses
for database in database_directories(job['lmc_file'], job['project'], job['pcb']):
icdb_address = prepare_icdb_address(database, root, emit=emit)
if icdb_address.get('status') != 'ABSENT':
raise RuntimeError(
'ICDB_SESSION_UNCONFIRMED: 数据库存在服务器地址记录,无法确认独占使用;'
'已保留地址文件,请先检查原 PCB/iCDB 会话。' + str(icdb_address))
from .verify_diagnostics import collect_preflight_diagnostics, collect_native_failure_logs
diagnostics = collect_preflight_diagnostics(job['pcb'], root)
emit(stage='preflight_diagnostics', non_blocking=True,
@@ -673,6 +674,8 @@ def execute_job(job, emit):
emit(stage='startup_log_baseline_unavailable', detail=str(error))
def native_error():
if job.get('cancel_signal') and Path(job['cancel_signal']).exists():
return 'VERIFY_CANCELLED: 停止后续操作并正常关闭目标文档'
# Inspect every source before returning a generic server/packager
# failure: either can be a consequence of a lost library session.
startup = pcb_log_reports_missing_server(job['pcb'], offset=pcb_log_offset)
@@ -689,6 +692,7 @@ def execute_job(job, emit):
worker_parent_pid = None
launcher_process = None
completed = False
identity_verified = False
helper = None
app = doc = pi = None
try:
@@ -730,6 +734,8 @@ def execute_job(job, emit):
pcb_deadline = reset_verify_activity_deadline(
0.0, time.monotonic(), timeout_seconds=pcb_startup_timeout_seconds(job['timeout']))
while time.monotonic() < pcb_deadline:
if job.get('cancel_signal') and Path(job['cancel_signal']).exists():
raise RuntimeError('VERIFY_CANCELLED: PCB 启动期间收到停止请求')
records = _process_details('ExpeditionPCB.exe')
worker = select_reusable_circuit_worker(
records,
@@ -755,6 +761,7 @@ def execute_job(job, emit):
emit=emit,
error_reader=native_error,
)
identity_verified = True
# Do not acquire MGCPCBAutomationLicensing from this 64-bit Python
# worker. EE7.9 registers that automation class for the 32-bit host;
# the old, working path acquires the token inside the SysWOW64
@@ -770,12 +777,15 @@ def execute_job(job, emit):
# references alive prevents the native PCB server from exiting cleanly.
pi = doc = app = None
gc.collect()
if job.get('cancel_signal') and Path(job['cancel_signal']).exists():
raise RuntimeError('VERIFY_CANCELLED: 未开始保存')
emit(stage='save_start')
script = Path(__file__).with_name('save_verified_block.vbs')
cscript = Path(os.environ.get('WINDIR', r'C:\Windows'))/'SysWOW64'/'cscript.exe'
from .desktop_worker import launch_save_helper
with (root/'save.log').open('w', encoding='utf-8') as log:
helper = launch_save_helper([str(cscript), '//nologo', str(script), job['project']],
helper = launch_save_helper([str(cscript), '//nologo', str(script), job['project'],
Path(job['pcb']).name, str(job.get('cancel_signal') or '')],
stdout=log, stderr=log, creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0))
emit(stage='save_helper', helper_pid=helper.pid)
last_markers = ()
@@ -814,9 +824,9 @@ def execute_job(job, emit):
baseline_pids=pcb_before, emit=emit)
if not released or not released.get('safe_to_continue'):
raise RuntimeError(f'PCB_RELEASE_UNCONFIRMED: 未确认 PCB 退出: {released}')
address = Path(job['project']).parent / 'database/cdbsvr/sAddress.adr'
if address.exists():
raise RuntimeError(f'ICDB_RELEASE_UNCONFIRMED: PCB 已退出但数据库地址记录仍存在;保留文件并停止批次: {address}')
addresses = unreleased_addresses(job['lmc_file'], job['project'], job['pcb'])
if addresses:
raise RuntimeError(f'ICDB_RELEASE_UNCONFIRMED: PCB 已退出但数据库地址记录仍存在;保留文件并停止批次: {addresses}')
cert_pcb = block_root/'Cert'/Path(job['pcb']).relative_to(block_root/'Work')
cert_evidence = collect_cert_evidence(block_root, cert_project, cert_pcb)
emit(stage='cert_diagnostics', **cert_evidence)
@@ -836,8 +846,13 @@ def execute_job(job, emit):
# Diagnostic failure must not erase the native error or cleanup.
pass
if helper is not None and helper.poll() is None:
# Stop only the automation client, never a native database tree.
helper.terminate()
emit(stage='save_helper_retained', helper_pid=helper.pid)
elif not completed and identity_verified:
try:
from .failed_session import close_failed_document
close_failed_document(job, emit=emit)
except Exception as error:
emit(stage='failure_close_unconfirmed', detail=str(error))
cleanup_verify_processes(
lm_pid,
worker_pid,
@@ -924,7 +939,7 @@ def worker_main(request_path):
try:
if job.get('supervisor_pid'):
from .desktop_worker import start_supervisor_watchdog
start_supervisor_watchdog(job['supervisor_pid'])
start_supervisor_watchdog(job['supervisor_pid'], cancel_path=job.get('cancel_signal'))
start_gate = Path(job.get('start_gate', '')) if job.get('start_gate') else None
if start_gate is not None:
gate_deadline = time.monotonic() + 15
+182
View File
@@ -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()
+193
View File
@@ -0,0 +1,193 @@
"""Drive the installed Project Backup Repair command on a private desktop."""
import ctypes
from ctypes import wintypes
import json
import ntpath
from pathlib import Path
import re
import subprocess
import time
import zipfile
def confirmation_allowed(main_title, project, text):
title = main_title.removeprefix('iCDB Project Backup - ')
if ntpath.normcase(ntpath.normpath(title)) != ntpath.normcase(ntpath.normpath(str(project))):
return False
normalized = ' '.join(text.casefold().split())
return all(marker in normalized for marker in (
'the project content will be validated and repaired if necessary.',
'a project backup will be created before any action take place.',
'you will be able to revert all changes using that backup.'))
def repair_completed(diagnostic_text, database_text, *, native_backup):
combined = diagnostic_text+'\n'+database_text
if re.search(r'\bERROR\s*:|not repaired|repair.*failed', combined, re.IGNORECASE):
return False
return bool(native_backup and 'Diagnostic: FINISH' in diagnostic_text
and ('Diagnostic: Snapshot:' in diagnostic_text or 'Diagnostic: START' in diagnostic_text)
and 'iCDBProjectBackupRepair' in database_text and 'IC: Closing project' in database_text)
def _repair_command(executable):
import win32api, win32gui, win32con
user32 = ctypes.WinDLL('user32')
user32.GetMenuStringW.argtypes = [wintypes.HMENU, wintypes.UINT, wintypes.LPWSTR,
ctypes.c_int, wintypes.UINT]
library = win32api.LoadLibraryEx(str(executable), 0, 2) # data resources only
commands = set()
def walk(menu, parents=()):
for index in range(win32gui.GetMenuItemCount(menu)):
value = ctypes.create_unicode_buffer(512)
user32.GetMenuStringW(menu, index, value, len(value), win32con.MF_BYPOSITION)
label = value.value.replace('&', '').split('\t')[0].strip().casefold()
sub = win32gui.GetSubMenu(menu, index)
if sub:
walk(sub, (*parents, label))
elif parents == ('project',) and label == 'repair':
commands.add(win32gui.GetMenuItemID(menu, index))
try:
for name in win32api.EnumResourceNames(library, 4):
menu = win32gui.LoadMenu(library, name)
try:
walk(menu)
finally:
win32gui.DestroyMenu(menu)
finally:
win32api.FreeLibrary(library)
if len(commands) != 1:
raise ValueError('NATIVE_REPAIR_UNSUPPORTED: 未唯一定位原生 Project/Repair 菜单')
return commands.pop()
def _windows(pid):
import win32gui, win32process
windows = []
def observe(hwnd, _):
if win32process.GetWindowThreadProcessId(hwnd)[1] != pid or not win32gui.IsWindowVisible(hwnd):
return
children = []
def child(handle, _):
if win32gui.IsWindowVisible(handle):
children.append({'hwnd': handle, 'text': win32gui.GetWindowText(handle),
'class': win32gui.GetClassName(handle), 'id': win32gui.GetDlgCtrlID(handle),
'enabled': bool(win32gui.IsWindowEnabled(handle))})
win32gui.EnumChildWindows(hwnd, child, None)
windows.append({'hwnd': hwnd, 'title': win32gui.GetWindowText(hwnd),
'class': win32gui.GetClassName(hwnd), 'enabled': bool(win32gui.IsWindowEnabled(hwnd)),
'children': children})
win32gui.EnumWindows(observe, None)
return windows
def _native_evidence(project, database, pid, started_ns, baseline):
"""Use only this native process's new diagnostic/close and backup evidence."""
def read_logs(folder):
text = []
for path in (database/'cdbsvr'/folder).glob(f'*-{pid}/*.txt'):
if path.stat().st_mtime_ns >= started_ns:
text.append(path.read_bytes()[-256*1024:].decode('utf-8', errors='replace'))
return '\n'.join(text)
from .icdb_recovery import read_log_failure
backup_log = project.parent/'Log Files/ProjectBackupLog.txt'
text, _ = read_log_failure(backup_log, baseline)
matches = re.findall(r'Successfully created \[Project Repair\] backup \[([^\]]+)\]', text)
native_backup = False
for name in matches:
# Native default storage verified here; alternate storage needs its own
# target/backup validation and must not silently become success.
if Path(name).name != name:
continue
archive = project.parent/'ProjectBackup/backups'/name
if archive.is_file():
with zipfile.ZipFile(archive) as zipped:
native_backup = bool(zipped.namelist()) and zipped.testzip() is None
diagnostic, db_log = read_logs('dbcheck'), read_logs('log')
valid = (str(database).casefold() in db_log.casefold()
and repair_completed(diagnostic, db_log, native_backup=native_backup))
return {'confirmed': bool(valid), 'native_backup': native_backup,
'diagnostic_tail': diagnostic[-8192:], 'database_tail': db_log[-8192:]}
def repair_worker_main(job_path):
import win32con, win32gui
from .native_repair import RepairTarget, backup_project
from .mentor_paths import discover_sdd_home
from .icdb_recovery import snapshot_log
job = json.loads(Path(job_path).read_text('utf-8'))
root = Path(job['root'])
project, database = Path(job['project']), Path(job['database'])
result = {'status': 'BLOCKED', 'project': str(project), 'database': str(database)}
process = None
def emit(**event):
with (root/'repair-events.jsonl').open('a', encoding='utf-8') as stream:
stream.write(json.dumps(event, ensure_ascii=False)+'\n')
try:
if project.suffix.casefold() != '.prj' or database.resolve() != (project.parent/'database').resolve():
raise ValueError('REPAIR_TARGET_UNCONFIRMED')
home = discover_sdd_home(job.get('mentor_bin'))
if home is None:
raise ValueError('NATIVE_REPAIR_UNAVAILABLE: 未找到 Mentor 安装目录')
executable = home/'iCDB/win32/bin/iCDBProjectBackup.exe'
command_id = _repair_command(executable)
from .mentor_adapter import pcb_processes, _process_details
if pcb_processes() or _process_details('LibraryManager.exe'):
raise ValueError('REPAIR_DATABASE_IN_USE')
backup_project(RepairTarget(project, database), root/'complete-backup')
emit(stage='complete_backup_verified', path=str(root/'complete-backup'))
if Path(job['cancel_signal']).exists():
raise ValueError('REPAIR_CANCELLED_AFTER_BACKUP')
baseline = snapshot_log(project.parent/'Log Files/ProjectBackupLog.txt')
started_ns = time.time_ns()
if job.get('supervisor_pid'):
from .desktop_worker import start_supervisor_watchdog
start_supervisor_watchdog(job['supervisor_pid'], cancel_path=job['cancel_signal'])
process = subprocess.Popen([str(executable), '-p', str(project)], cwd=str(project.parent))
result['native_pid'] = process.pid
emit(stage='native_started', pid=process.pid, project=str(project))
deadline = time.monotonic()+max(1, float(job['timeout']))
invoked = confirmed = closing = False
evidence = None
while process.poll() is None and time.monotonic()<deadline:
windows = _windows(process.pid)
main = next((w for w in windows if w['class'].startswith('Afx:')
and w['title'].casefold() == ('iCDB Project Backup - '+str(project)).casefold()), None)
dialogs = [w for w in windows if w['class'] == '#32770']
if not invoked and main and not dialogs and main['enabled']:
if Path(job['cancel_signal']).exists():
raise ValueError('REPAIR_CANCELLED_BEFORE_START')
win32gui.PostMessage(main['hwnd'], 0x0111, command_id, 0)
invoked = True
emit(stage='native_repair_requested', command=command_id)
if invoked and not confirmed and main:
for dialog in dialogs:
text = '\n'.join(c['text'] for c in dialog['children'])
if confirmation_allowed(main['title'], project, text):
if Path(job['cancel_signal']).exists():
raise ValueError('REPAIR_CANCELLED_BEFORE_CONFIRM')
button = next((c for c in dialog['children'] if c['class'] == 'Button'
and c['id'] == 1 and c['enabled']), None)
if button:
win32gui.PostMessage(button['hwnd'], win32con.BM_CLICK, 0, 0)
confirmed = True
emit(stage='native_repair_confirmed', text=text)
if confirmed and not closing and main and not dialogs and main['enabled']:
evidence = _native_evidence(project, database, process.pid, started_ns, baseline)
if evidence['confirmed']:
win32gui.PostMessage(main['hwnd'], win32con.WM_CLOSE, 0, 0)
closing = True
emit(stage='native_repair_finished', **evidence)
time.sleep(.2)
if (closing and process.poll() == 0 and evidence and evidence['confirmed']
and not (database/'cdbsvr/sAddress.adr').exists()):
result.update(status='REPAIRED', evidence=evidence)
else:
result.update(status='RETAINED' if process.poll() is None else 'UNCONFIRMED',
detail='原生 Repair 未取得完整成功/释放证据,未重试校验')
except Exception as error:
result.update(detail=str(error), status='RETAINED' if process and process.poll() is None else 'BLOCKED')
# Never terminate a repair or its database owner. Retained PID/desktop is
# reported to the parent, including unknown native prompts.
(root/'repair-result.json').write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding='utf-8')
return 0 if result['status'] == 'REPAIRED' else 1
@@ -5,8 +5,12 @@ Set app = GetObject(, "MGCPCB.Application")
Set doc = app.ActiveDocument
Set pi = doc.ProjectIntegration
If LCase(pi.ProjectFile) <> LCase(expected) Then WScript.Quit 2
If WScript.Arguments.Count > 1 Then
If LCase(doc.Name) <> LCase(WScript.Arguments(1)) Then WScript.Quit 2
End If
If pi.ForwardAnnotationStatus <> 2 Or pi.SynchCESStatus <> 2 Or pi.LoadCESStatus <> 2 Or pi.BackAnnotationStatus <> 2 Then WScript.Quit 3
WScript.Echo "VALIDATE_START"
CheckCancellation
measuredStart = Timer
Set licensing = CreateObject("MGCPCBAutomationLicensing.Application")
token = licensing.GetToken(doc.Validate(0))
@@ -14,11 +18,13 @@ doc.Validate token
LogElapsed "validate", measuredStart
WScript.Echo "LICENSE_OK"
WScript.Echo "SAVE_START"
CheckCancellation
measuredStart = Timer
operationOK = doc.Save()
LogElapsed "save", measuredStart
If Not operationOK Then WScript.Quit 4
WScript.Echo "SAVE_OK"
CheckCancellation
measuredStart = Timer
operationOK = doc.IsSaved()
LogElapsed "is_saved", measuredStart
@@ -40,6 +46,7 @@ If Not stable Then WScript.Quit 7
WScript.Echo "POST_SAVE_SYNCHRONIZED"
If Not doc.IsSaved() Then WScript.Quit 8
WScript.Echo "CLOSE_START"
CheckCancellation
measuredStart = Timer
operationOK = doc.Close(True)
LogElapsed "close", measuredStart
@@ -54,6 +61,18 @@ LogElapsed "quit", measuredStart
WScript.Echo "QUIT_OK"
Set app = Nothing
Sub CheckCancellation()
Dim fso, cancelPath
If WScript.Arguments.Count < 3 Then Exit Sub
cancelPath = WScript.Arguments(2)
If Len(cancelPath) = 0 Then Exit Sub
Set fso = CreateObject("Scripting.FileSystemObject")
If fso.FileExists(cancelPath) Then
WScript.Echo "VERIFY_CANCELLED"
WScript.Quit 9
End If
End Sub
Sub LogElapsed(phaseName, started)
Dim elapsed
elapsed = Timer - started
+9 -6
View File
@@ -315,15 +315,18 @@ class StatusBridgeServer:
except OSError:
pass
if process.poll() is None:
process.terminate()
try:
process.wait(timeout=2)
except subprocess.TimeoutExpired:
try:
process.kill()
except OSError:
pass
process.terminate()
try:
process.wait(timeout=2)
except subprocess.TimeoutExpired:
pass
try:
process.kill()
except OSError:
pass
try:
process.wait(timeout=2)
except subprocess.TimeoutExpired:
pass
+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: