fix: report known catalog conflicts before WMI startup

This commit is contained in:
阿白叔 committed 2026-11-25 11:53:07 +08:00
1 parent 0ee24d7beb
commit 75612cd4da
4 files changed
+88 -17

No files matched your search

+16 -2
View File
@@ -1134,7 +1134,7 @@ def _open_catalog_manager_library(pid):
return next(iter(paths)) if len(paths) == 1 else None return next(iter(paths)) if len(paths) == 1 else None
def _check_catalog_owners(library, processes): def _check_catalog_owners(library, processes, *, known_conflicts_only=False):
"""Screen existing managers before starting a separately owned catalog instance.""" """Screen existing managers before starting a separately owned catalog instance."""
library = Path(library).resolve() library = Path(library).resolve()
manager_pids = [pid for pid, *_ in processes] manager_pids = [pid for pid, *_ in processes]
@@ -1158,9 +1158,13 @@ def _check_catalog_owners(library, processes):
observed_libraries[pid] = str(other) observed_libraries[pid] = str(other)
continue continue
except (OSError, ValueError) as error: except (OSError, ValueError) as error:
if known_conflicts_only:
continue
detail = f'无法确认另一中心库的资源范围:{error}' detail = f'无法确认另一中心库的资源范围:{error}'
raise NativeOperationError(f'LIBRARY_MANAGER_BUSY: PID {pid} · {detail}。', raise NativeOperationError(f'LIBRARY_MANAGER_BUSY: PID {pid} · {detail}。',
safe_to_continue=True, blocking_manager_pids=(pid,)) safe_to_continue=True, blocking_manager_pids=(pid,))
if known_conflicts_only:
return observed_libraries
try: try:
_probe_catalog_files(library) _probe_catalog_files(library)
except OSError as error: except OSError as error:
@@ -1204,10 +1208,20 @@ def _catalog_com(job, root):
desktop, name = _current_desktop() desktop, name = _current_desktop()
if name != job['desktop'] or not name.startswith('CbbManagement_'): if name != job['desktop'] or not name.startswith('CbbManagement_'):
raise RuntimeError('拒绝在非本次私有桌面读取原生目录。') raise RuntimeError('拒绝在非本次私有桌面读取原生目录。')
read_registrations = (job.get('worker_role') == 'catalog_readonly'
and not job.get('include_engineering_identity', True))
if read_registrations:
from .owner_probe import snapshot_process_ids
try:
pids = snapshot_process_ids('LibraryManager.exe')
if pids:
_check_catalog_owners(job['library'], [(pid,) for pid in pids], known_conflicts_only=True)
except OSError:
pass # The full owner and file checks still run before activation.
previous_managers = _process_details('LibraryManager.exe') previous_managers = _process_details('LibraryManager.exe')
existing_libraries = {} existing_libraries = {}
if previous_managers: if previous_managers:
if job.get('worker_role') != 'catalog_readonly' or job.get('include_engineering_identity', True): if not read_registrations:
raise RuntimeError('LIBRARY_MANAGER_BUSY: 已有 Library Manager 运行,请关闭后重试。') raise RuntimeError('LIBRARY_MANAGER_BUSY: 已有 Library Manager 运行,请关闭后重试。')
expected = Path(job['mentor_home'])/'lm/win32/bin/LibraryManager.exe' expected = Path(job['mentor_home'])/'lm/win32/bin/LibraryManager.exe'
if hash_file(expected) != _BINARY_PROOF['lm/win32/bin/LibraryManager.exe']: if hash_file(expected) != _BINARY_PROOF['lm/win32/bin/LibraryManager.exe']:
+36
View File
@@ -7,6 +7,42 @@ import sys
import tempfile import tempfile
def snapshot_process_ids(name):
"""Read executable names from the local process table without starting WMI."""
import ctypes
from ctypes import wintypes
class ProcessEntry(ctypes.Structure):
_fields_ = [('size', wintypes.DWORD), ('usage', wintypes.DWORD), ('pid', wintypes.DWORD),
('heap_id', ctypes.c_size_t), ('module_id', wintypes.DWORD), ('threads', wintypes.DWORD),
('parent', wintypes.DWORD), ('priority', wintypes.LONG), ('flags', wintypes.DWORD),
('name', wintypes.WCHAR * 260)]
kernel = ctypes.WinDLL('kernel32', use_last_error=True)
kernel.CreateToolhelp32Snapshot.argtypes = [wintypes.DWORD, wintypes.DWORD]
kernel.CreateToolhelp32Snapshot.restype = wintypes.HANDLE
kernel.CloseHandle.argtypes = [wintypes.HANDLE]
for step in (kernel.Process32FirstW, kernel.Process32NextW):
step.argtypes = [wintypes.HANDLE, ctypes.POINTER(ProcessEntry)]
step.restype = wintypes.BOOL
handle = kernel.CreateToolhelp32Snapshot(2, 0) # TH32CS_SNAPPROCESS
if handle == ctypes.c_void_p(-1).value:
raise ctypes.WinError(ctypes.get_last_error())
try:
entry = ProcessEntry(size=ctypes.sizeof(ProcessEntry))
found = []
processing = kernel.Process32FirstW(handle, ctypes.byref(entry))
while processing:
if entry.name.casefold() == name.casefold():
found.append(entry.pid)
processing = kernel.Process32NextW(handle, ctypes.byref(entry))
if ctypes.get_last_error() != 18: # ERROR_NO_MORE_FILES
raise ctypes.WinError(ctypes.get_last_error())
return found
finally:
kernel.CloseHandle(handle)
def query_owners(names, *, timeout_seconds=10): def query_owners(names, *, timeout_seconds=10):
names = tuple(names) names = tuple(names)
if not names or any(not re.fullmatch(r'[\w.-]+\.exe', name, re.I) for name in names): if not names or any(not re.fullmatch(r'[\w.-]+\.exe', name, re.I) for name in names):
+24 -2
View File
@@ -27,7 +27,7 @@ def test_status_scan_delivers_progress_after_each_record(tmp_path):
def test_catalog_registration_only_skips_project_identities(tmp_path, monkeypatch, include_identity, unknown_foreign): def test_catalog_registration_only_skips_project_identities(tmp_path, monkeypatch, include_identity, unknown_foreign):
import win32com.client import win32com.client
import win32process import win32process
from cbb_refresh_verify import mentor_adapter from cbb_refresh_verify import mentor_adapter, owner_probe
lmc = tmp_path / 'lib.lmc' lmc = tmp_path / 'lib.lmc'
lmc.touch() lmc.touch()
@@ -46,6 +46,7 @@ def test_catalog_registration_only_skips_project_identities(tmp_path, monkeypatc
previous = [(321, str(exe), '', 0)] if unknown_foreign else [] previous = [(321, str(exe), '', 0)] if unknown_foreign else []
snapshots = iter([previous, [*previous, (123, str(exe), '', 0)]]) snapshots = iter([previous, [*previous, (123, str(exe), '', 0)]])
monkeypatch.setattr(mentor_adapter, '_process_details', lambda _: next(snapshots)) monkeypatch.setattr(mentor_adapter, '_process_details', lambda _: next(snapshots))
monkeypatch.setattr(owner_probe, 'snapshot_process_ids', lambda _: [])
if unknown_foreign: if unknown_foreign:
exe.parent.mkdir(parents=True) exe.parent.mkdir(parents=True)
exe.write_bytes(b'library manager') exe.write_bytes(b'library manager')
@@ -66,6 +67,26 @@ def test_catalog_registration_only_skips_project_identities(tmp_path, monkeypatc
assert hashed == ([project] if include_identity else []) assert hashed == ([project] if include_identity else [])
def test_catalog_reports_exact_same_library_before_slow_owner_lookup(tmp_path, monkeypatch):
import win32com.client
from cbb_refresh_verify import mentor_adapter, owner_probe
library = tmp_path / 'lib.lmc'
library.touch()
monkeypatch.setattr(native, '_current_desktop', lambda: (None, 'CbbManagement_test'))
monkeypatch.setattr(owner_probe, 'snapshot_process_ids', lambda name: [123], raising=False)
monkeypatch.setattr(native, '_open_catalog_manager_library', lambda pid: library)
monkeypatch.setattr(mentor_adapter, '_process_details', lambda name: pytest.fail('slow owner lookup'))
monkeypatch.setattr(win32com.client, 'DispatchEx', lambda name: pytest.fail('busy library was opened'))
with pytest.raises(native.NativeOperationError, match='LIBRARY_MANAGER_BUSY.*123') as caught:
native._catalog_com({'operation': 'catalog', 'worker_role': 'catalog_readonly',
'include_engineering_identity': False, 'library': str(library),
'desktop': 'CbbManagement_test', 'mentor_home': str(tmp_path)}, tmp_path)
assert caught.value.safe_to_continue is True
assert caught.value.blocking_manager_pids == (123,)
@pytest.mark.parametrize('scope', ['foreign', 'same', 'shared', 'unknown', 'switched', 'occupied']) @pytest.mark.parametrize('scope', ['foreign', 'same', 'shared', 'unknown', 'switched', 'occupied'])
def test_catalog_distinguishes_foreign_and_conflicting_manager(tmp_path, monkeypatch, scope): def test_catalog_distinguishes_foreign_and_conflicting_manager(tmp_path, monkeypatch, scope):
target = tmp_path/'target'/'lib.lmc' target = tmp_path/'target'/'lib.lmc'
@@ -99,7 +120,7 @@ def test_catalog_distinguishes_foreign_and_conflicting_manager(tmp_path, monkeyp
@pytest.mark.parametrize('title_resolved', [True, False]) @pytest.mark.parametrize('title_resolved', [True, False])
def test_catalog_rejects_reused_foreign_com_proxy_without_mutating_it(tmp_path, monkeypatch, title_resolved): def test_catalog_rejects_reused_foreign_com_proxy_without_mutating_it(tmp_path, monkeypatch, title_resolved):
import win32com.client import win32com.client
from cbb_refresh_verify import mentor_adapter from cbb_refresh_verify import mentor_adapter, owner_probe
target = tmp_path/'target'/'lib.lmc' target = tmp_path/'target'/'lib.lmc'
other = tmp_path/'other'/'lib.lmc' other = tmp_path/'other'/'lib.lmc'
@@ -112,6 +133,7 @@ def test_catalog_rejects_reused_foreign_com_proxy_without_mutating_it(tmp_path,
monkeypatch.setitem(native._BINARY_PROOF, 'lm/win32/bin/LibraryManager.exe', native.hash_file(exe)) monkeypatch.setitem(native._BINARY_PROOF, 'lm/win32/bin/LibraryManager.exe', native.hash_file(exe))
before = [(123, 'LibraryManager.exe', f'LibraryManager.exe "{other}"', 0)] before = [(123, 'LibraryManager.exe', f'LibraryManager.exe "{other}"', 0)]
monkeypatch.setattr(mentor_adapter, '_process_details', lambda _: before) monkeypatch.setattr(mentor_adapter, '_process_details', lambda _: before)
monkeypatch.setattr(owner_probe, 'snapshot_process_ids', lambda _: [])
monkeypatch.setattr(native, '_open_catalog_manager_library', lambda _: other if title_resolved else None) monkeypatch.setattr(native, '_open_catalog_manager_library', lambda _: other if title_resolved else None)
monkeypatch.setattr(native, '_current_desktop', monkeypatch.setattr(native, '_current_desktop',
lambda: (SimpleNamespace(EnumDesktopWindows=lambda: []), 'CbbManagement_test')) lambda: (SimpleNamespace(EnumDesktopWindows=lambda: []), 'CbbManagement_test'))
+12 -13
View File
@@ -326,20 +326,19 @@ def test_recovery_scope_uses_interrupted_block_instead_of_new_selection(tmp_path
def test_probe_timeout_reports_last_io_phase_and_path(tmp_path, monkeypatch): def test_probe_timeout_reports_last_io_phase_and_path(tmp_path, monkeypatch):
from cbb_refresh_verify import file_probe from cbb_refresh_verify import file_probe
import sys from pathlib import Path
script = tmp_path/'slow_probe.py' from types import SimpleNamespace
library = tmp_path/'lib.lmc' library = tmp_path/'lib.lmc'
script.write_text(
"import json, sys, time\n" def start(command, **kwargs):
"from pathlib import Path\n" Path(command[-1]).with_name('progress.json').write_text(
"job = Path(sys.argv[-1])\n" '{"stage": "open_exclusive", "path": "SymbolLibs/icdb.dat"}', 'utf-8')
"job.with_name('progress.json').write_text(json.dumps(" return SimpleNamespace(stdin=SimpleNamespace(close=lambda: None), wait=lambda _: 0)
"{'stage': 'open_exclusive', 'path': 'SymbolLibs/icdb.dat'}))\n"
"time.sleep(30)\n", monkeypatch.setattr(file_probe.subprocess, 'Popen', start)
encoding='utf-8') ticks = iter([0., 1., 1.])
start = file_probe.subprocess.Popen monkeypatch.setattr(file_probe.time, 'monotonic', lambda: next(ticks))
monkeypatch.setattr(file_probe.subprocess, 'Popen',
lambda command, **kwargs: start([sys.executable, str(script), command[-1]], **kwargs))
with pytest.raises(TimeoutError, match=r'FILE_PROBE_TIMEOUT.*open_exclusive.*SymbolLibs/icdb.dat'): with pytest.raises(TimeoutError, match=r'FILE_PROBE_TIMEOUT.*open_exclusive.*SymbolLibs/icdb.dat'):
with file_probe.hold_release_files(library, timeout_seconds=.7): with file_probe.hold_release_files(library, timeout_seconds=.7):
pytest.fail('a timed-out probe cannot prove release') pytest.fail('a timed-out probe cannot prove release')