feat: add guarded native CBB management and recovery coordination
This commit is contained in:
1 parent
3415e010ff
commit
797a79c30e
17 files changed
+2423
-15
No files matched your search
@@ -0,0 +1,576 @@
|
||||
"""Version-pinned native adapter, private desktop transport and strict catalog.
|
||||
|
||||
The installed Tcl CleanWGLib/F4 contract has isolated removal proof. Discovery
|
||||
of an Add dialog is deliberately insufficient to enable production Add/Update.
|
||||
"""
|
||||
from dataclasses import asdict
|
||||
import ctypes
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from uuid import uuid4
|
||||
|
||||
from .management import (Capability, Catalog, CatalogEntry, NativeOutcome,
|
||||
engineering_identity, validate_name, _write_json)
|
||||
from .scoped_manifest import hash_file
|
||||
|
||||
_retained_workers = []
|
||||
_BINARY_PROOF = {
|
||||
'lm/win32/bin/CleanWGLib.exe': '7808ded326555f1fd5d5c14f68803dbb4f970d624f9ad6e1c7982dc9ed867917',
|
||||
'lm/win32/bin/LibraryManager.exe': 'a9c4c3d806794dbdc56d2bc4c637a1cf25e87e98644a7d5fd4eb0067ca5845e0',
|
||||
'common/win32/lib/LMCDLL70.dll': 'fc614d43ed0a2fd28dbe37116510e303fc0e71542da585ac03aaa147630629b8',
|
||||
'common/win32/lib/LMCDocAddin70.dll': 'ff022ce285544ddd7eb639e4eb90216899b63adabcef8b3448236b4916150154',
|
||||
}
|
||||
|
||||
|
||||
def removal_input(name, partition):
|
||||
validate_name(name); validate_name(partition)
|
||||
try:
|
||||
return f'REUSE_BLOCK\t{partition}\t{name}\n'.encode('ascii')
|
||||
except UnicodeEncodeError as error:
|
||||
raise ValueError('已验证的 CleanWGLib 输入仅支持 ASCII 名称和分区。') from error
|
||||
|
||||
|
||||
def removal_output_ok(code, output, name, partition):
|
||||
return (code == 0 and '# Warning:' not in output and '# Error:' not in output
|
||||
and re.search(r"# Note: Removed [^\r\n]+ '" + re.escape(name)
|
||||
+ r"' from partition '" + re.escape(partition) + r"'\.", output) is not None)
|
||||
|
||||
|
||||
def catalog_dialog_action(title, text):
|
||||
value = (title + '\n' + text).casefold()
|
||||
if ('this central library must be updated' in value or 'select flow type' in value):
|
||||
return 'cancel'
|
||||
return 'observe'
|
||||
|
||||
|
||||
class NativeManagementAdapter:
|
||||
def __init__(self, *, mentor_home=None, worker_factory=None, timeout_seconds=180):
|
||||
from .mentor_paths import discover_sdd_home
|
||||
self.home = Path(mentor_home) if mentor_home is not None else discover_sdd_home()
|
||||
self.worker_factory = worker_factory
|
||||
self.timeout_seconds = timeout_seconds
|
||||
|
||||
def capabilities(self):
|
||||
reason = ''
|
||||
for relative, expected in _BINARY_PROOF.items():
|
||||
path = self.home/relative if self.home else Path(relative)
|
||||
try:
|
||||
if not self.home or not path.is_file() or hash_file(path) != expected:
|
||||
reason = f'{Path(relative).name} 缺失或与已隔离验证的 EE 7.9.5 版本不一致。'
|
||||
break
|
||||
except OSError as error:
|
||||
reason = f'无法核对原生程序 {path}: {error}'
|
||||
break
|
||||
return {
|
||||
'remove': Capability(not reason, reason or '已验证 CleanWGLib/F4;仅 ASCII 名称、Logical-Physical 和 DxDesigner 库。'),
|
||||
'add': Capability(False, '原生新增尚未完成隔离注册及工程内容复读验证;请先运行独立诊断。'),
|
||||
'update': Capability(False, '同名更新需要原生移除、重新导入及完整端到端隔离验证,目前不可用。'),
|
||||
}
|
||||
|
||||
def _worker(self, job, evidence):
|
||||
from .desktop_worker import DesktopWorker
|
||||
evidence = Path(evidence)
|
||||
evidence.mkdir(parents=True, exist_ok=False)
|
||||
request_path = evidence/'request.json'
|
||||
desktop = 'CbbManagement_' + uuid4().hex[:12]
|
||||
timeout = float(job.get('timeout_seconds', self.timeout_seconds))
|
||||
job = {**job, 'desktop': desktop, 'mentor_home': str(self.home or ''),
|
||||
'timeout_seconds': timeout, 'supervisor_pid': os.getpid()}
|
||||
_write_json(request_path, job)
|
||||
command = ([sys.executable] if getattr(sys, 'frozen', False)
|
||||
else [sys.executable, '-m', 'cbb_refresh_verify'])
|
||||
worker = (self.worker_factory or DesktopWorker)(command + ['--management-worker', str(request_path)], desktop)
|
||||
deadline = time.monotonic() + timeout
|
||||
while worker.poll() is None and time.monotonic() < deadline:
|
||||
time.sleep(.1)
|
||||
if worker.poll() is None:
|
||||
# DesktopWorker.close() requests a kill without a cancellation file.
|
||||
# Keep this exact worker alive until its native call returns normally.
|
||||
_retained_workers.append(worker)
|
||||
return {'success': False, 'safe_to_continue': False,
|
||||
'detail': f'TIMEOUT: 原生调用尚未返回,保留私有桌面 {desktop},请检查 {evidence}'}
|
||||
try:
|
||||
result = json.loads((evidence/'result.json').read_text(encoding='utf-8'))
|
||||
if not isinstance(result.get('safe_to_continue'), bool):
|
||||
raise ValueError('原生释放记录缺失')
|
||||
return result
|
||||
except (OSError, ValueError) as error:
|
||||
return {'success': False, 'safe_to_continue': False, 'detail': str(error)}
|
||||
finally:
|
||||
worker.close()
|
||||
|
||||
def catalog(self, library, evidence):
|
||||
result = self._worker({'operation': 'catalog', 'library': str(library)}, evidence)
|
||||
if not result.get('success') or not result.get('safe_to_continue'):
|
||||
raise RuntimeError(result.get('detail', '原生目录复读未确认,禁止文件夹回退。'))
|
||||
return Catalog(Path(result['library']), int(result['flow']),
|
||||
tuple(CatalogEntry(**entry) for entry in result['entries']), result['safe_to_continue'])
|
||||
|
||||
def remove(self, request, evidence):
|
||||
caps = self.capabilities()
|
||||
if not caps['remove'].supported:
|
||||
return NativeOutcome(False, True, caps['remove'].reason)
|
||||
removal_input(request.name, request.partition)
|
||||
if request.partition != 'Logical-Physical':
|
||||
return NativeOutcome(False, True, '仅已验证 Logical-Physical 原生移除。')
|
||||
result = self._worker({'operation': 'remove', 'library': str(request.library),
|
||||
'name': request.name, 'partition': request.partition,
|
||||
'timeout_seconds': request.timeout_seconds}, evidence)
|
||||
return NativeOutcome(bool(result.get('success')), bool(result.get('safe_to_continue')), result.get('detail', ''))
|
||||
|
||||
def preflight(self, request, catalog):
|
||||
if request.operation in ('remove', 'update'):
|
||||
removal_input(request.name, request.partition)
|
||||
if request.partition != 'Logical-Physical' or catalog.flow != 1:
|
||||
raise ValueError('仅验证了 DxDesigner / Logical-Physical 管理操作。')
|
||||
|
||||
def add(self, request, evidence):
|
||||
return NativeOutcome(False, True, self.capabilities()['add'].reason)
|
||||
|
||||
|
||||
def prepare_probe_library(job, root):
|
||||
"""Diagnostic create is restricted to a new fixed descendant of this job."""
|
||||
expected = Path(root).resolve()/'fixture/mentor_lib.lmc'
|
||||
if Path(job['library']).resolve() != expected or expected.parent.exists():
|
||||
raise ValueError('诊断只能创建当前任务下全新独占 fixture/mentor_lib.lmc。')
|
||||
expected.parent.mkdir()
|
||||
return expected
|
||||
|
||||
|
||||
def validate_probe_readd(job, root):
|
||||
expected = Path(root).parent.resolve()/'native-add/fixture/mentor_lib.lmc'
|
||||
try:
|
||||
owner = json.loads((Path(root).parent/'probe-owner.json').read_text(encoding='utf-8'))
|
||||
except (OSError, ValueError) as error:
|
||||
raise ValueError('没有本次原生创建的隔离库所有权记录。') from error
|
||||
if (Path(job['library']).resolve() != expected or not expected.is_file()
|
||||
or owner.get('library') != str(expected) or not job.get('probe_token')
|
||||
or owner.get('token') != job['probe_token']):
|
||||
raise ValueError('重新导入诊断仅允许本次原生新建的固定隔离库。')
|
||||
return expected
|
||||
|
||||
|
||||
def _close_probe_dialogs(desktop, owned_pids):
|
||||
"""Normal child-first close; never terminate a native owner."""
|
||||
import pythoncom, win32con, win32gui, win32process
|
||||
for title, control in (('New Reusable Block', 1082), ('Reusable Blocks', 1052)):
|
||||
for hwnd in desktop.EnumDesktopWindows():
|
||||
if (win32process.GetWindowThreadProcessId(hwnd)[1] in owned_pids
|
||||
and win32gui.GetWindowText(hwnd) == title and win32gui.IsWindowVisible(hwnd)):
|
||||
button = win32gui.GetDlgItem(hwnd, control)
|
||||
if not button or not win32gui.IsWindowEnabled(button):
|
||||
return
|
||||
win32gui.PostMessage(button, win32con.BM_CLICK, 0, 0)
|
||||
deadline = time.monotonic() + 3
|
||||
while win32gui.IsWindow(hwnd) and time.monotonic() < deadline:
|
||||
pythoncom.PumpWaitingMessages(); time.sleep(.1)
|
||||
if win32gui.IsWindow(hwnd):
|
||||
return # Never close a parent with an unreleased child.
|
||||
|
||||
|
||||
def _probe_add_dialog(app, job, desktop, owned_pids, root):
|
||||
try:
|
||||
return _probe_add_dialog_impl(app, job, desktop, owned_pids, root)
|
||||
finally:
|
||||
import gc
|
||||
gc.collect() # Release UIA wrappers before closing native child dialogs.
|
||||
_close_probe_dialogs(desktop, owned_pids)
|
||||
|
||||
|
||||
def _probe_add_dialog_impl(app, job, desktop, owned_pids, root):
|
||||
"""Diagnostic only: proven editor/UIA tab and resource1103 controls.
|
||||
|
||||
This function has no production capability override. It is called only
|
||||
after this worker itself creates a new disposable library.
|
||||
"""
|
||||
import pythoncom, win32con, win32gui, win32process
|
||||
from pywinauto import Desktop
|
||||
from .backup_recovery import _align_library
|
||||
from .management import source_project
|
||||
source, pcb, top = source_project(job['source'], job.get('top_level_block', ''))
|
||||
source_folder = 'source-replacement' if job['operation'] == 'probe_readd' else 'source'
|
||||
if not source.is_relative_to(Path(root).parent.resolve()/source_folder):
|
||||
raise ValueError('隔离新增只允许使用本次复制的来源工程。')
|
||||
_align_library(source, pcb, Path(job['library']))
|
||||
validate_name(job['name'])
|
||||
deadline = time.monotonic() + float(job['timeout_seconds'])
|
||||
def find_window(title):
|
||||
for hwnd in desktop.EnumDesktopWindows():
|
||||
if (win32process.GetWindowThreadProcessId(hwnd)[1] in owned_pids
|
||||
and win32gui.IsWindowVisible(hwnd) and win32gui.GetWindowText(hwnd) == title):
|
||||
return hwnd
|
||||
return None
|
||||
def await_window(title):
|
||||
while time.monotonic() < deadline:
|
||||
hwnd = find_window(title)
|
||||
if hwnd:
|
||||
return hwnd
|
||||
pythoncom.PumpWaitingMessages(); time.sleep(.1)
|
||||
raise TimeoutError(f'原生窗口未出现:{title}')
|
||||
app.OnReusableBlocksEditor()
|
||||
editor = await_window('Reusable Blocks')
|
||||
tabs = Desktop(backend='uia').window(handle=editor).descendants(control_type='TabItem')
|
||||
physical = [tab for tab in tabs if tab.window_text() == 'Logical - Physical']
|
||||
if len(physical) != 1:
|
||||
raise RuntimeError('无法唯一识别已验证的 Logical - Physical 页签。')
|
||||
if not physical[0].is_selected():
|
||||
physical[0].select()
|
||||
if not physical[0].is_selected():
|
||||
raise RuntimeError('Logical - Physical 页签未选中。')
|
||||
# UIA objects hold COM references into Library Manager. Do not retain them
|
||||
# during the native write or app.Quit / process-release observation.
|
||||
physical = tabs = None
|
||||
import gc
|
||||
gc.collect()
|
||||
new_button = win32gui.GetDlgItem(editor, 1066)
|
||||
if not new_button or not win32gui.IsWindowEnabled(new_button):
|
||||
raise RuntimeError('原生 New 按钮不可用。')
|
||||
win32gui.PostMessage(new_button, win32con.BM_CLICK, 0, 0)
|
||||
dialog = await_window('New Reusable Block')
|
||||
fields = {1217: str(source), 1215: job['name'], 1218: top, 1216: 'Isolated CBB management validation'}
|
||||
for control, value in fields.items():
|
||||
hwnd = win32gui.GetDlgItem(dialog, control)
|
||||
if not hwnd or win32gui.GetClassName(hwnd) != 'Edit':
|
||||
raise RuntimeError(f'原生新增字段身份不匹配:{control}')
|
||||
win32gui.SendMessage(hwnd, win32con.WM_SETTEXT, 0, value)
|
||||
if win32gui.GetWindowText(hwnd) != value:
|
||||
raise RuntimeError(f'原生新增字段回读失败:{control}')
|
||||
_write_json(root/'submitted-fields.json', fields)
|
||||
ok = win32gui.GetDlgItem(dialog, 1083)
|
||||
if not ok:
|
||||
raise RuntimeError('原生新增确认按钮缺失。')
|
||||
win32gui.PostMessage(ok, win32con.BM_CLICK, 0, 0)
|
||||
success = None
|
||||
while time.monotonic() < deadline:
|
||||
pythoncom.PumpWaitingMessages()
|
||||
for hwnd in desktop.EnumDesktopWindows():
|
||||
if win32process.GetWindowThreadProcessId(hwnd)[1] not in owned_pids or not win32gui.IsWindowVisible(hwnd):
|
||||
continue
|
||||
children = []
|
||||
win32gui.EnumChildWindows(hwnd, lambda child, _: children.append(child), None)
|
||||
text = '\n'.join(win32gui.GetWindowText(child) for child in children)
|
||||
if 'New Logical-Physical Reuse Block was successfully added.' in text:
|
||||
success = text
|
||||
button = win32gui.GetDlgItem(hwnd, 2) or win32gui.GetDlgItem(hwnd, 1)
|
||||
if button:
|
||||
win32gui.PostMessage(button, win32con.BM_CLICK, 0, 0)
|
||||
break
|
||||
if success:
|
||||
break
|
||||
time.sleep(.1)
|
||||
_write_json(root/'native-add-output.json', {'success_message': success})
|
||||
close = win32gui.GetDlgItem(editor, 1052)
|
||||
if success and close:
|
||||
win32gui.PostMessage(close, win32con.BM_CLICK, 0, 0)
|
||||
for _ in range(20):
|
||||
pythoncom.PumpWaitingMessages(); time.sleep(.1)
|
||||
if not win32gui.IsWindow(editor):
|
||||
break
|
||||
if not success:
|
||||
raise TimeoutError('未取得原生新增成功消息;保留副本与私有桌面证据。')
|
||||
|
||||
|
||||
def run_isolated_probe(source, root, name, *, mentor_home=None, replacement_source=None):
|
||||
"""Create a fresh native fixture and test Add without enabling production.
|
||||
|
||||
Root must not exist. Source is copied completely before native access. A
|
||||
successful command alone is not acceptance: close/reopen and byte identity
|
||||
checks are recorded independently for human review.
|
||||
"""
|
||||
from .management import source_project, ManagementRequest
|
||||
from .library_lock import LibraryLock
|
||||
from .scoped_manifest import ManifestScope
|
||||
from .scoped_manifest import copy_verified, build_manifest
|
||||
import pythoncom, win32con, win32event
|
||||
root = Path(root).resolve()
|
||||
if root.exists():
|
||||
raise ValueError('诊断目录必须是全新目录,不能复用现有中心库或旧 fixture。')
|
||||
source, _, top = source_project(source)
|
||||
validate_name(name)
|
||||
if root.is_relative_to(source.parent) or source.parent.is_relative_to(root):
|
||||
raise ValueError('诊断目录不能与来源工程相互包含。')
|
||||
mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795')
|
||||
acquired = False
|
||||
token = uuid4().hex
|
||||
record = {'operation': 'isolated_add_probe', 'source': str(source), 'name': name,
|
||||
'production_capability_enabled': False}
|
||||
from .com_runtime import initialize_com, uninitialize_com
|
||||
initialized = initialize_com()
|
||||
try:
|
||||
acquired = win32event.WaitForSingleObject(mutex, 0) in (win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED)
|
||||
if not acquired:
|
||||
raise RuntimeError('已有 CBB 校验/恢复/管理任务,请稍后运行隔离诊断。')
|
||||
root.mkdir(parents=True, exist_ok=False)
|
||||
manifest = copy_verified(source.parent, root/'source')
|
||||
staged = root/'source'/source.name
|
||||
identity = engineering_identity(staged)
|
||||
adapter = NativeManagementAdapter(mentor_home=mentor_home)
|
||||
if not adapter.capabilities()['remove'].supported:
|
||||
raise RuntimeError('诊断要求已识别的 EE7.9.5 原生安装。')
|
||||
library = root/'native-add/fixture/mentor_lib.lmc'
|
||||
native = adapter._worker({'operation': 'probe_create_add', 'library': str(library),
|
||||
'source': str(staged), 'name': name, 'top_level_block': top,
|
||||
'probe_token': token}, root/'native-add')
|
||||
record['native'] = native
|
||||
record['source_unchanged'] = build_manifest(source.parent) == manifest
|
||||
if native.get('success') and native.get('safe_to_continue'):
|
||||
catalog = adapter.catalog(library, root/'reopen')
|
||||
record['catalog'] = asdict(catalog)
|
||||
matches = [entry for entry in catalog.entries if entry.name == name and entry.partition == 'Logical-Physical']
|
||||
record['identity_matches'] = len(matches) == 1 and matches[0].engineering_identity == identity
|
||||
record['accepted'] = record['identity_matches'] and record['source_unchanged']
|
||||
else:
|
||||
record['accepted'] = False
|
||||
_write_json(root/'probe-result.json', record)
|
||||
if record['accepted'] and replacement_source is not None:
|
||||
replacement, _, replacement_top = source_project(replacement_source)
|
||||
if replacement.is_relative_to(root) or root.is_relative_to(replacement.parent):
|
||||
raise ValueError('更新诊断来源必须位于隔离库与证据目录之外。')
|
||||
replacement_manifest = copy_verified(replacement.parent, root/'source-replacement')
|
||||
staged_replacement = root/'source-replacement'/replacement.name
|
||||
replacement_identity = engineering_identity(staged_replacement)
|
||||
record['update'] = {'stage': 'backup', 'accepted': False, 'source': str(replacement)}
|
||||
record['accepted'] = False
|
||||
with LibraryLock(library):
|
||||
copy_verified(library.parent, root/'library-before-update',
|
||||
scope=ManifestScope.library(name, library.name))
|
||||
request = ManagementRequest('remove', library, name, evidence_dir=root)
|
||||
removal = adapter.remove(request, root/'native-remove')
|
||||
record['update']['removal'] = asdict(removal)
|
||||
_write_json(root/'probe-result.json', record)
|
||||
if not removal.success or not removal.safe_to_continue:
|
||||
return record
|
||||
missing = adapter.catalog(library, root/'after-remove')
|
||||
if any(e.name == name for e in missing.entries):
|
||||
record['update']['error'] = '原生移除后条目仍存在'
|
||||
_write_json(root/'probe-result.json', record)
|
||||
return record
|
||||
record['update']['stage'] = 'removed'
|
||||
_write_json(root/'probe-result.json', record)
|
||||
readd = adapter._worker({'operation': 'probe_readd', 'library': str(library),
|
||||
'source': str(staged_replacement), 'name': name, 'top_level_block': replacement_top,
|
||||
'probe_token': token}, root/'native-readd')
|
||||
record['update']['readd'] = readd
|
||||
if readd.get('success') and readd.get('safe_to_continue'):
|
||||
updated = adapter.catalog(library, root/'reopen-update')
|
||||
record['update']['catalog'] = asdict(updated)
|
||||
entries = [e for e in updated.entries if e.name == name and e.partition == 'Logical-Physical']
|
||||
record['update']['accepted'] = (len(entries) == 1
|
||||
and entries[0].engineering_identity == replacement_identity
|
||||
and build_manifest(replacement.parent) == replacement_manifest)
|
||||
record['update']['stage'] = 'complete' if record['update']['accepted'] else 'RECOVERY_REQUIRED'
|
||||
record['accepted'] = record['update']['accepted']
|
||||
_write_json(root/'probe-result.json', record)
|
||||
return record
|
||||
except Exception as error:
|
||||
record.update(accepted=False, error=str(error))
|
||||
if root.exists():
|
||||
_write_json(root/'probe-result.json', record)
|
||||
raise
|
||||
finally:
|
||||
if acquired:
|
||||
win32event.ReleaseMutex(mutex)
|
||||
mutex.Close()
|
||||
uninitialize_com(initialized)
|
||||
|
||||
|
||||
def _current_desktop():
|
||||
import win32api, win32service
|
||||
desktop = win32service.GetThreadDesktop(win32api.GetCurrentThreadId())
|
||||
user32 = ctypes.WinDLL('user32', use_last_error=True)
|
||||
user32.GetUserObjectInformationW.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_void_p,
|
||||
ctypes.c_uint, ctypes.POINTER(ctypes.c_uint)]
|
||||
buffer = ctypes.create_unicode_buffer(256)
|
||||
needed = ctypes.c_uint()
|
||||
if not user32.GetUserObjectInformationW(int(desktop), 2, buffer, ctypes.sizeof(buffer), ctypes.byref(needed)):
|
||||
raise OSError('无法确认工作进程桌面身份')
|
||||
return desktop, buffer.value
|
||||
|
||||
|
||||
def _wait_native_exit(pids, timeout=10):
|
||||
"""Observe exact process handles after COM teardown, without COM/WMI."""
|
||||
import pywintypes, win32api, win32con, win32event
|
||||
deadline = time.monotonic() + timeout
|
||||
for pid in pids:
|
||||
try:
|
||||
handle = win32api.OpenProcess(win32con.SYNCHRONIZE, False, int(pid))
|
||||
except pywintypes.error as error:
|
||||
if error.winerror == 87: # Process no longer exists.
|
||||
continue
|
||||
return False
|
||||
try:
|
||||
remaining = max(0, int((deadline - time.monotonic()) * 1000))
|
||||
if win32event.WaitForSingleObject(handle, remaining) != win32con.WAIT_OBJECT_0:
|
||||
return False
|
||||
finally:
|
||||
handle.Close()
|
||||
return True
|
||||
|
||||
|
||||
def _catalog_native(job, root):
|
||||
import gc, pythoncom
|
||||
from .com_runtime import initialize_com, uninitialize_com
|
||||
initialized = initialize_com()
|
||||
try:
|
||||
result = _catalog_com(job, root)
|
||||
finally:
|
||||
gc.collect()
|
||||
uninitialize_com(initialized)
|
||||
# A failed COM activation can have created an unaccounted server. An empty
|
||||
# PID list is missing release evidence, not proof that nothing was launched.
|
||||
result['safe_to_continue'] = bool(result.get('native_pids')) and _wait_native_exit(result['native_pids'])
|
||||
return result
|
||||
|
||||
|
||||
def _catalog_com(job, root):
|
||||
import pythoncom, win32com.client, win32con, win32gui, win32process
|
||||
from .mentor_adapter import _process_details
|
||||
desktop, name = _current_desktop()
|
||||
if name != job['desktop'] or not name.startswith('CbbManagement_'):
|
||||
raise RuntimeError('拒绝在非本次私有桌面读取原生目录。')
|
||||
if _process_details('LibraryManager.exe'):
|
||||
raise RuntimeError('已有 Library Manager 运行,请关闭后重试。')
|
||||
stop = threading.Event()
|
||||
refused = []
|
||||
observed = []
|
||||
owned_pids = set()
|
||||
def observe_dialogs():
|
||||
while not stop.wait(.1):
|
||||
for hwnd in desktop.EnumDesktopWindows():
|
||||
try:
|
||||
pid = win32process.GetWindowThreadProcessId(hwnd)[1]
|
||||
if pid not in owned_pids or not win32gui.IsWindowVisible(hwnd):
|
||||
continue
|
||||
children = []
|
||||
win32gui.EnumChildWindows(hwnd, lambda child, _: children.append(child), None)
|
||||
title = win32gui.GetWindowText(hwnd)
|
||||
text = '\n'.join(win32gui.GetWindowText(child) for child in children)
|
||||
if catalog_dialog_action(title, text) == 'cancel':
|
||||
if hwnd not in observed:
|
||||
observed.append(hwnd)
|
||||
refused.append({'title': title, 'text': text})
|
||||
_write_json(root/'refused-dialogs.json', refused)
|
||||
cancel = win32gui.GetDlgItem(hwnd, 2)
|
||||
if cancel:
|
||||
win32gui.PostMessage(cancel, win32con.BM_CLICK, 0, 0)
|
||||
except Exception:
|
||||
continue
|
||||
app = library = None
|
||||
result = {'success': False, 'safe_to_continue': False}
|
||||
watcher = None
|
||||
try:
|
||||
app = win32com.client.DispatchEx('LibraryManager.Application')
|
||||
app.Visible = True
|
||||
processes = _process_details('LibraryManager.exe')
|
||||
owned_pids.update(int(p[0]) for p in processes)
|
||||
if len(owned_pids) != 1:
|
||||
raise RuntimeError('无法唯一确认本次 Library Manager 进程。')
|
||||
expected_binary = Path(job['mentor_home'])/'lm/win32/bin/LibraryManager.exe'
|
||||
if Path(processes[0][1]).resolve() != expected_binary.resolve():
|
||||
raise RuntimeError('COM 注册指向不同的 Library Manager 安装,拒绝打开中心库。')
|
||||
watcher = threading.Thread(target=observe_dialogs, daemon=True)
|
||||
watcher.start()
|
||||
if job['operation'] == 'probe_create_add':
|
||||
target = prepare_probe_library(job, root)
|
||||
library = app.CreateLibrary(str(target), 1)
|
||||
_write_json(root.parent/'probe-owner.json', {'library': str(target), 'token': job['probe_token']})
|
||||
else:
|
||||
if job['operation'] == 'probe_readd':
|
||||
validate_probe_readd(job, root)
|
||||
library = app.OpenLibrary(str(Path(job['library']).resolve()))
|
||||
if refused:
|
||||
raise RuntimeError('目录读取需要升级中心库或选择流程;已拒绝,目标未获准自动升级。')
|
||||
if library is None or Path(str(library.FullName)).resolve() != Path(job['library']).resolve():
|
||||
raise RuntimeError('原生返回中心库身份不一致。')
|
||||
if job['operation'] in ('probe_create_add', 'probe_readd'):
|
||||
_probe_add_dialog(app, job, desktop, owned_pids, root)
|
||||
entries = []
|
||||
parts = library.Partitions(7)
|
||||
for i in range(1, int(parts.Count) + 1):
|
||||
partition = parts.Item(i)
|
||||
for j in range(1, int(partition.Count) + 1):
|
||||
item = partition.Item(j)
|
||||
block_name, partition_name = str(item.Name), str(item.PartitionName)
|
||||
validate_name(block_name)
|
||||
identity = {}
|
||||
work = Path(job['library']).parent/'ReusableBlocksLP'/block_name/'Work'
|
||||
projects = list(work.glob('*.prj'))
|
||||
if len(projects) == 1:
|
||||
try:
|
||||
identity = engineering_identity(projects[0])
|
||||
except (ValueError, OSError):
|
||||
pass
|
||||
entries.append(asdict(CatalogEntry(block_name, partition_name, identity)))
|
||||
item = None
|
||||
partition = None
|
||||
parts = None
|
||||
result.update(success=True, library=str(library.FullName), flow=int(library.FlowType), entries=entries)
|
||||
except Exception as error:
|
||||
result['detail'] = str(error)
|
||||
finally:
|
||||
if library is not None:
|
||||
try: library.Close()
|
||||
except Exception as error: result['close_detail'] = str(error)
|
||||
library = None
|
||||
if app is not None:
|
||||
try: app.Quit()
|
||||
except Exception as error: result['quit_detail'] = str(error)
|
||||
app = None
|
||||
stop.set()
|
||||
if watcher:
|
||||
watcher.join(1)
|
||||
result['native_pids'] = sorted(owned_pids)
|
||||
if refused:
|
||||
result.update(success=False, detail='拒绝目录读取触发的中心库升级/流程选择。')
|
||||
return result
|
||||
|
||||
|
||||
def management_worker_main(request_path):
|
||||
"""Internal worker. Desktop identity and capability gates are rechecked here."""
|
||||
request_path = Path(request_path)
|
||||
root = request_path.parent
|
||||
job = json.loads(request_path.read_text(encoding='utf-8'))
|
||||
result = {'success': False, 'safe_to_continue': False}
|
||||
try:
|
||||
_, desktop = _current_desktop()
|
||||
if desktop != job['desktop'] or not desktop.startswith('CbbManagement_'):
|
||||
raise RuntimeError('原生管理操作仅允许在本次私有桌面执行。')
|
||||
if job['operation'] in ('catalog', 'probe_create_add', 'probe_readd'):
|
||||
result = _catalog_native(job, root)
|
||||
elif job['operation'] == 'remove':
|
||||
adapter = NativeManagementAdapter(mentor_home=job['mentor_home'])
|
||||
cap = adapter.capabilities()['remove']
|
||||
if not cap.supported:
|
||||
raise RuntimeError(cap.reason)
|
||||
if job['partition'] != 'Logical-Physical':
|
||||
raise ValueError('未验证的分区类型')
|
||||
input_path = root/'remove-list.txt'
|
||||
input_path.write_bytes(removal_input(job['name'], job['partition']))
|
||||
command = [str(adapter.home/'lm/win32/bin/CleanWGLib.exe'), str(job['library']), 'F4', str(input_path)]
|
||||
_write_json(root/'command.json', command)
|
||||
with (root/'native-output.txt').open('wb') as output:
|
||||
process = subprocess.Popen(command, stdout=output, stderr=subprocess.STDOUT,
|
||||
creationflags=subprocess.CREATE_NO_WINDOW)
|
||||
_write_json(root/'native-process.json', {'pid': process.pid, 'command': command})
|
||||
# Never terminate this native database owner on timeout.
|
||||
try:
|
||||
code = process.wait(timeout=float(job['timeout_seconds']))
|
||||
except subprocess.TimeoutExpired:
|
||||
result.update(detail=f'TIMEOUT: CleanWGLib PID {process.pid} 尚未释放')
|
||||
else:
|
||||
text = (root/'native-output.txt').read_bytes().decode('mbcs', errors='replace')
|
||||
result.update(success=removal_output_ok(code, text, job['name'], job['partition']),
|
||||
safe_to_continue=True, detail=text, exit_code=code)
|
||||
else:
|
||||
raise ValueError('未验证的原生管理操作')
|
||||
except Exception as error:
|
||||
result['detail'] = str(error)
|
||||
finally:
|
||||
_write_json(root/'result.json', result)
|
||||
return 0 if result['success'] and result['safe_to_continue'] else 2
|
||||
Reference in new issue
Block a user