fix: handle owned CAD error dialogs and unblock verified shutdown
This commit is contained in:
1 parent
08ddf4cd6a
commit
75ee8bd33a
9 files changed
+560
-11
No files matched your search
@@ -61,6 +61,20 @@ class _DesktopLease:
|
||||
self.owner._track(process)
|
||||
return process
|
||||
|
||||
def inspect_dialogs(self, pid):
|
||||
if self.desktop is None or self.generation != self.owner.generation:
|
||||
return ()
|
||||
inspect = getattr(self.desktop, 'inspect_dialogs', None)
|
||||
if inspect is None or not any(process.pid == pid and process.poll() is None for process in self.processes):
|
||||
return ()
|
||||
return inspect(pid)
|
||||
|
||||
def acknowledge_dialog(self, dialog):
|
||||
if (self.desktop is None or self.generation != self.owner.generation or
|
||||
not any(process.pid == dialog['pid'] and process.poll() is None for process in self.processes)):
|
||||
raise WorkerMonitorError('stale or unavailable batch dialog owner')
|
||||
self.desktop.acknowledge_dialog(dialog)
|
||||
|
||||
def close(self):
|
||||
errors, remaining, records = [], [], []
|
||||
for process in reversed(self.processes):
|
||||
@@ -435,7 +449,8 @@ class BatchCadRuntime:
|
||||
self.record['cad_shutdown'] = {key: cad_record[key] for key in (
|
||||
'state', 'clean', 'cad_exit_code', 'quit_helper_exit_code', 'cleanup_errors',
|
||||
'shutdown_seconds', 'orderly_shutdown', 'diagnostic_errors', 'forced_termination',
|
||||
'forced_root_termination', 'forced_descendant_pids', 'termination_reason') if key in cad_record}
|
||||
'forced_root_termination', 'forced_descendant_pids', 'termination_reason',
|
||||
'dialog_supervision') if key in cad_record}
|
||||
if self.desktop is not None:
|
||||
try:
|
||||
self.desktop.close()
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
"""Bounded, COM-independent observations of modal dialogs on an owned desktop."""
|
||||
import ctypes
|
||||
from ctypes import wintypes
|
||||
import json
|
||||
import time
|
||||
from threading import RLock
|
||||
|
||||
from .batch_resources import write_record
|
||||
|
||||
|
||||
def _text(handle):
|
||||
user = ctypes.WinDLL('user32', use_last_error=True)
|
||||
send = user.SendMessageTimeoutW
|
||||
send.argtypes = [wintypes.HWND, wintypes.UINT, wintypes.WPARAM, wintypes.LPARAM,
|
||||
wintypes.UINT, wintypes.UINT, ctypes.POINTER(ctypes.c_size_t)]
|
||||
send.restype = wintypes.LPARAM
|
||||
buffer, result = ctypes.create_unicode_buffer(2048), ctypes.c_size_t()
|
||||
if not send(handle, 0x000D, len(buffer), ctypes.addressof(buffer), 0x0002, 50, ctypes.byref(result)):
|
||||
raise OSError('dialog text unavailable or unresponsive')
|
||||
if result.value >= len(buffer) - 1:
|
||||
raise OSError('dialog text exceeds observation limit')
|
||||
return buffer.value
|
||||
|
||||
|
||||
def inspect_owned_dialogs(api, desktop_name, pid):
|
||||
import win32gui
|
||||
import win32process
|
||||
|
||||
result = []
|
||||
deadline = time.monotonic() + .5
|
||||
for window in api._desktop_windows(desktop_name):
|
||||
if window['pid'] != pid or window['class'] != '#32770' or not win32gui.IsWindowVisible(window['hwnd']):
|
||||
continue
|
||||
handle = window['hwnd']
|
||||
row = dict(window, title='', text='', buttons=[], complete=True)
|
||||
labels, children = [], []
|
||||
try:
|
||||
row['title'] = _text(handle)
|
||||
win32gui.EnumChildWindows(handle, lambda child, _: children.append(child), None)
|
||||
for child in children:
|
||||
if time.monotonic() >= deadline or len(children) > 64:
|
||||
row['complete'] = False
|
||||
break
|
||||
if not win32gui.IsWindowVisible(child):
|
||||
continue
|
||||
if win32process.GetWindowThreadProcessId(child)[1] != pid:
|
||||
row['complete'] = False
|
||||
continue
|
||||
text = _text(child)
|
||||
if win32gui.GetClassName(child).casefold() == 'button':
|
||||
row['buttons'].append({'hwnd': int(child), 'id': win32gui.GetDlgCtrlID(child),
|
||||
'text': text, 'enabled': bool(win32gui.IsWindowEnabled(child))})
|
||||
elif text:
|
||||
labels.append(text)
|
||||
except Exception as error:
|
||||
row.update(complete=False, read_error=str(error))
|
||||
row['text'] = '\n'.join(labels)[:8192]
|
||||
result.append(row)
|
||||
if len(result) >= 8 or time.monotonic() >= deadline:
|
||||
break
|
||||
return tuple(result)
|
||||
|
||||
|
||||
def acknowledge_owned_dialog(api, desktop_name, pid, expected):
|
||||
import win32gui
|
||||
|
||||
# Re-enumerate the private desktop and compare the complete fingerprint;
|
||||
# a recycled HWND or changed prompt cannot inherit the earlier decision.
|
||||
current = next((row for row in inspect_owned_dialogs(api, desktop_name, pid)
|
||||
if row == expected), None)
|
||||
if current is None or not _script_error(current):
|
||||
raise OSError('dialog changed before acknowledgement')
|
||||
win32gui.PostMessage(current['buttons'][0]['hwnd'], 0x00F5, 0, 0) # BM_CLICK, no global input
|
||||
|
||||
|
||||
def _script_error(row):
|
||||
title = row['title'].strip().casefold()
|
||||
body = row['text'].casefold()
|
||||
buttons = row['buttons']
|
||||
return (row.get('complete') is True and title in {'script error', 'microsoft vbscript', 'dxdesigner', '脚本错误'}
|
||||
and any(marker in body for marker in ('microsoft vbscript compilation error', 'microsoft vbscript 编译器错误'))
|
||||
and len(buttons) == 1 and buttons[0]['id'] in {1, 2} and buttons[0]['enabled']
|
||||
and buttons[0]['text'].replace('&', '').strip().casefold() in {'ok', '确定', '确定(o)'})
|
||||
|
||||
|
||||
class CadDialogGuard:
|
||||
def __init__(self, desktop, process, evidence_path, token):
|
||||
self.desktop, self.process = desktop, process
|
||||
self.evidence_path, self.token = evidence_path, token
|
||||
self.records, self.seen = [], set()
|
||||
self.blocking = []
|
||||
self.failure = ''
|
||||
self._lock = RLock()
|
||||
|
||||
def poll(self, phase):
|
||||
with self._lock:
|
||||
self._poll(phase)
|
||||
|
||||
def _poll(self, phase):
|
||||
inspect = getattr(self.desktop, 'inspect_dialogs', None)
|
||||
if inspect is None or self.process.poll() is not None:
|
||||
self.blocking = []
|
||||
return
|
||||
rows = [row for row in inspect(self.process.pid)
|
||||
if row['pid'] == self.process.pid and row['class'] == '#32770']
|
||||
self.blocking = [row['title'] or '未命名弹窗' for row in rows]
|
||||
for row in rows:
|
||||
key = json.dumps(row, ensure_ascii=False, sort_keys=True)
|
||||
action = 'acknowledge_script_error' if _script_error(row) else 'manual_required'
|
||||
if action == 'acknowledge_script_error':
|
||||
self.failure = 'CAD script error: ' + row['text'][:1000]
|
||||
if key in self.seen or len(self.records) >= 100:
|
||||
continue
|
||||
record = dict(row, phase=phase, action=action, observed_at=time.time())
|
||||
self.records.append(record)
|
||||
self._save() # No automatic button action without durable evidence.
|
||||
self.seen.add(key)
|
||||
if action == 'acknowledge_script_error':
|
||||
self.desktop.acknowledge_dialog(row)
|
||||
|
||||
def _save(self):
|
||||
write_record(self.evidence_path, {'version': 1, 'session_token': self.token,
|
||||
'cad_pid': self.process.pid, 'dialogs': self.records})
|
||||
|
||||
def summary(self):
|
||||
with self._lock:
|
||||
return {'evidence_path': str(self.evidence_path), 'dialogs_seen': len(self.records),
|
||||
'blocked': bool(self.blocking), 'blocking_titles': list(self.blocking), 'error': self.failure}
|
||||
@@ -52,6 +52,9 @@ def _scrub_json(value):
|
||||
|
||||
|
||||
def _allowed(parts):
|
||||
if re.fullmatch(r'cad-dialogs-[a-f0-9]{32}\.json', parts[-1]):
|
||||
return ((len(parts) == 4 and parts[0] == 'batch-resources' and re.fullmatch(r'generation-\d+', parts[2])) or
|
||||
any(value in parts for value in ('quick-run', 'quickrun', 'quick-run-history')))
|
||||
if (len(parts) == 5 and parts[0] == 'tasks' and parts[2] == 'quick-run-history'
|
||||
and re.fullmatch(r'bom-import-[A-Za-z0-9-]+', parts[3])):
|
||||
return parts[-1] == 'source-map.json'
|
||||
|
||||
@@ -7,12 +7,14 @@ import subprocess
|
||||
import sys
|
||||
import time
|
||||
from traceback import clear_frames
|
||||
from threading import Event, Thread
|
||||
from uuid import uuid4
|
||||
|
||||
from .cad_identity import CadBinding, current_desktop_name, verify_application, project_file_path
|
||||
from .isolated_desktop import PrivateDesktop
|
||||
from .worker_monitor import WorkerMonitorError
|
||||
from .path_access import internal_path, canonical_path, retry_sharing_violation
|
||||
from .cad_dialogs import CadDialogGuard
|
||||
|
||||
|
||||
class PrivateCadStartupError(WorkerMonitorError):
|
||||
@@ -98,6 +100,10 @@ class IsolatedCadSession:
|
||||
self.abort_event = abort_event
|
||||
self.stop_control = stop_control
|
||||
self.record = {'desktop': self.desktop.name, 'token': self.token, 'state': 'starting'}
|
||||
self._dialogs = None
|
||||
self._dialog_monitor_error = ''
|
||||
self._dialog_stop = Event()
|
||||
self._dialog_thread = None
|
||||
|
||||
def _record(self, **values):
|
||||
self.record.update(values)
|
||||
@@ -118,6 +124,8 @@ class IsolatedCadSession:
|
||||
self._check_abort()
|
||||
self.desktop.__enter__()
|
||||
self.cad = self.desktop.start_process((str(_designer_executable()),))
|
||||
self._dialogs = CadDialogGuard(self.desktop, self.cad,
|
||||
self.root / ('cad-dialogs-' + self.token + '.json'), self.token)
|
||||
self._record(cad_pid=self.cad.pid)
|
||||
bootstrap = self.root / ('cad-binding-' + self.token + '.json')
|
||||
environment = dict(os.environ, DXPART_DESKTOP=self.desktop.name,
|
||||
@@ -129,16 +137,18 @@ class IsolatedCadSession:
|
||||
deadline = time.monotonic() + 120
|
||||
while probe.poll() is None:
|
||||
self._check_abort()
|
||||
self._poll_dialogs('startup')
|
||||
cad_exit = self.cad.poll()
|
||||
if cad_exit is not None:
|
||||
raise WorkerMonitorError(f'owned private CAD exited during startup: exit code {cad_exit}')
|
||||
if time.monotonic() >= deadline:
|
||||
raise WorkerMonitorError('private CAD bootstrap timed out')
|
||||
raise WorkerMonitorError('private CAD bootstrap timed out' + self._dialog_description())
|
||||
time.sleep(0.05)
|
||||
code = probe.poll()
|
||||
if code:
|
||||
failure_type = CadIdentityConflict if code == PRIVATE_CAD_IDENTITY_EXIT_CODE else WorkerMonitorError
|
||||
raise failure_type('private CAD startup failed: ' + probe.stderr.read().decode('utf-8', errors='replace'))
|
||||
self._poll_dialogs('startup')
|
||||
finally:
|
||||
probe.close()
|
||||
try:
|
||||
@@ -151,8 +161,10 @@ class IsolatedCadSession:
|
||||
raise CadIdentityConflict('private CAD bootstrap identity evidence is invalid: ' + str(failure)) from failure
|
||||
self.binding = binding
|
||||
self._record(state='ready', guid=self.binding.guid, startup_seconds=time.monotonic() - self.started)
|
||||
self._start_dialog_monitor()
|
||||
return self
|
||||
except Exception as error:
|
||||
self._stop_dialog_monitor()
|
||||
try:
|
||||
self.desktop.close()
|
||||
except Exception as failure:
|
||||
@@ -167,6 +179,54 @@ class IsolatedCadSession:
|
||||
if self.abort_event is not None and self.abort_event.is_set():
|
||||
raise WorkerMonitorError('private CAD startup was cancelled before execution')
|
||||
|
||||
def _start_dialog_monitor(self):
|
||||
if getattr(self.desktop, 'inspect_dialogs', None) is None:
|
||||
return
|
||||
def monitor():
|
||||
while not self._dialog_stop.wait(.2):
|
||||
self._poll_dialogs('running')
|
||||
self._dialog_thread = Thread(target=monitor, name='owned-cad-dialogs', daemon=True)
|
||||
self._dialog_thread.start()
|
||||
|
||||
def _stop_dialog_monitor(self):
|
||||
self._dialog_stop.set()
|
||||
if self._dialog_thread is not None:
|
||||
self._dialog_thread.join(3)
|
||||
if self._dialog_thread.is_alive():
|
||||
self._dialog_monitor_error = 'CAD dialog monitor did not stop within its budget'
|
||||
|
||||
def _poll_dialogs(self, phase):
|
||||
if self._dialogs is None:
|
||||
return
|
||||
try:
|
||||
self._dialogs.poll(phase)
|
||||
except Exception as error:
|
||||
self._dialog_monitor_error = str(error)
|
||||
self.record['dialog_supervision'] = dict(self._dialogs.summary(), monitor_error=self._dialog_monitor_error)
|
||||
if phase in {'startup', 'checkpoint'} and self._dialogs.failure:
|
||||
raise WorkerMonitorError(self._dialogs.failure + self._dialog_description())
|
||||
|
||||
def _dialog_description(self):
|
||||
if self._dialogs is None or not self._dialogs.records:
|
||||
return ''
|
||||
summary = self._dialogs.summary()
|
||||
titles = ' / '.join(summary['blocking_titles']) or '已记录弹窗'
|
||||
return f';CAD 弹窗:{titles};详情:{summary["evidence_path"]}'
|
||||
|
||||
def _wait_process(self, process, timeout, phase):
|
||||
if getattr(self.desktop, 'inspect_dialogs', None) is None:
|
||||
return process.wait(timeout=timeout)
|
||||
deadline = time.monotonic() + timeout
|
||||
while True:
|
||||
self._poll_dialogs(phase)
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
raise subprocess.TimeoutExpired(getattr(process, 'args', phase), timeout)
|
||||
try:
|
||||
return process.wait(timeout=min(.25, remaining))
|
||||
except subprocess.TimeoutExpired:
|
||||
pass
|
||||
|
||||
def start_worker(self, command, *, extra_environment=None, **options):
|
||||
if self.binding is None or self.cad.poll() is not None:
|
||||
raise WorkerMonitorError('owned private CAD is unavailable')
|
||||
@@ -187,7 +247,7 @@ class IsolatedCadSession:
|
||||
process = self.start_worker(_helper_command('checkpoint', evidence, self.cad.pid),
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
try:
|
||||
code = process.wait(timeout=20)
|
||||
code = self._wait_process(process, 20, 'checkpoint')
|
||||
if code:
|
||||
failure_type = CadIdentityConflict if code == PRIVATE_CAD_IDENTITY_EXIT_CODE else WorkerMonitorError
|
||||
raise failure_type('project close checkpoint failed: ' +
|
||||
@@ -206,6 +266,7 @@ class IsolatedCadSession:
|
||||
return result
|
||||
|
||||
def __exit__(self, error_type, error, traceback):
|
||||
self._stop_dialog_monitor()
|
||||
closing_started = time.monotonic()
|
||||
cleanup_errors = []
|
||||
diagnostic_errors = []
|
||||
@@ -250,20 +311,25 @@ class IsolatedCadSession:
|
||||
if self.cad is not None and self.cad.poll() is not None:
|
||||
raise WorkerMonitorError('owned CAD exited before the authorized quit request')
|
||||
if self.cad is not None and self.binding is not None:
|
||||
self._poll_dialogs('closing')
|
||||
closing = self.desktop.start_process(_helper_command('quit', self.root / 'private-desktop.json', self.cad.pid),
|
||||
env=_child_environment(self.binding.environment()), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
quit_code = closing.wait(timeout=20)
|
||||
quit_code = self._wait_process(closing, 20, 'closing')
|
||||
exit_codes['quit_helper_exit_code'] = quit_code
|
||||
if quit_code:
|
||||
raise WorkerMonitorError('owned CAD refused orderly exit: ' + closing.stderr.read().decode('utf-8', errors='replace'))
|
||||
cad_code = self.cad.wait(timeout=15)
|
||||
cad_code = self._wait_process(self.cad, 15, 'closing')
|
||||
exit_codes['cad_exit_code'] = cad_code
|
||||
if cad_code != 0:
|
||||
raise WorkerMonitorError('owned CAD returned a nonzero exit code after quit')
|
||||
self.record['orderly_shutdown'] = True
|
||||
except Exception as failure:
|
||||
remember('orderly_shutdown', failure)
|
||||
remember('orderly_shutdown', WorkerMonitorError(str(failure) + self._dialog_description())
|
||||
if self._dialog_description() else failure)
|
||||
finally:
|
||||
if self._dialogs is not None and (self._dialogs.failure or self._dialog_monitor_error):
|
||||
remember('cad_dialog', WorkerMonitorError(
|
||||
(self._dialogs.failure or self._dialog_monitor_error) + self._dialog_description()))
|
||||
if error is not None or failures:
|
||||
# Evidence failure must never prevent the identity-checked Quit
|
||||
# above or release of the handles we own below.
|
||||
@@ -277,10 +343,14 @@ class IsolatedCadSession:
|
||||
if cad_running:
|
||||
# A refused/timed-out Quit may still be saving or closing.
|
||||
# Keep both CAD and its helper owned and alive until the
|
||||
# interactive caller confirms force, including ordinary stop.
|
||||
# caller confirms force or both retained processes exit.
|
||||
from .stop_control import wait_for_resolution
|
||||
def owned_processes_exited():
|
||||
self._poll_dialogs('closing')
|
||||
return self.cad.poll() is not None and (closing is None or closing.poll() is not None)
|
||||
try:
|
||||
wait_for_resolution(self.stop_control, self.root, failure_message())
|
||||
wait_for_resolution(self.stop_control, self.root, failure_message(),
|
||||
resolved=owned_processes_exited)
|
||||
except WorkerMonitorError as failure:
|
||||
force_event = getattr(self.stop_control, 'force_event', None)
|
||||
if force_event is None or not force_event.is_set():
|
||||
|
||||
@@ -536,6 +536,19 @@ class PrivateDesktop:
|
||||
def __exit__(self, *_exc: object) -> None:
|
||||
self.close()
|
||||
|
||||
def inspect_dialogs(self, pid):
|
||||
from .cad_dialogs import inspect_owned_dialogs
|
||||
if self._handle is None or not any(process.pid == pid and process.poll() is None for process in self._processes):
|
||||
return ()
|
||||
return inspect_owned_dialogs(self._api, self.name, pid)
|
||||
|
||||
def acknowledge_dialog(self, dialog):
|
||||
from .cad_dialogs import acknowledge_owned_dialog
|
||||
pid = dialog['pid']
|
||||
if self._handle is None or not any(process.pid == pid and process.poll() is None for process in self._processes):
|
||||
raise TaskCenterError('private_desktop', 'dialog process is no longer owned and alive')
|
||||
acknowledge_owned_dialog(self._api, self.name, pid, dialog)
|
||||
|
||||
def _create(self) -> None:
|
||||
if os.name != "nt" and self._api is None:
|
||||
return
|
||||
|
||||
@@ -42,11 +42,12 @@ def protect_interruption(root, reason):
|
||||
os.fsync(stream.fileno())
|
||||
|
||||
|
||||
def wait_for_resolution(control, root, error):
|
||||
"""Interactive owners retain a possibly changed project until explicit force.
|
||||
def wait_for_resolution(control, root, error, *, resolved=None):
|
||||
"""Retain uncertain work until explicit force or an owned-exit proof.
|
||||
|
||||
The GUI-side supervisor can also terminate its own Job after durable force
|
||||
evidence. Ordinary cancellation never releases this wait.
|
||||
evidence. Ordinary cancellation never releases this wait; an optional
|
||||
observer may prove all retained processes exited without clearing uncertainty.
|
||||
"""
|
||||
if not isinstance(control, StopControl):
|
||||
return
|
||||
@@ -71,6 +72,9 @@ def wait_for_resolution(control, root, error):
|
||||
resolution_error=str(error), stop_requested=True, safe_stop=False)
|
||||
_publish_progress(root / 'worker-progress.json', record)
|
||||
while True:
|
||||
if resolved is not None and resolved():
|
||||
control.waiting_for_resolution = False
|
||||
return
|
||||
if control.force_event.wait(.1):
|
||||
try:
|
||||
protect()
|
||||
|
||||
Reference in new issue
Block a user