fix: scope catalog availability and report status progress
This commit is contained in:
1 parent
31a93cd313
commit
4fb978ee21
5 files changed
+465
-44
No files matched your search
@@ -24,9 +24,10 @@ _retained_workers = []
|
||||
|
||||
|
||||
class NativeOperationError(RuntimeError):
|
||||
def __init__(self, detail, *, safe_to_continue):
|
||||
def __init__(self, detail, *, safe_to_continue, blocking_manager_pids=()):
|
||||
super().__init__(detail)
|
||||
self.safe_to_continue = safe_to_continue
|
||||
self.blocking_manager_pids = tuple(blocking_manager_pids)
|
||||
# Coordinator-owned Create/Add/conflict/update/remove/backup-reimport evidence:
|
||||
# diagnostics/issue2-native-crud-20261103/engine-e2e/cycle-result.json
|
||||
_PRODUCTION_ADD_VALIDATED = True
|
||||
@@ -286,15 +287,20 @@ class NativeManagementAdapter:
|
||||
finally:
|
||||
worker.close()
|
||||
|
||||
def catalog(self, library, evidence):
|
||||
def catalog(self, library, evidence, *, include_engineering_identity=True):
|
||||
result = self._worker({'operation': 'catalog', 'worker_role': 'catalog_readonly',
|
||||
'library': str(absolute_preserving_drive(library))}, evidence)
|
||||
'library': str(absolute_preserving_drive(library)),
|
||||
'include_engineering_identity': include_engineering_identity}, evidence)
|
||||
if not result.get('success') or not result.get('safe_to_continue'):
|
||||
raise NativeOperationError(result.get('detail', '原生目录复读未确认,禁止文件夹回退。'),
|
||||
safe_to_continue=result.get('safe_to_continue') is True)
|
||||
safe_to_continue=result.get('safe_to_continue') is True,
|
||||
blocking_manager_pids=result.get('blocking_manager_pids', ()))
|
||||
return Catalog(Path(result['library']), int(result['flow']),
|
||||
tuple(CatalogEntry(**entry) for entry in result['entries']), result['safe_to_continue'])
|
||||
|
||||
def catalog_registrations(self, library, evidence):
|
||||
return self.catalog(library, evidence, include_engineering_identity=False)
|
||||
|
||||
def remove(self, request, evidence):
|
||||
caps = self.capabilities()
|
||||
if not caps['remove'].supported:
|
||||
@@ -1087,6 +1093,77 @@ def _wait_native_exit(pids, timeout=10):
|
||||
return True
|
||||
|
||||
|
||||
def _catalog_shared_dependencies(library):
|
||||
from .icdb_ownership import shared_symbol_database
|
||||
database = shared_symbol_database(library) / 'icdb.dat'
|
||||
try:
|
||||
info = database.stat()
|
||||
except FileNotFoundError:
|
||||
return set()
|
||||
return {(info.st_dev, info.st_ino, database.resolve())}
|
||||
|
||||
|
||||
def _probe_catalog_files(library):
|
||||
import pywintypes, win32con, win32file
|
||||
from contextlib import ExitStack
|
||||
|
||||
with ExitStack() as handles:
|
||||
paths = (library, *(path for _, _, path in _catalog_shared_dependencies(library)))
|
||||
for path in paths:
|
||||
try:
|
||||
handle = win32file.CreateFile(str(path), win32con.GENERIC_READ, 0, None,
|
||||
win32con.OPEN_EXISTING, 0, None)
|
||||
except (OSError, pywintypes.error) as error:
|
||||
raise OSError(f'{path}:{error}') from error
|
||||
handles.callback(handle.Close)
|
||||
|
||||
|
||||
def _open_catalog_manager_library(pid):
|
||||
from .residual_sessions import _process_windows, _window_error
|
||||
|
||||
windows = _process_windows({pid})
|
||||
if _window_error(windows, pid):
|
||||
return None
|
||||
paths = set()
|
||||
for window in windows[pid]:
|
||||
title = window['title']
|
||||
if title.startswith('Library Manager: '):
|
||||
path = Path(title.removeprefix('Library Manager: ').strip())
|
||||
if path.is_absolute() and path.suffix.casefold() == '.lmc':
|
||||
paths.add(path)
|
||||
return next(iter(paths)) if len(paths) == 1 else None
|
||||
|
||||
|
||||
def _check_catalog_owners(library, processes):
|
||||
"""A foreign LM is compatible only with a disjoint library and free target resources."""
|
||||
library = Path(library).resolve()
|
||||
manager_pids = [pid for pid, *_ in processes]
|
||||
target_dependencies = _catalog_shared_dependencies(library)
|
||||
for pid in manager_pids:
|
||||
try:
|
||||
current = _open_catalog_manager_library(pid)
|
||||
if current is None:
|
||||
detail = '无法确认已运行的 Library Manager 对应哪个库'
|
||||
else:
|
||||
other = current.resolve(strict=True)
|
||||
if library.samefile(other):
|
||||
detail = '当前库已在另一个 Library Manager 中打开'
|
||||
elif any(left[2] == right[2] or (left[1] and left[:2] == right[:2])
|
||||
for left in target_dependencies for right in _catalog_shared_dependencies(other)):
|
||||
detail = '另一个 Library Manager 正在使用相同的共享符号库'
|
||||
else:
|
||||
continue
|
||||
except (OSError, ValueError) as error:
|
||||
detail = f'无法确认另一中心库的资源范围:{error}'
|
||||
raise NativeOperationError(f'LIBRARY_MANAGER_BUSY: PID {pid} · {detail}。',
|
||||
safe_to_continue=True, blocking_manager_pids=(pid,))
|
||||
try:
|
||||
_probe_catalog_files(library)
|
||||
except OSError as error:
|
||||
raise NativeOperationError(f'LIBRARY_MANAGER_BUSY: PID {manager_pids} · 当前库资源占用未确认:{error}',
|
||||
safe_to_continue=True, blocking_manager_pids=manager_pids) from error
|
||||
|
||||
|
||||
def _catalog_native(job, root):
|
||||
import gc, pythoncom
|
||||
from .com_runtime import initialize_com, uninitialize_com
|
||||
@@ -1102,7 +1179,8 @@ def _catalog_native(job, root):
|
||||
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'])
|
||||
result['safe_to_continue'] = bool(result.get('no_new_manager') or (
|
||||
result.get('native_pids') and _wait_native_exit(result['native_pids'])))
|
||||
return result
|
||||
|
||||
|
||||
@@ -1121,8 +1199,16 @@ def _catalog_com(job, root):
|
||||
desktop, name = _current_desktop()
|
||||
if name != job['desktop'] or not name.startswith('CbbManagement_'):
|
||||
raise RuntimeError('拒绝在非本次私有桌面读取原生目录。')
|
||||
if _process_details('LibraryManager.exe'):
|
||||
raise RuntimeError('LIBRARY_MANAGER_BUSY: 已有 Library Manager 运行,请关闭后重试。')
|
||||
previous_managers = _process_details('LibraryManager.exe')
|
||||
if previous_managers:
|
||||
if job.get('worker_role') != 'catalog_readonly' or job.get('include_engineering_identity', True):
|
||||
raise RuntimeError('LIBRARY_MANAGER_BUSY: 已有 Library Manager 运行,请关闭后重试。')
|
||||
expected = Path(job['mentor_home'])/'lm/win32/bin/LibraryManager.exe'
|
||||
if hash_file(expected) != _BINARY_PROOF['lm/win32/bin/LibraryManager.exe']:
|
||||
pids = sorted(pid for pid, *_ in previous_managers)
|
||||
raise NativeOperationError(f'LIBRARY_MANAGER_BUSY: PID {pids} · 当前安装尚未验证并行目录读取。',
|
||||
safe_to_continue=True, blocking_manager_pids=pids)
|
||||
_check_catalog_owners(job['library'], previous_managers)
|
||||
except Exception as error:
|
||||
error.safe_to_continue = True
|
||||
raise
|
||||
@@ -1178,16 +1264,26 @@ def _catalog_com(job, root):
|
||||
# Keep the launch pending until its exact native identity is recorded.
|
||||
app = dispatch_native(job, lambda: win32com.client.DispatchEx('LibraryManager.Application'),
|
||||
asynchronous=True)
|
||||
app.Visible = True
|
||||
processes = _process_details('LibraryManager.exe')
|
||||
owned_pids.update(int(p[0]) for p in processes)
|
||||
from .session_record import update_worker_state
|
||||
update_worker_state(job, 'POSTCALL', identities=[('native', pid) for pid in owned_pids])
|
||||
if len(owned_pids) != 1:
|
||||
previous_pids = {pid for pid, *_ in previous_managers}
|
||||
new_processes = [process for process in processes if process[0] not in previous_pids]
|
||||
if not new_processes and previous_pids and {p[0] for p in processes} == previous_pids:
|
||||
# DispatchEx reused an existing instance. Drop this proxy without invoking any method.
|
||||
result.update(no_new_manager=True, blocking_manager_pids=sorted(previous_pids))
|
||||
raise RuntimeError(f'LIBRARY_MANAGER_BUSY: 当前 COM 注册复用了已有 Library Manager,PID {sorted(previous_pids)}。')
|
||||
if len(new_processes) != 1:
|
||||
raise RuntimeError('无法唯一确认本次 Library Manager 进程。')
|
||||
pid, executable, *_ = new_processes[0]
|
||||
expected_binary = Path(job['mentor_home'])/'lm/win32/bin/LibraryManager.exe'
|
||||
if Path(processes[0][1]).resolve() != expected_binary.resolve():
|
||||
if Path(executable).resolve() != expected_binary.resolve():
|
||||
raise RuntimeError('COM 注册指向不同的 Library Manager 安装,拒绝打开中心库。')
|
||||
if job.get('session_record_path') or previous_pids:
|
||||
desktop_pids = {win32process.GetWindowThreadProcessId(hwnd)[1] for hwnd in desktop.EnumDesktopWindows()}
|
||||
if pid not in desktop_pids:
|
||||
raise RuntimeError('无法确认新 Library Manager 位于本次私有桌面。')
|
||||
owned_pids.add(pid)
|
||||
update_worker_state(job, 'POSTCALL', identities=[('native', pid)])
|
||||
app.Visible = True
|
||||
watcher = threading.Thread(target=observe_dialogs, daemon=True)
|
||||
watcher.start()
|
||||
if job['operation'] in ('probe_create_add', 'probe_create'):
|
||||
@@ -1228,13 +1324,14 @@ def _catalog_com(job, root):
|
||||
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
|
||||
if job.get('include_engineering_identity', True):
|
||||
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
|
||||
@@ -1262,7 +1359,7 @@ def _catalog_com(job, root):
|
||||
result['close_detail'] = str(error)
|
||||
result['close_exception'] = _exception_details(error)
|
||||
library = None
|
||||
if app is not None and not job.get('_native_add_pending'):
|
||||
if app is not None and owned_pids and not job.get('_native_add_pending'):
|
||||
try:
|
||||
dispatch_native(job, lambda: app.Quit(), phase='CLOSING')
|
||||
except Exception as error:
|
||||
@@ -1381,6 +1478,8 @@ def management_worker_main(request_path, *, catalog_readonly=False):
|
||||
except Exception as error:
|
||||
if getattr(error, 'safe_to_continue', None) is True:
|
||||
result['safe_to_continue'] = True
|
||||
if getattr(error, 'blocking_manager_pids', ()):
|
||||
result['blocking_manager_pids'] = list(error.blocking_manager_pids)
|
||||
result['detail'] = str(error)
|
||||
result['exception'] = _exception_details(error)
|
||||
finally:
|
||||
|
||||
Reference in new issue
Block a user