fix: harden PCB and iCDB verification lifecycle for beta release
This commit is contained in:
1 parent
11a2b2e46e
commit
a11eb3c766
33 files changed
+1226
-267
No files matched your search
@@ -1 +1 @@
|
||||
__version__ = "0.1.0"
|
||||
__version__ = "0.2.2b1"
|
||||
@@ -98,7 +98,13 @@ def main(argv: Sequence[str] | None = None) -> int:
|
||||
mapped_remote_root=lease.remote_root,
|
||||
native_lm_verify=native_lm_verify_enabled())
|
||||
for name in names]
|
||||
results = run_batch(requests)
|
||||
try:
|
||||
results = run_batch(requests)
|
||||
except Exception:
|
||||
lease.retain_for_recovery()
|
||||
raise
|
||||
if any(not result.safe_to_continue for result in results):
|
||||
lease.retain_for_recovery()
|
||||
report = write_batch_report(requests, results, context.root/'reports')
|
||||
logger.info('batch_report path=%s', report)
|
||||
logger.info('failure_report path=%s', failure_report_path(report))
|
||||
|
||||
@@ -15,22 +15,18 @@
|
||||
{
|
||||
"rule_id": "database-restoration",
|
||||
"priority": 95,
|
||||
"category": "SAFE_RECOVERY",
|
||||
"category": "FATAL_ACK",
|
||||
"phases": ["PCB_STARTING", "DATABASE_RECOVERY", "DOCUMENT_ATTACH"],
|
||||
"semantic_any": ["database restoration", "last user saved database", "数据库恢复"],
|
||||
"action": "restore_last_saved",
|
||||
"channels": ["uia_select", "win32_button_click", "uia_invoke"],
|
||||
"postcondition": "window_gone"
|
||||
"error_code": "DATABASE_RECOVERY_REQUIRED"
|
||||
},
|
||||
{
|
||||
"rule_id": "open-lock-confirm",
|
||||
"priority": 90,
|
||||
"category": "SAFE_RECOVERY",
|
||||
"category": "FATAL_ACK",
|
||||
"phases": ["PCB_STARTING", "DOCUMENT_ATTACH"],
|
||||
"semantic_any": ["continue to open the design with read/write access permission", "confirm that no other users have the design open"],
|
||||
"action": "confirm_open_lock",
|
||||
"channels": ["win32_button_click", "uia_invoke"],
|
||||
"postcondition": "window_gone"
|
||||
"error_code": "DATABASE_RECOVERY_REQUIRED"
|
||||
},
|
||||
{
|
||||
"rule_id": "forward-annotation-confirm",
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
"""Launch automation on a private Windows desktop, never the input desktop."""
|
||||
import subprocess
|
||||
import os
|
||||
import threading
|
||||
import win32con
|
||||
import win32event
|
||||
import win32job
|
||||
@@ -7,6 +9,46 @@ import win32process
|
||||
import win32service
|
||||
|
||||
|
||||
_automation_clients = []
|
||||
_automation_clients_lock = threading.Lock()
|
||||
|
||||
|
||||
def launch_save_helper(command, **kwargs):
|
||||
"""Register the save client atomically with respect to supervisor loss."""
|
||||
with _automation_clients_lock:
|
||||
helper = subprocess.Popen(command, **kwargs)
|
||||
_automation_clients.append(helper)
|
||||
return helper
|
||||
|
||||
|
||||
def start_supervisor_watchdog(supervisor_pid):
|
||||
"""A crashed supervisor must not leave unsupervised automation writing.
|
||||
|
||||
Stop only this Python worker and its registered automation clients. Native
|
||||
database owners remain alive, including a COM call already in progress.
|
||||
"""
|
||||
import win32api
|
||||
parent = win32api.OpenProcess(win32con.SYNCHRONIZE, False, int(supervisor_pid))
|
||||
|
||||
def watch():
|
||||
try:
|
||||
win32event.WaitForSingleObject(parent, win32event.INFINITE)
|
||||
with _automation_clients_lock:
|
||||
for helper in _automation_clients:
|
||||
try:
|
||||
if helper.poll() is None:
|
||||
helper.terminate()
|
||||
except OSError:
|
||||
pass
|
||||
finally:
|
||||
parent.Close()
|
||||
os._exit(75)
|
||||
|
||||
thread = threading.Thread(target=watch, name='supervisor-watchdog', daemon=True)
|
||||
thread.start()
|
||||
return thread
|
||||
|
||||
|
||||
def startup_desktop_name(name, *, interactive_input=False):
|
||||
"""Return the CreateProcess desktop target for a worker.
|
||||
|
||||
@@ -25,8 +67,8 @@ class DesktopWorker:
|
||||
self.interactive_input = bool(interactive_input)
|
||||
self.desktop = None if self.interactive_input else win32service.CreateDesktop(
|
||||
name, 0, win32con.GENERIC_ALL, None)
|
||||
# The worker spawns Expedition PCB and a cscript helper. Bind the whole
|
||||
# tree to a job so a supervisor kill can never orphan a process.
|
||||
# Track the session, but never use kill-on-close: PCB descendants can
|
||||
# still own a database transaction when the Python supervisor exits.
|
||||
self.job = win32job.CreateJobObject(None, '')
|
||||
self.job_bound = False
|
||||
self.companions = []
|
||||
@@ -39,9 +81,6 @@ class DesktopWorker:
|
||||
win32con.CREATE_NO_WINDOW, None, None, startup)
|
||||
thread.Close()
|
||||
try:
|
||||
info = win32job.QueryInformationJobObject(self.job, win32job.JobObjectExtendedLimitInformation)
|
||||
info['BasicLimitInformation']['LimitFlags'] |= win32job.JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
|
||||
win32job.SetInformationJobObject(self.job, win32job.JobObjectExtendedLimitInformation, info)
|
||||
win32job.AssignProcessToJobObject(self.job, self.handle)
|
||||
self.job_bound = True
|
||||
except Exception:
|
||||
@@ -80,20 +119,23 @@ class DesktopWorker:
|
||||
return self.poll()
|
||||
|
||||
def kill(self):
|
||||
if self.job_bound:
|
||||
try:
|
||||
win32job.TerminateJobObject(self.job, 1)
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
# Fallback: terminate the worker and every descendant it launched.
|
||||
"""Stop automation clients only; preserve native PCB/iCDB sessions."""
|
||||
try:
|
||||
subprocess.run(['taskkill', '/PID', str(self.pid), '/T', '/F'],
|
||||
capture_output=True, timeout=20,
|
||||
creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0))
|
||||
win32process.TerminateProcess(self.handle, 1)
|
||||
except Exception:
|
||||
pass
|
||||
# The worker is now stopped and cannot spawn another save helper.
|
||||
from .mentor_adapter import _process_details, _terminate_pid
|
||||
try:
|
||||
for pid, _exe, command, parent in _process_details('cscript.exe'):
|
||||
if (int(parent or 0) == self.pid
|
||||
and 'save_verified_block.vbs' in str(command).casefold()):
|
||||
_terminate_pid(pid) # single automation process, no /T
|
||||
except Exception:
|
||||
pass
|
||||
for companion in self.companions:
|
||||
try:
|
||||
win32process.TerminateProcess(self.handle, 1)
|
||||
win32process.TerminateProcess(companion, 1)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@@ -103,10 +145,7 @@ class DesktopWorker:
|
||||
return self.poll()
|
||||
|
||||
def close(self):
|
||||
# A job may be unavailable on a machine where the worker is already
|
||||
# assigned to another job. In that case merely closing our handles
|
||||
# would orphan PCB/cscript descendants, so terminate the tree before
|
||||
# releasing the desktop and job handles.
|
||||
# Releasing Python resources must not kill native database owners.
|
||||
try:
|
||||
if self.poll() is None:
|
||||
self.kill()
|
||||
@@ -114,14 +153,15 @@ class DesktopWorker:
|
||||
pass
|
||||
for companion in self.companions:
|
||||
try:
|
||||
if win32process.GetExitCodeProcess(companion) == 259:
|
||||
win32process.TerminateProcess(companion, 1)
|
||||
companion.Close()
|
||||
except Exception:
|
||||
pass
|
||||
self.companions.clear()
|
||||
self.companion_pids.clear()
|
||||
self.handle.Close()
|
||||
# Closing the last job handle reaps any survivor thanks to
|
||||
# KILL_ON_JOB_CLOSE; this also covers a supervisor crash.
|
||||
# Native processes keep their desktop alive if manual recovery is needed.
|
||||
self.job.Close()
|
||||
if self.desktop is not None:
|
||||
self.desktop.CloseDesktop()
|
||||
@@ -193,6 +193,14 @@ def decide(snapshot: WindowSnapshot, rules: Sequence[DialogRule]) -> RuleDecisio
|
||||
and not snapshot.controls):
|
||||
return RuleDecision(rule_id='ime-floating-language-bar', category='OBSERVE_PROGRESS')
|
||||
combined = normalize_text(' '.join((snapshot.title, *snapshot.texts)))
|
||||
# These prompts require knowledge of database ownership or a recovery
|
||||
# choice. A generic Yes/restore rule cannot establish either fact.
|
||||
if any(marker in combined for marker in (
|
||||
'continue to open the design with read/write access permission',
|
||||
'confirm that no other users have the design open',
|
||||
'database restoration', 'last user saved database', '数据库恢复')):
|
||||
return RuleDecision(error_code='DATABASE_RECOVERY_REQUIRED',
|
||||
detail=' | '.join(snapshot.texts) or snapshot.title)
|
||||
if ('problem encountered while opening one of the database files' in combined
|
||||
and 'loading of the job has failed' in combined):
|
||||
return RuleDecision(
|
||||
|
||||
@@ -370,14 +370,14 @@ def classify_dialog(snapshot: DialogSnapshot) -> DialogDecision:
|
||||
if ("database restoration" in title
|
||||
or ("restore database" in joined and "last user saved database" in joined)
|
||||
or "数据库恢复" in joined):
|
||||
return DialogDecision(action="restore_last_saved")
|
||||
return DialogDecision(error_code="DATABASE_RECOVERY_REQUIRED", detail=combined)
|
||||
if "select the desired product license" in joined:
|
||||
return DialogDecision(action="accept_license")
|
||||
if "do you want to save the reusable block cell" in joined:
|
||||
return DialogDecision(action="save_reusable_block")
|
||||
if ("continue to open the design with read/write access permission" in joined
|
||||
or "confirm that no other users have the design open" in joined):
|
||||
return DialogDecision(action="confirm_open_lock")
|
||||
return DialogDecision(error_code="DATABASE_RECOVERY_REQUIRED", detail=combined)
|
||||
if "tip of the day" in combined:
|
||||
return DialogDecision(action="dismiss_tip")
|
||||
|
||||
|
||||
@@ -51,6 +51,13 @@ def refresh_integration(pi, *, emit=lambda **event: None, settle_seconds=5, time
|
||||
emit(stage='integration_status', statuses=state)
|
||||
if green_entry is None:
|
||||
green_entry = all(status == 2 for status in state.values())
|
||||
if green_entry and not bool(value(pi, 'IsForwardAnnotationAllowed')):
|
||||
# Verified blocks can forbid another ForwardAnnotate despite
|
||||
# all four statuses being InSynch. Respect the native gate;
|
||||
# the caller still requires Save/Close and authoritative READY.
|
||||
emit(stage='integration_complete', statuses=state, actions=[],
|
||||
policy='already_synchronized_native_action_disallowed')
|
||||
return state
|
||||
if previous_state is not None and state != previous_state and deadline is not None:
|
||||
deadline.touch()
|
||||
previous_state = state
|
||||
|
||||
@@ -150,13 +150,11 @@ class LibraryVerifySession:
|
||||
pass
|
||||
try:
|
||||
if self.process.poll() is None:
|
||||
self.process.terminate()
|
||||
self.process.wait(timeout=5)
|
||||
except Exception:
|
||||
try:
|
||||
self.process.kill()
|
||||
except Exception:
|
||||
pass
|
||||
# A slow native shutdown can still be flushing the library.
|
||||
# The caller records the retained process and stops the batch.
|
||||
pass
|
||||
|
||||
|
||||
def launch_library_verify(
|
||||
@@ -291,9 +289,6 @@ def launch_library_verify(
|
||||
session = LibraryVerifySession(target, process, int(tree.handle), library, block_name)
|
||||
return session
|
||||
except Exception:
|
||||
if session is None:
|
||||
try:
|
||||
process.terminate()
|
||||
except Exception:
|
||||
pass
|
||||
emit(stage='lm_recovery_required', lm_pid=process.pid,
|
||||
detail='Verify 启动异常;保留原生会话供检查,停止批次。')
|
||||
raise
|
||||
@@ -25,6 +25,8 @@ import traceback
|
||||
import logging
|
||||
import shutil
|
||||
import socket
|
||||
import gc
|
||||
import tempfile
|
||||
from collections import Counter
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -109,31 +111,46 @@ def ensure_pcb_central_library(pcb_path, lmc_path, *, evidence_dir=None,
|
||||
# Different drive letters or an unresolved UNC mapping cannot be
|
||||
# represented relatively; preserve the explicit selected path.
|
||||
project_target = target
|
||||
try:
|
||||
with project.open('r', encoding='utf-8', errors='replace', newline='') as stream:
|
||||
original = stream.read()
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
changed = False
|
||||
|
||||
def replace_match(match):
|
||||
nonlocal changed
|
||||
if match.group(2) == project_target:
|
||||
return match.group(0)
|
||||
changed = True
|
||||
return f'{match.group(1)}{project_target}{match.group(3)}'
|
||||
|
||||
updated = _CENTRAL_LIBRARY_KEY.sub(replace_match, original)
|
||||
if not changed:
|
||||
original = project.read_bytes()
|
||||
if original.startswith((b'\xff\xfe', b'\xfe\xff')):
|
||||
# Strict, round-trippable Unicode; never substitute undecodable bytes.
|
||||
codec = 'utf-16-le' if original.startswith(b'\xff\xfe') else 'utf-16-be'
|
||||
text = original[2:].decode(codec)
|
||||
updated = original[:2] + _CENTRAL_LIBRARY_KEY.sub(
|
||||
lambda match: match[1] + project_target + match[3], text).encode(codec)
|
||||
else:
|
||||
# Patch only the ASCII key value, preserving all native ANSI comments,
|
||||
# unrelated fields, newline bytes and the exact original backup.
|
||||
try:
|
||||
target_bytes = project_target.encode('ascii')
|
||||
except UnicodeEncodeError:
|
||||
if original.startswith(b'\xef\xbb\xbf'):
|
||||
codec = 'utf-8'
|
||||
elif any(byte > 127 for byte in original):
|
||||
try:
|
||||
original.decode('utf-8')
|
||||
codec = 'utf-8'
|
||||
except UnicodeDecodeError:
|
||||
codec = 'mbcs'
|
||||
else:
|
||||
codec = 'mbcs' # unmarked EE7.9 native text uses Windows ACP
|
||||
target_bytes = project_target.encode(codec, errors='strict')
|
||||
bom = b'\xef\xbb\xbf' if original.startswith(b'\xef\xbb\xbf') else b''
|
||||
pattern = re.compile(_CENTRAL_LIBRARY_KEY.pattern.encode('ascii'), re.I | re.M)
|
||||
updated = bom + pattern.sub(
|
||||
lambda match: match[1] + target_bytes + match[3], original[len(bom):])
|
||||
if updated == original:
|
||||
emit(stage='central_library_path', status='MATCH', path=str(project), target=target)
|
||||
return False
|
||||
if evidence_dir is not None:
|
||||
evidence = Path(evidence_dir)
|
||||
evidence.mkdir(parents=True, exist_ok=True)
|
||||
(evidence / 'pcb.prj.before-central-library').write_text(original, encoding='utf-8')
|
||||
with project.open('w', encoding='utf-8', newline='') as stream:
|
||||
stream.write(updated)
|
||||
(evidence / 'pcb.prj.before-central-library').write_bytes(original)
|
||||
# Stage on the same volume. Failure cannot leave a truncated project file.
|
||||
with tempfile.TemporaryDirectory(prefix='.cbb-prj-write-', dir=project.parent) as temporary:
|
||||
staged = Path(temporary) / 'pcb.prj'
|
||||
staged.write_bytes(updated)
|
||||
os.replace(staged, project)
|
||||
emit(stage='central_library_path', status='UPDATED', path=str(project), target=target)
|
||||
return True
|
||||
|
||||
@@ -193,14 +210,19 @@ def launch_pcb_process(command, cwd):
|
||||
|
||||
|
||||
def _process_details(name):
|
||||
queries = {
|
||||
'ExpeditionPCB.exe': "SELECT ProcessId, ParentProcessId, ExecutablePath, CommandLine FROM Win32_Process WHERE Name='ExpeditionPCB.exe'",
|
||||
'LibraryManager.exe': "SELECT ProcessId, ParentProcessId, ExecutablePath, CommandLine FROM Win32_Process WHERE Name='LibraryManager.exe'",
|
||||
'cscript.exe': "SELECT ProcessId, ParentProcessId, ExecutablePath, CommandLine FROM Win32_Process WHERE Name='cscript.exe'",
|
||||
}
|
||||
if name not in queries:
|
||||
raise ValueError(f'Unsupported process query: {name}')
|
||||
import win32com.client
|
||||
service = win32com.client.GetObject('winmgmts:')
|
||||
return [
|
||||
(int(p.ProcessId), str(p.ExecutablePath or ''), str(p.CommandLine or ''),
|
||||
int(p.ParentProcessId or 0))
|
||||
for p in service.ExecQuery(
|
||||
f"SELECT ProcessId, ParentProcessId, ExecutablePath, CommandLine "
|
||||
f"FROM Win32_Process WHERE Name='{name}'")
|
||||
for p in service.ExecQuery(queries[name])
|
||||
]
|
||||
|
||||
|
||||
@@ -338,8 +360,10 @@ def choose_dialog_action(title, texts):
|
||||
joined = ' '.join(values).lower()
|
||||
if ('database restoration' in str(title or '').lower()
|
||||
or ('restore database' in joined and 'last user saved database' in joined)
|
||||
or '数据库恢复' in joined):
|
||||
return 'restore_last_saved'
|
||||
or '数据库恢复' in joined
|
||||
or 'continue to open the design with read/write access permission' in joined
|
||||
or 'confirm that no other users have the design open' in joined):
|
||||
return None
|
||||
if 'your task is being' in joined and 'elapsed time' in joined:
|
||||
return None
|
||||
positive = ('yes', 'ok', 'continue', 'retry', 'restore', 'open', 'use', 'load',
|
||||
@@ -582,6 +606,11 @@ def execute_job(job, emit):
|
||||
|
||||
root = Path(job['root'])
|
||||
block_root = Path(job['project']).parent.parent
|
||||
# COM publishes a shared active application. Never attach while another
|
||||
# native PCB session (including a retained failure) is still running.
|
||||
pcb_before = {pid for pid, _, _ in pcb_processes()}
|
||||
if pcb_before:
|
||||
raise RuntimeError(f'PCB_SESSION_ACTIVE: 已有 PCB 会话,请正常关闭后再校验: {sorted(pcb_before)}')
|
||||
# Do not recursively snapshot a live CBB over SMB immediately before
|
||||
# launching Mentor. The backup is evidence only; on Win10 a timed-out
|
||||
# robocopy can retain network handles/oplocks and make Verify nondeterministic.
|
||||
@@ -606,8 +635,10 @@ def execute_job(job, emit):
|
||||
# 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') == 'STALE_UNMOVED':
|
||||
emit(stage='icdb_address_warning', detail='旧 iCDB 地址无法隔离;继续启动以保留现场。')
|
||||
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,
|
||||
@@ -633,7 +664,6 @@ def execute_job(job, emit):
|
||||
}
|
||||
except OSError:
|
||||
integration_offsets[path] = {'size': 0, 'mtime_ns': None, 'digest': ''}
|
||||
pcb_before = {pid for pid, _, _ in pcb_processes()}
|
||||
emit(stage='pcb_baseline', pids=sorted(pcb_before))
|
||||
lm_session = None
|
||||
lm_pid = None
|
||||
@@ -642,6 +672,7 @@ def execute_job(job, emit):
|
||||
launcher_process = None
|
||||
completed = False
|
||||
helper = None
|
||||
app = doc = pi = None
|
||||
try:
|
||||
ensure_pcb_central_library(
|
||||
job['pcb'],
|
||||
@@ -717,11 +748,16 @@ def execute_job(job, emit):
|
||||
timeout_seconds=job['timeout'],
|
||||
error_reader=lambda: pcb_log_reports_integration_error(job['pcb'], offsets=integration_offsets),
|
||||
)
|
||||
# The x86 helper acquires its own COM references. Keeping these Python
|
||||
# references alive prevents the native PCB server from exiting cleanly.
|
||||
pi = doc = app = None
|
||||
gc.collect()
|
||||
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 = subprocess.Popen([str(cscript), '//nologo', str(script), job['project']],
|
||||
helper = launch_save_helper([str(cscript), '//nologo', str(script), job['project']],
|
||||
stdout=log, stderr=log, creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0))
|
||||
emit(stage='save_helper', helper_pid=helper.pid)
|
||||
last_markers = ()
|
||||
@@ -753,17 +789,16 @@ def execute_job(job, emit):
|
||||
process_exit_deadline = time.monotonic() + (15 if 'QUIT_OK' not in markers else 30)
|
||||
while any(p in {lm_pid, worker_pid, worker_parent_pid} for p, _, _ in pcb_processes()):
|
||||
if time.monotonic() >= process_exit_deadline:
|
||||
emit(stage='pcb_exit_recovered', detail='Save/Close 已确认但 PCB 未自行退出,执行定向清理。')
|
||||
cleanup_verify_processes(
|
||||
lm_pid,
|
||||
worker_pid,
|
||||
worker_parent_pid,
|
||||
expected_pcb=job.get('pcb'),
|
||||
baseline_pids=pcb_before,
|
||||
emit=emit,
|
||||
)
|
||||
break
|
||||
raise RuntimeError('PCB_RELEASE_UNCONFIRMED: Save/Close 返回成功,但未确认 PCB 退出;保留原生进程并停止批次。')
|
||||
time.sleep(.5)
|
||||
released = cleanup_verify_processes(
|
||||
lm_pid, worker_pid, worker_parent_pid, expected_pcb=job.get('pcb'),
|
||||
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}')
|
||||
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)
|
||||
@@ -771,6 +806,8 @@ def execute_job(job, emit):
|
||||
emit(stage='complete', status='PASS', certified_project=str(cert_project), cert_evidence=cert_evidence)
|
||||
return {'status': 'PASS', 'stdout': 'ReusableCircuit 校验;四项 InSynch;Save/IsSaved/Close 成功;PCB 已退出。'}
|
||||
finally:
|
||||
pi = doc = app = None
|
||||
gc.collect()
|
||||
if not completed:
|
||||
try:
|
||||
logs = collect_native_failure_logs(job['pcb'], root)
|
||||
@@ -781,7 +818,8 @@ 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:
|
||||
_terminate(helper, grace_seconds=1)
|
||||
# Stop only the automation client, never a native database tree.
|
||||
helper.terminate()
|
||||
cleanup_verify_processes(
|
||||
lm_pid,
|
||||
worker_pid,
|
||||
@@ -790,15 +828,15 @@ def execute_job(job, emit):
|
||||
baseline_pids=pcb_before,
|
||||
emit=emit,
|
||||
)
|
||||
if lm_session is not None:
|
||||
if completed and lm_session is not None:
|
||||
lm_session.close()
|
||||
|
||||
|
||||
def _terminate_pid(pid, *, timeout=20):
|
||||
"""Terminate only the PCB PID associated with the current Verify item."""
|
||||
"""Terminate a validated automation helper PID, never its native children."""
|
||||
try:
|
||||
subprocess.run(
|
||||
['taskkill', '/PID', str(int(pid)), '/T', '/F'],
|
||||
[str(Path(os.environ.get('WINDIR', r'C:\Windows'))/'System32'/'taskkill.exe'), '/PID', str(int(pid)), '/F'],
|
||||
capture_output=True,
|
||||
timeout=timeout,
|
||||
creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0),
|
||||
@@ -809,49 +847,30 @@ def _terminate_pid(pid, *, timeout=20):
|
||||
|
||||
def cleanup_verify_processes(lm_pid, worker_pid, worker_parent_pid=None, *,
|
||||
expected_pcb=None, baseline_pids=(), emit=None):
|
||||
"""Terminate every process created by one Verify session, child first.
|
||||
"""Observe native process release without interrupting database writes.
|
||||
|
||||
The worker can be killed by the outer supervisor before it has observed the
|
||||
``common``/``wg`` pair or before its own ``finally`` block runs. In that
|
||||
case the explicit PIDs are incomplete, so discover only new
|
||||
``ExpeditionPCB.exe`` processes whose command line contains this CBB's
|
||||
``-ReusableCircuit`` path. Existing PCB sessions are excluded by the
|
||||
baseline snapshot.
|
||||
A cleanup request is not evidence of release. Retained or unobservable
|
||||
sessions block the batch and require recovery; they must never be killed.
|
||||
"""
|
||||
seen = set()
|
||||
targets = [('pcb_worker', worker_pid), ('pcb_launcher', worker_parent_pid)]
|
||||
baseline = {int(pid) for pid in (baseline_pids or ())}
|
||||
if expected_pcb:
|
||||
try:
|
||||
records = _process_details('ExpeditionPCB.exe')
|
||||
except Exception:
|
||||
records = ()
|
||||
discovered = []
|
||||
for pid, executable, command, parent_pid in records:
|
||||
pid = int(pid)
|
||||
if pid in baseline or not is_reusable_circuit_pcb(executable, command, expected_pcb):
|
||||
continue
|
||||
discovered.append((pid, int(parent_pid or 0), str(executable or '').casefold()))
|
||||
discovered_pids = {pid for pid, _parent_pid, _executable in discovered}
|
||||
# The worker path is the child in the normal common/wg pair. Parent
|
||||
# first is intentionally avoided here: taskkill /T on the child is
|
||||
# harmless, and the explicit parent is terminated in the next pass.
|
||||
for pid, parent_pid, executable in discovered:
|
||||
role = 'pcb_worker' if '\\wg\\' in executable else 'pcb_launcher'
|
||||
targets.append((role, pid))
|
||||
# Do not infer an arbitrary parent (usually this Python worker) as
|
||||
# a Mentor launcher. Only add a parent that is itself one of the
|
||||
# newly discovered PCB pair processes.
|
||||
if parent_pid in discovered_pids:
|
||||
targets.append(('pcb_launcher', parent_pid))
|
||||
targets.append(('library_manager', lm_pid))
|
||||
for role, pid in targets:
|
||||
if not pid or int(pid) in seen:
|
||||
continue
|
||||
seen.add(int(pid))
|
||||
_terminate_pid(int(pid))
|
||||
if emit is not None:
|
||||
emit(stage='process_cleanup', role=role, pid=int(pid))
|
||||
tracked = {int(pid) for pid in (lm_pid, worker_pid, worker_parent_pid) if pid}
|
||||
try:
|
||||
pcb_records = _process_details('ExpeditionPCB.exe')
|
||||
lm_records = _process_details('LibraryManager.exe') if lm_pid else ()
|
||||
for pid, executable, command, _parent in pcb_records:
|
||||
if (expected_pcb and int(pid) not in baseline
|
||||
and is_reusable_circuit_pcb(executable, command, expected_pcb)):
|
||||
tracked.add(int(pid))
|
||||
alive = {int(record[0]) for record in (*pcb_records, *lm_records)}
|
||||
remaining = sorted(tracked & alive)
|
||||
result = {'safe_to_continue': not remaining, 'remaining_pids': remaining}
|
||||
except Exception as error:
|
||||
result = {'safe_to_continue': False, 'remaining_pids': sorted(tracked),
|
||||
'error': str(error)}
|
||||
if emit is not None:
|
||||
emit(stage=('process_exit_confirmed' if result['safe_to_continue']
|
||||
else 'process_retained'), **result)
|
||||
return result
|
||||
|
||||
|
||||
def _terminate(process, *, grace_seconds=5, kill_timeout_seconds=20):
|
||||
@@ -862,7 +881,7 @@ def _terminate(process, *, grace_seconds=5, kill_timeout_seconds=20):
|
||||
return
|
||||
except subprocess.TimeoutExpired:
|
||||
pass
|
||||
subprocess.run(['taskkill', '/PID', str(process.pid), '/T', '/F'], capture_output=True,
|
||||
subprocess.run([str(Path(os.environ.get('WINDIR', r'C:\Windows'))/'System32'/'taskkill.exe'), '/PID', str(process.pid), '/T', '/F'], capture_output=True,
|
||||
timeout=max(1.0, float(kill_timeout_seconds)),
|
||||
creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0))
|
||||
except Exception:
|
||||
@@ -872,25 +891,6 @@ def _terminate(process, *, grace_seconds=5, kill_timeout_seconds=20):
|
||||
pass
|
||||
|
||||
|
||||
def abort_job_document(job):
|
||||
"""Discard a failed item's PCB document so later CBBs can still run."""
|
||||
try:
|
||||
import win32com.client
|
||||
app = win32com.client.GetActiveObject('MGCPCB.Application')
|
||||
doc = app.ActiveDocument
|
||||
if doc and same_path(doc.ProjectIntegration.ProjectFile, job['project']):
|
||||
try:
|
||||
doc.Close(False)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
app.Quit()
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def worker_main(request_path):
|
||||
import pythoncom
|
||||
pythoncom.CoInitialize()
|
||||
@@ -904,6 +904,9 @@ def worker_main(request_path):
|
||||
stream.write(json.dumps(event, ensure_ascii=False) + '\n')
|
||||
|
||||
try:
|
||||
if job.get('supervisor_pid'):
|
||||
from .desktop_worker import start_supervisor_watchdog
|
||||
start_supervisor_watchdog(job['supervisor_pid'])
|
||||
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
|
||||
@@ -914,10 +917,8 @@ def worker_main(request_path):
|
||||
outcome = execute_job(job, emit)
|
||||
except Exception as error:
|
||||
traceback.print_exc()
|
||||
abort_job_document(job)
|
||||
message = str(error)
|
||||
unsafe = any(marker in message for marker in ('timeout', '超时', 'unknown dialog', '未确认 PCB 退出'))
|
||||
outcome = {'status': 'FAIL', 'stderr': message, 'safe_to_continue': not unsafe}
|
||||
outcome = {'status': 'FAIL', 'stderr': message, 'safe_to_continue': False}
|
||||
emit(stage='failed', error=message)
|
||||
finally:
|
||||
pythoncom.CoUninitialize()
|
||||
@@ -986,14 +987,10 @@ def probe_icdb_server(hosts, port, *, timeout_seconds=0.25):
|
||||
|
||||
|
||||
def prepare_icdb_address(database_dir, evidence_root, *, emit=lambda **event: None):
|
||||
"""Quarantine an unreachable stale iCDB address advertisement.
|
||||
"""Inspect the advertisement without removing database ownership state.
|
||||
|
||||
``sAddress.adr`` is volatile runtime state. When a previous PCB/cdbsvr
|
||||
session crashed, EE7.9 keeps the old network endpoint and the next PCB
|
||||
launch spends its entire startup window retrying that dead server instead
|
||||
of starting a local one. We preserve the file in this run's evidence and
|
||||
remove only the unreachable advertisement; a live endpoint is never
|
||||
touched.
|
||||
Network timeout/refusal does not prove that the server has exited. Even a
|
||||
reachable endpoint does not establish exclusive access for this Verify.
|
||||
"""
|
||||
address = Path(database_dir) / 'cdbsvr' / 'sAddress.adr'
|
||||
if not address.is_file():
|
||||
@@ -1012,20 +1009,9 @@ def prepare_icdb_address(database_dir, evidence_root, *, emit=lambda **event: No
|
||||
'hosts': parsed['hosts'], 'detail': detail}
|
||||
emit(stage='icdb_address_check', **result)
|
||||
return result
|
||||
archive = (Path(evidence_root) / 'diagnostics' / 'cdbsvr' /
|
||||
f"sAddress.adr.stale-{time.strftime('%Y%m%d-%H%M%S')}")
|
||||
try:
|
||||
archive.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.move(str(address), str(archive))
|
||||
except OSError as error:
|
||||
result = {'status': 'STALE_UNMOVED', 'path': str(address), 'port': parsed['port'],
|
||||
'hosts': parsed['hosts'], 'detail': f'{detail}; {error}'}
|
||||
emit(stage='icdb_address_check', **result)
|
||||
return result
|
||||
result = {'status': 'STALE_MOVED', 'path': str(address), 'archive': str(archive),
|
||||
result = {'status': 'UNREACHABLE', 'path': str(address),
|
||||
'port': parsed['port'], 'hosts': parsed['hosts'], 'detail': detail}
|
||||
emit(stage='icdb_address_check', **result)
|
||||
emit(stage='icdb_address_stale', **result)
|
||||
return result
|
||||
|
||||
|
||||
@@ -1040,7 +1026,8 @@ def icdb_ports_bindable(ports=(10000, 10050, 10100)):
|
||||
for port in ports:
|
||||
probe = socket.socket()
|
||||
try:
|
||||
probe.bind(('0.0.0.0', port))
|
||||
# Temporary native port preflight only; never listen or accept.
|
||||
probe.bind(('0.0.0.0', port)) # nosec B104
|
||||
return True, f'端口 {port} 可用'
|
||||
except OSError as error:
|
||||
failures.append(f'{port}: {error}')
|
||||
@@ -1310,6 +1297,25 @@ def _private_library_window(desktop, library):
|
||||
return None
|
||||
|
||||
|
||||
def close_library_reader(pid, desktop, *, timeout_seconds=5):
|
||||
"""Request native close and observe exit, never force-kill a reader."""
|
||||
import win32con, win32gui, win32process
|
||||
try:
|
||||
for hwnd in desktop.EnumDesktopWindows():
|
||||
if (win32process.GetWindowThreadProcessId(hwnd)[1] == int(pid)
|
||||
and win32gui.GetWindowText(hwnd).startswith('Library Manager')):
|
||||
win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0)
|
||||
deadline = time.monotonic() + max(0, timeout_seconds)
|
||||
while True:
|
||||
if not any(int(item[0]) == int(pid) for item in _process_details('LibraryManager.exe')):
|
||||
return True
|
||||
if time.monotonic() >= deadline:
|
||||
return False
|
||||
time.sleep(.2)
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def read_library_flag(library, name, *, timeout_seconds=90, log_path=None):
|
||||
"""Return (flag, detail) for one CBB by reading its tree icon.
|
||||
|
||||
@@ -1372,13 +1378,7 @@ def read_library_flag(library, name, *, timeout_seconds=90, log_path=None):
|
||||
except Exception as error:
|
||||
return FLAG_UNKNOWN, f'状态读取失败: {error}'
|
||||
finally:
|
||||
if pid is not None:
|
||||
try:
|
||||
subprocess.run(['taskkill', '/PID', str(pid), '/T', '/F'], capture_output=True,
|
||||
timeout=5,
|
||||
creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0))
|
||||
except (OSError, subprocess.TimeoutExpired):
|
||||
pass
|
||||
released = pid is None or close_library_reader(pid, desktop)
|
||||
if handle is not None:
|
||||
try:
|
||||
handle.Close()
|
||||
@@ -1389,6 +1389,9 @@ def read_library_flag(library, name, *, timeout_seconds=90, log_path=None):
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if not released:
|
||||
raise RuntimeError(f'LIBRARY_RELEASE_UNCONFIRMED: pid={pid}; desktop={desktop_name}')
|
||||
|
||||
|
||||
def read_library_tree_image_map(library, names, *, timeout_seconds=45, log_path=None):
|
||||
"""Read all CBB tree icon resource IDs in one private LM session.
|
||||
@@ -1463,13 +1466,7 @@ def read_library_tree_image_map(library, names, *, timeout_seconds=45, log_path=
|
||||
logger.warning('library_tree_image_item_missing name=%s reason=tree_path_lookup_failed', name)
|
||||
return result
|
||||
finally:
|
||||
if pid is not None:
|
||||
try:
|
||||
subprocess.run(['taskkill', '/PID', str(pid), '/T', '/F'], capture_output=True,
|
||||
timeout=5,
|
||||
creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0))
|
||||
except (OSError, subprocess.TimeoutExpired):
|
||||
pass
|
||||
released = pid is None or close_library_reader(pid, desktop)
|
||||
if handle is not None:
|
||||
try:
|
||||
handle.Close()
|
||||
@@ -1480,6 +1477,9 @@ def read_library_tree_image_map(library, names, *, timeout_seconds=45, log_path=
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if not released:
|
||||
raise RuntimeError(f'LIBRARY_RELEASE_UNCONFIRMED: pid={pid}; desktop={desktop_name}')
|
||||
|
||||
|
||||
def read_library_status_map(library, names, *, timeout_seconds=45, log_path=None,
|
||||
image_status_map=None):
|
||||
|
||||
@@ -178,6 +178,7 @@ class LibraryPathLease:
|
||||
created: bool = False
|
||||
_backend: WNetBackend | None = None
|
||||
_closed: bool = False
|
||||
_retained_for_recovery: bool = False
|
||||
|
||||
@classmethod
|
||||
def acquire(cls, path, *, backend: WNetBackend | None = None) -> "LibraryPathLease":
|
||||
@@ -224,11 +225,15 @@ class LibraryPathLease:
|
||||
f"NETWORK_UNAVAILABLE: 无法挂载中心库 {remote_root}: {error}"
|
||||
) from error
|
||||
|
||||
def retain_for_recovery(self) -> None:
|
||||
"""Keep the Mentor drive available to a retained native session."""
|
||||
self._retained_for_recovery = True
|
||||
|
||||
def close(self) -> None:
|
||||
if self._closed:
|
||||
return
|
||||
self._closed = True
|
||||
if not self.created or self._backend is None or not self.drive:
|
||||
if self._retained_for_recovery or not self.created or self._backend is None or not self.drive:
|
||||
return
|
||||
try:
|
||||
current = self._backend.mappings().get(self.drive)
|
||||
|
||||
@@ -45,10 +45,14 @@ operationOK = doc.Close(True)
|
||||
LogElapsed "close", measuredStart
|
||||
If Not operationOK Then WScript.Quit 6
|
||||
WScript.Echo "CLOSE_OK"
|
||||
Set pi = Nothing
|
||||
Set doc = Nothing
|
||||
Set licensing = Nothing
|
||||
measuredStart = Timer
|
||||
app.Quit
|
||||
LogElapsed "quit", measuredStart
|
||||
WScript.Echo "QUIT_OK"
|
||||
Set app = Nothing
|
||||
|
||||
Sub LogElapsed(phaseName, started)
|
||||
Dim elapsed
|
||||
|
||||
@@ -383,6 +383,8 @@ class MainWindow(QWidget):
|
||||
|
||||
def _batch_done(self, outcome):
|
||||
results, report = outcome
|
||||
if self.library_lease is not None and any(not result.safe_to_continue for result in results):
|
||||
self.library_lease.retain_for_recovery()
|
||||
for result in results:
|
||||
if not result.safe_to_continue and result.evidence_path:
|
||||
self.recovery_path = result.evidence_path.parent
|
||||
@@ -392,6 +394,8 @@ class MainWindow(QWidget):
|
||||
failed = len(results)-passed-skipped
|
||||
text = (f'已结束:成功 {passed},失败 {failed},预检跳过 {len(self.skipped_names)},'
|
||||
f'队列未执行 {skipped}。\n完整日志:{report}\n仅失败日志:{failure_report_path(report)}')
|
||||
if any(not result.safe_to_continue for result in results):
|
||||
text += '\n未确认数据库或会话安全,已停止剩余校验。请查看恢复现场。'
|
||||
self.status_label.setText(text); self.output.append(text)
|
||||
self.summary = QMessageBox(self)
|
||||
self.summary.setWindowTitle('CBB 校验结果'); self.summary.setText(text)
|
||||
@@ -405,6 +409,8 @@ class MainWindow(QWidget):
|
||||
self.stop.set(); self.status_label.setText('已请求停止;当前 CBB 完成或超时后停止队列。'); self._update()
|
||||
|
||||
def _failed(self, error):
|
||||
if self.library_lease is not None:
|
||||
self.library_lease.retain_for_recovery()
|
||||
self.status_label.setText(str(error)); self.output.append(str(error))
|
||||
if self.logging_context: self.logging_context.logger.error('cbb_worker_failed %s', error)
|
||||
|
||||
|
||||
@@ -127,7 +127,7 @@ def classify_output(exit_code: int | None, output: str, *, timed_out: bool = Fal
|
||||
"""Never invent success: PASS needs the success text and no error marker."""
|
||||
if timed_out:
|
||||
return 'TIMEOUT'
|
||||
if SUCCESS_TEXT.search(output) and not ERROR_TEXT.search(output):
|
||||
if exit_code == 0 and SUCCESS_TEXT.search(output) and not ERROR_TEXT.search(output):
|
||||
return 'PASS'
|
||||
if ERROR_TEXT.search(output):
|
||||
return 'FAIL'
|
||||
@@ -156,6 +156,14 @@ def preflight(request):
|
||||
pcb = absolute_preserving_drive(project.parent/refs[0])
|
||||
if not pcb.is_relative_to(absolute_preserving_drive(work)):
|
||||
raise ValueError(f'{name}: PCB 引用越出当前 CBB,停止操作: {pcb}')
|
||||
real_work = work.resolve()
|
||||
expected_work = library.parent.resolve() / 'ReusableBlocksLP' / name / 'Work'
|
||||
if os.path.normcase(str(real_work)) != os.path.normcase(str(expected_work)):
|
||||
raise ValueError(f'{name}: Work 路径通过链接指向其他工程,停止操作')
|
||||
for candidate in (project, pcb, pcb.parent/'pcb.prj', pcb.parent/'Layout',
|
||||
pcb.parent/'Layout'/'LayoutDB.lyt', work/'database', work/'CES'):
|
||||
if not candidate.resolve().is_relative_to(real_work):
|
||||
raise ValueError(f'{name}: 文件或目录链接越出当前 CBB,停止操作: {candidate}')
|
||||
if not pcb.is_file() or not (pcb.parent/'Layout'/'LayoutDB.lyt').is_file():
|
||||
raise ValueError(f'{name}: 缺少 PCB 或布局数据库: {pcb}')
|
||||
return project, pcb
|
||||
@@ -199,7 +207,7 @@ def _run_process(command, timeout_seconds, cwd):
|
||||
# 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(['taskkill', '/PID', str(process.pid), '/T', '/F'],
|
||||
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):
|
||||
@@ -216,7 +224,7 @@ def _run_process(command, timeout_seconds, cwd):
|
||||
|
||||
|
||||
def _stop_worker(process, *, timeout=5):
|
||||
"""Best-effort worker tree termination that never masks the item result."""
|
||||
"""Stop automation clients; native database owners are preserved."""
|
||||
try:
|
||||
process.kill()
|
||||
except Exception:
|
||||
@@ -269,6 +277,10 @@ def read_library_flag_with_retry(reader, library, block_name, *, attempts=3,
|
||||
def classify_failure_category(detail):
|
||||
text = str(detail or '')
|
||||
lower = text.casefold()
|
||||
if any(code in lower for code in (
|
||||
'pcb_release_unconfirmed', 'icdb_release_unconfirmed',
|
||||
'icdb_session_unconfirmed', 'pcb_session_active', 'database_recovery_required')):
|
||||
return 'DATABASE_SAFETY_STOP'
|
||||
if 'tf_floatinglangbar_wndtitle' in lower or 'cicerouiwndframe' in lower:
|
||||
return 'TOOL_FALSE_DIALOG'
|
||||
if 'could not load job preferences db' in lower or 'unable to create local cell library' in lower:
|
||||
@@ -472,13 +484,7 @@ def native_lm_verify_enabled():
|
||||
|
||||
def _cleanup_session_processes(root, *, lm_pid, target_pid, pcb, pcb_baseline,
|
||||
progress=None):
|
||||
"""Reap Mentor processes after the worker can no longer run its ``finally``.
|
||||
|
||||
The outer supervisor owns the worker lifetime. A timeout or an unknown
|
||||
dialog may therefore terminate the worker while its child LMC/PCB processes
|
||||
remain alive. Delegate the same target-filtered cleanup used by the worker
|
||||
and persist its events before the batch advances.
|
||||
"""
|
||||
"""Record native release or retention after automation has stopped."""
|
||||
from .mentor_adapter import cleanup_verify_processes
|
||||
|
||||
event_path = Path(root) / 'events.jsonl'
|
||||
@@ -497,7 +503,7 @@ def _cleanup_session_processes(root, *, lm_pid, target_pid, pcb, pcb_baseline,
|
||||
if progress:
|
||||
progress(event)
|
||||
|
||||
cleanup_verify_processes(
|
||||
return cleanup_verify_processes(
|
||||
lm_pid,
|
||||
target_pid,
|
||||
None,
|
||||
@@ -509,6 +515,29 @@ def _cleanup_session_processes(root, *, lm_pid, target_pid, pcb, pcb_baseline,
|
||||
|
||||
def run_verify(request, *, progress=None, flag_reader=None, process_runner=None, port_check=None,
|
||||
dialog_supervisor_factory=None):
|
||||
# Cover contents checking, native work and final state reads with one
|
||||
# session-wide mutex. The worker-stage lock below is reentrant on Windows.
|
||||
import win32event, win32con
|
||||
mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795')
|
||||
acquired = False
|
||||
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)
|
||||
return _run_verify_serialized(
|
||||
request, progress=progress, flag_reader=flag_reader,
|
||||
process_runner=process_runner, port_check=port_check,
|
||||
dialog_supervisor_factory=dialog_supervisor_factory)
|
||||
finally:
|
||||
if acquired:
|
||||
win32event.ReleaseMutex(mutex)
|
||||
mutex.Close()
|
||||
|
||||
|
||||
def _run_verify_serialized(request, *, progress=None, flag_reader=None, process_runner=None,
|
||||
port_check=None, dialog_supervisor_factory=None):
|
||||
timing = RunTimings()
|
||||
result = _run_verify(request, timing=timing, progress=progress, flag_reader=flag_reader,
|
||||
process_runner=process_runner, port_check=port_check,
|
||||
@@ -573,12 +602,12 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
runner = process_runner or _run_process
|
||||
|
||||
def finish(result):
|
||||
# Backups are transient protection for the active worker. Keep the
|
||||
# small, actionable evidence files but reclaim the copied CBB tree so
|
||||
# large libraries do not accumulate tens of megabytes per item.
|
||||
# Only reclaim auxiliary backups after confirmed success. Failed runs
|
||||
# retain every available original file for incident investigation.
|
||||
try:
|
||||
from .mentor_adapter import cleanup_evidence_backup
|
||||
cleanup_evidence_backup(root)
|
||||
if result.status == 'PASS' and result.safe_to_continue:
|
||||
cleanup_evidence_backup(root)
|
||||
except Exception:
|
||||
# Cleanup must never hide or change the verification result.
|
||||
pass
|
||||
@@ -635,6 +664,7 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
return finish(VerifyResult('BLOCKED', stderr=ports_detail))
|
||||
|
||||
job = {'lmc_file': str(absolute_preserving_drive(request.lmc_file)), 'block_name': request.block_name,
|
||||
'supervisor_pid': os.getpid(),
|
||||
'project': str(project), 'pcb': str(pcb), 'root': str(root), 'timeout': request.timeout_seconds,
|
||||
'mentor_bin': str(request.mentor_bin or ''),
|
||||
'mapped_drive': str(request.mapped_drive or ''),
|
||||
@@ -789,11 +819,11 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
'FAIL',
|
||||
stderr=f'{dialog_result.error_code}: {dialog_result.detail}',
|
||||
error_stage=phase.value,
|
||||
safe_to_continue=True,
|
||||
safe_to_continue=False,
|
||||
))
|
||||
if deadline.expired():
|
||||
_write_failure_windows(root, latest_snapshots)
|
||||
# Kills the worker's whole job: worker, PCB and cscript helper.
|
||||
# Stop automation without killing PCB/iCDB during a write.
|
||||
_write_process_tree(root, process, target_pid)
|
||||
if last_post_verify_observation:
|
||||
(root/'post_verify_observations.jsonl').write_text(json.dumps({
|
||||
@@ -817,8 +847,8 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
'detail': detail,
|
||||
'observation': last_post_verify_observation,
|
||||
})
|
||||
return finish(VerifyResult(status, stderr=detail, safe_to_continue=True))
|
||||
return finish(VerifyResult('TIMEOUT', stderr='操作超时;已记录现场,跳过当前 CBB。', error_stage=phase.value, safe_to_continue=True))
|
||||
return finish(VerifyResult(status, stderr=detail, safe_to_continue=False))
|
||||
return finish(VerifyResult('TIMEOUT', stderr='操作超时;已停止自动化并保留原生会话,停止批次,请检查恢复记录。', error_stage=phase.value, safe_to_continue=False))
|
||||
time.sleep(.2)
|
||||
worker_result = root/'outcome.json'
|
||||
if not worker_result.exists():
|
||||
@@ -832,12 +862,20 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
_stop_worker(process)
|
||||
return finish(VerifyResult('FAIL', stderr=str(error), safe_to_continue=False))
|
||||
finally:
|
||||
close_errors = []
|
||||
if 'dialog_agent' in locals() and dialog_agent is not None:
|
||||
dialog_agent.close()
|
||||
if 'process' in locals(): process.close()
|
||||
try:
|
||||
dialog_agent.close()
|
||||
except Exception as error:
|
||||
close_errors.append(str(error))
|
||||
if 'process' in locals():
|
||||
try:
|
||||
_cleanup_session_processes(
|
||||
process.close()
|
||||
except Exception as error:
|
||||
close_errors.append(str(error))
|
||||
if 'process' in locals():
|
||||
try:
|
||||
release_result = _cleanup_session_processes(
|
||||
root,
|
||||
lm_pid=lm_pid,
|
||||
target_pid=target_pid,
|
||||
@@ -845,11 +883,30 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
pcb_baseline=pcb_baseline,
|
||||
progress=progress,
|
||||
)
|
||||
except Exception:
|
||||
# Cleanup is best effort; the original Verify result remains
|
||||
# authoritative and the evidence directory records everything
|
||||
# that was successfully reaped.
|
||||
pass
|
||||
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():
|
||||
release_result = {**(release_result or {}), 'safe_to_continue': False,
|
||||
'icdb_address': str(address)}
|
||||
except OSError as error:
|
||||
close_errors.append(str(error))
|
||||
if close_errors:
|
||||
release_result = {**(release_result or {}), 'safe_to_continue': False,
|
||||
'close_errors': close_errors}
|
||||
if not release_result or not release_result.get('safe_to_continue'):
|
||||
if 'result' in locals():
|
||||
result = replace(result, status='FAIL', safe_to_continue=False,
|
||||
stderr=(result.stderr + '\nPCB_RELEASE_UNCONFIRMED: 未确认原生会话退出').strip())
|
||||
recovery = {'desktop': job['desktop'], 'project': str(project),
|
||||
'pcb': str(pcb), 'release': release_result,
|
||||
'action': '停止批次;检查原生会话及数据库;不要删除锁文件或自动恢复。'}
|
||||
try:
|
||||
(root/'recovery-required.json').write_text(
|
||||
json.dumps(recovery, ensure_ascii=False, indent=2), encoding='utf-8')
|
||||
except OSError:
|
||||
pass # Evidence failure must not prevent mutex release.
|
||||
# Drain the timing tail even when the worker exited before a poll.
|
||||
# This is optional telemetry: an unreadable log must not mask failure
|
||||
# or prevent releasing the serial-operation mutex.
|
||||
@@ -891,7 +948,7 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
|
||||
|
||||
def run_batch(requests, max_workers=1, verifier=None, *, stop=None, progress=None):
|
||||
"""Run CBBs serially; one item's failure never aborts the queue."""
|
||||
"""Run serially and stop when database/session safety is unconfirmed."""
|
||||
if max_workers != 1:
|
||||
raise ValueError('Only serial Verify is supported for the shared Library Manager session')
|
||||
if verifier is None:
|
||||
@@ -905,13 +962,12 @@ def run_batch(requests, max_workers=1, verifier=None, *, stop=None, progress=Non
|
||||
try:
|
||||
result = verifier(request)
|
||||
except Exception as error:
|
||||
# An unexpected worker exception is a failed item, not a batch abort.
|
||||
# An unexpected exception cannot establish database safety.
|
||||
result = VerifyResult('FAIL', stderr=str(error), safe_to_continue=False)
|
||||
results.append(result)
|
||||
# Failure status and safe_to_continue describe this item, not the batch;
|
||||
# the queue is skipped only after an explicit stop signal.
|
||||
queue_stop = queue_stop or result.status == 'QUEUE_STOP'
|
||||
if result.status == 'QUEUE_STOP' and stop is not None:
|
||||
# Never start another writer after an unconfirmed native shutdown.
|
||||
queue_stop = queue_stop or result.status == 'QUEUE_STOP' or not result.safe_to_continue
|
||||
if queue_stop and stop is not None:
|
||||
stop.set()
|
||||
if progress: progress(request.block_name, result)
|
||||
return results
|
||||
|
||||
Reference in new issue
Block a user