fix: preserve mapped native paths and retain probe ownership guards
This commit is contained in:
1 parent
dd1fcea7e2
commit
46c3e72364
7 files changed
+365
-36
No files matched your search
@@ -27,6 +27,8 @@ class ManagementRequest:
|
||||
evidence_dir: Path = Path('management-evidence')
|
||||
top_level_block: str = ''
|
||||
timeout_seconds: float = 180
|
||||
mapped_drive: str = ''
|
||||
mapped_remote_root: str = ''
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -187,30 +189,36 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
|
||||
if request.operation not in ('add', 'update', 'remove'):
|
||||
raise ValueError('不支持的管理操作。')
|
||||
validate_name(request.name); validate_name(request.partition)
|
||||
library = Path(request.library).resolve(strict=True)
|
||||
from .network_path import absolute_preserving_drive
|
||||
library = absolute_preserving_drive(request.library)
|
||||
canonical_library = library.resolve(strict=True)
|
||||
library_root = canonical_library.parent
|
||||
if library.suffix.casefold() != '.lmc' or not library.is_file():
|
||||
raise ValueError('中心库必须为现有 LMC 文件。')
|
||||
evidence = Path(request.evidence_dir).resolve()
|
||||
if evidence.is_relative_to(library.parent) or library.parent.is_relative_to(evidence):
|
||||
if evidence.is_relative_to(library_root) or library_root.is_relative_to(evidence):
|
||||
raise ValueError('操作记录与备份必须位于目标中心库之外,且不能包含目标库。')
|
||||
capability = adapter.capabilities().get(request.operation, Capability(False, '未验证的原生接口'))
|
||||
if not capability.supported:
|
||||
return finish('UNSUPPORTED', capability.reason)
|
||||
for unfinished in unfinished_operations(evidence):
|
||||
if unfinished.get('library') and Path(unfinished['library']).resolve() == library:
|
||||
if unfinished.get('library') and Path(unfinished['library']).resolve() == canonical_library:
|
||||
return finish('BLOCKED', f'存在未完成/需恢复任务,禁止自动重放:{unfinished["evidence_path"]}', False)
|
||||
source = pcb = None
|
||||
if request.operation in ('add', 'update'):
|
||||
if request.source is None:
|
||||
raise ValueError('新增/更新需要完整来源工程。')
|
||||
source, pcb, top = source_project(request.source, request.top_level_block)
|
||||
if (source.is_relative_to(library.parent) or evidence.is_relative_to(source.parent)
|
||||
if (source.parent.is_relative_to(library_root) or library_root.is_relative_to(source.parent)
|
||||
or evidence.is_relative_to(source.parent)
|
||||
or source.parent.is_relative_to(evidence)):
|
||||
raise ValueError('来源工程、目标库与操作证据必须使用独立目录。')
|
||||
mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795')
|
||||
acquired = win32event.WaitForSingleObject(mutex, 0) in (win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED)
|
||||
if not acquired:
|
||||
return finish('BLOCKED', '已有 CBB 校验/管理/恢复任务运行。', False)
|
||||
if hasattr(adapter, 'bind_library_mapping'):
|
||||
adapter.bind_library_mapping(request.mapped_drive, request.mapped_remote_root)
|
||||
with LibraryLock(library, safe_to_release=lambda: owner_safe):
|
||||
root = evidence/('management-' + uuid4().hex)
|
||||
root.mkdir(parents=True, exist_ok=False)
|
||||
@@ -232,7 +240,7 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
|
||||
owner_safe = False
|
||||
before = adapter.catalog(library, root/'before')
|
||||
owner_safe = before.safe_to_continue
|
||||
if not owner_safe or Path(before.library).resolve() != library or before.flow != 1:
|
||||
if not owner_safe or Path(before.library).resolve() != canonical_library or before.flow != 1:
|
||||
return finish('BLOCKED', '原生目录身份/流程或所有者释放未确认。仅支持已验证 DxDesigner 流程。', owner_safe)
|
||||
same_name = [entry for entry in before.entries if entry.name.casefold() == request.name.casefold()]
|
||||
matches = [entry for entry in same_name if entry.partition == request.partition and entry.name == request.name]
|
||||
@@ -246,7 +254,7 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
|
||||
idle_check(library, target_project, target_pcb)
|
||||
scope = ManifestScope.library(request.name, library.name)
|
||||
checkpoint('backup')
|
||||
original = copy_verified(library.parent, root/'library-before', scope=scope, progress=progress)
|
||||
original = copy_verified(library_root, root/'library-before', scope=scope, progress=progress)
|
||||
_write_json(root/'library-before-manifest.json', original)
|
||||
staged = request
|
||||
identity = None
|
||||
@@ -258,7 +266,7 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
|
||||
identity = engineering_identity(staged.source)
|
||||
if build_manifest(source.parent) != source_manifest:
|
||||
raise OSError('来源工程在暂存期间变化。')
|
||||
if build_manifest(library.parent, scope=scope) != original:
|
||||
if build_manifest(library_root, scope=scope) != original:
|
||||
raise OSError('备份后中心库内容变化,停止写入。')
|
||||
if request.operation in ('remove', 'update'):
|
||||
checkpoint('native_remove')
|
||||
@@ -272,7 +280,7 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
|
||||
owner_safe = False
|
||||
after = adapter.catalog(library, root/'after-remove')
|
||||
owner_safe = after.safe_to_continue
|
||||
if (not owner_safe or Path(after.library).resolve() != library or after.flow != 1
|
||||
if (not owner_safe or Path(after.library).resolve() != canonical_library or after.flow != 1
|
||||
or any(e.name == request.name and e.partition == request.partition for e in after.entries)):
|
||||
return finish('RECOVERY_REQUIRED', '原生移除后目录未确认目标缺失。', False)
|
||||
removed = True
|
||||
@@ -292,7 +300,7 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
|
||||
owner_safe = after.safe_to_continue
|
||||
matches = [entry for entry in after.entries if entry.name == request.name
|
||||
and entry.partition == request.partition]
|
||||
if (not owner_safe or Path(after.library).resolve() != library or after.flow != 1
|
||||
if (not owner_safe or Path(after.library).resolve() != canonical_library or after.flow != 1
|
||||
or len(matches) != 1 or matches[0].engineering_identity != identity):
|
||||
return finish('RECOVERY_REQUIRED', '原生新增后名称、分区或来源工程内容未确认一致。', False)
|
||||
uploaded = True
|
||||
@@ -302,7 +310,8 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
|
||||
# Adapter catalog cannot return until its exact native owner exits.
|
||||
checkpoint('verify')
|
||||
owner_safe = False
|
||||
verified = verifier(VerifyRequest(library, request.name, root/'verify'), progress=progress)
|
||||
verified = verifier(VerifyRequest(library, request.name, root/'verify',
|
||||
mapped_drive=request.mapped_drive, mapped_remote_root=request.mapped_remote_root), progress=progress)
|
||||
owner_safe = verified.safe_to_continue
|
||||
checkpoint('verified', verification=asdict(verified))
|
||||
good = verified.status == 'PASS' and verified.library_flag == 'GREEN' and owner_safe
|
||||
|
||||
@@ -18,6 +18,7 @@ from uuid import uuid4
|
||||
from .management import (Capability, Catalog, CatalogEntry, NativeOutcome,
|
||||
engineering_identity, validate_name, _write_json)
|
||||
from .scoped_manifest import hash_file
|
||||
from .network_path import absolute_preserving_drive
|
||||
|
||||
_retained_workers = []
|
||||
_BINARY_PROOF = {
|
||||
@@ -55,6 +56,12 @@ class NativeManagementAdapter:
|
||||
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
|
||||
self.mapped_drive = ''
|
||||
self.mapped_remote_root = ''
|
||||
|
||||
def bind_library_mapping(self, drive, remote_root):
|
||||
self.mapped_drive = drive or ''
|
||||
self.mapped_remote_root = remote_root or ''
|
||||
|
||||
def capabilities(self):
|
||||
reason = ''
|
||||
@@ -74,14 +81,36 @@ class NativeManagementAdapter:
|
||||
}
|
||||
|
||||
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 ''),
|
||||
'mapped_drive': job.get('mapped_drive', self.mapped_drive),
|
||||
'mapped_remote_root': job.get('mapped_remote_root', self.mapped_remote_root),
|
||||
'timeout_seconds': timeout, 'supervisor_pid': os.getpid()}
|
||||
if job['operation'] == 'probe_create_add':
|
||||
# Prepare the fixed NEW fixture before a native owner can start.
|
||||
# The parent owns its sidecar for the entire create/add invocation.
|
||||
from .library_lock import LibraryLock
|
||||
library = absolute_preserving_drive(evidence)/'fixture/mentor_lib.lmc'
|
||||
if Path(job['library']).resolve() != library.resolve() or not job.get('probe_token'):
|
||||
raise ValueError('隔离创建目标必须为本次工作目录内的新库。')
|
||||
library.parent.mkdir(exist_ok=False)
|
||||
_write_json(evidence/'probe-prepared.json', {'library': str(library), 'token': job['probe_token'],
|
||||
'supervisor_pid': os.getpid()})
|
||||
owner_safe = True
|
||||
with LibraryLock(library, safe_to_release=lambda: owner_safe):
|
||||
owner_safe = False
|
||||
result = self._launch_worker(job, evidence)
|
||||
owner_safe = result.get('safe_to_continue') is True
|
||||
return result
|
||||
return self._launch_worker(job, evidence)
|
||||
|
||||
def _launch_worker(self, job, evidence):
|
||||
from .desktop_worker import DesktopWorker
|
||||
request_path = evidence/'request.json'
|
||||
desktop, timeout = job['desktop'], job['timeout_seconds']
|
||||
_write_json(request_path, job)
|
||||
command = ([sys.executable] if getattr(sys, 'frozen', False)
|
||||
else [sys.executable, '-m', 'cbb_refresh_verify'])
|
||||
@@ -106,7 +135,7 @@ class NativeManagementAdapter:
|
||||
worker.close()
|
||||
|
||||
def catalog(self, library, evidence):
|
||||
result = self._worker({'operation': 'catalog', 'library': str(library)}, evidence)
|
||||
result = self._worker({'operation': 'catalog', 'library': str(absolute_preserving_drive(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']),
|
||||
@@ -119,8 +148,9 @@ class NativeManagementAdapter:
|
||||
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),
|
||||
result = self._worker({'operation': 'remove', 'library': str(absolute_preserving_drive(request.library)),
|
||||
'name': request.name, 'partition': request.partition,
|
||||
'mapped_drive': request.mapped_drive, 'mapped_remote_root': request.mapped_remote_root,
|
||||
'timeout_seconds': request.timeout_seconds}, evidence)
|
||||
return NativeOutcome(bool(result.get('success')), bool(result.get('safe_to_continue')), result.get('detail', ''))
|
||||
|
||||
@@ -135,22 +165,36 @@ class NativeManagementAdapter:
|
||||
|
||||
|
||||
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()
|
||||
"""Validate a NEW fixed fixture already guarded by its supervisor."""
|
||||
from .library_lock import blocker_path, checkpoint_record
|
||||
expected = absolute_preserving_drive(root)/'fixture/mentor_lib.lmc'
|
||||
try:
|
||||
prepared = json.loads((Path(root)/'probe-prepared.json').read_text(encoding='utf-8'))
|
||||
guard = checkpoint_record(blocker_path(expected))
|
||||
allowed = {'.mentor_lib.cbb-upload.lock', '.mentor_lib.cbb-upload.blocked.json'}
|
||||
valid = (Path(job['library']).resolve() == expected.resolve() and not expected.exists()
|
||||
and expected.parent.is_dir() and {p.name for p in expected.parent.iterdir()} == allowed
|
||||
and prepared.get('token') == job.get('probe_token') and bool(job.get('probe_token'))
|
||||
and Path(prepared['library']).resolve() == expected.resolve()
|
||||
and prepared.get('supervisor_pid') == job.get('supervisor_pid')
|
||||
and guard is not None and guard['pid'] == job.get('supervisor_pid')
|
||||
and Path(guard['library']).resolve() == expected.resolve()
|
||||
and guard['status'] == 'OPERATION_IN_PROGRESS')
|
||||
except (OSError, ValueError, KeyError):
|
||||
valid = False
|
||||
if not valid:
|
||||
raise ValueError('诊断只能创建当前监督进程已持锁的全新 fixture/mentor_lib.lmc。')
|
||||
return expected
|
||||
|
||||
|
||||
def validate_probe_readd(job, root):
|
||||
expected = Path(root).parent.resolve()/'native-add/fixture/mentor_lib.lmc'
|
||||
expected = absolute_preserving_drive(root).parent/'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')
|
||||
if (Path(job['library']).resolve() != expected.resolve() or not expected.is_file()
|
||||
or not owner.get('library') or Path(owner['library']).resolve() != expected.resolve() or not job.get('probe_token')
|
||||
or owner.get('token') != job['probe_token']):
|
||||
raise ValueError('重新导入诊断仅允许本次原生新建的固定隔离库。')
|
||||
return expected
|
||||
@@ -288,18 +332,19 @@ def run_isolated_probe(source, root, name, *, mentor_home=None, replacement_sour
|
||||
from .scoped_manifest import ManifestScope
|
||||
from .scoped_manifest import copy_verified, build_manifest
|
||||
import pythoncom, win32con, win32event
|
||||
root = Path(root).resolve()
|
||||
root = absolute_preserving_drive(root)
|
||||
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):
|
||||
if root.resolve().is_relative_to(source.parent) or source.parent.is_relative_to(root.resolve()):
|
||||
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}
|
||||
owner_safe = True
|
||||
from .com_runtime import initialize_com, uninitialize_com
|
||||
initialized = initialize_com()
|
||||
try:
|
||||
@@ -314,13 +359,20 @@ def run_isolated_probe(source, root, name, *, mentor_home=None, replacement_sour
|
||||
if not adapter.capabilities()['remove'].supported:
|
||||
raise RuntimeError('诊断要求已识别的 EE7.9.5 原生安装。')
|
||||
library = root/'native-add/fixture/mentor_lib.lmc'
|
||||
def read_catalog(evidence):
|
||||
nonlocal owner_safe
|
||||
owner_safe = False
|
||||
catalog = adapter.catalog(library, evidence)
|
||||
owner_safe = catalog.safe_to_continue
|
||||
return catalog
|
||||
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')
|
||||
with LibraryLock(library, safe_to_release=lambda: owner_safe):
|
||||
catalog = read_catalog(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
|
||||
@@ -330,35 +382,39 @@ def run_isolated_probe(source, root, name, *, mentor_home=None, replacement_sour
|
||||
_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):
|
||||
if replacement.is_relative_to(root.resolve()) or root.resolve().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):
|
||||
with LibraryLock(library, safe_to_release=lambda: owner_safe):
|
||||
copy_verified(library.parent, root/'library-before-update',
|
||||
scope=ManifestScope.library(name, library.name))
|
||||
request = ManagementRequest('remove', library, name, evidence_dir=root)
|
||||
owner_safe = False
|
||||
removal = adapter.remove(request, root/'native-remove')
|
||||
owner_safe = removal.safe_to_continue
|
||||
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')
|
||||
missing = read_catalog(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)
|
||||
owner_safe = False
|
||||
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')
|
||||
owner_safe = readd.get('safe_to_continue') is True
|
||||
record['update']['readd'] = readd
|
||||
if readd.get('success') and readd.get('safe_to_continue'):
|
||||
updated = adapter.catalog(library, root/'reopen-update')
|
||||
updated = read_catalog(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
|
||||
@@ -483,7 +539,7 @@ def _catalog_com(job, root):
|
||||
else:
|
||||
if job['operation'] == 'probe_readd':
|
||||
validate_probe_readd(job, root)
|
||||
library = app.OpenLibrary(str(Path(job['library']).resolve()))
|
||||
library = app.OpenLibrary(str(absolute_preserving_drive(job['library'])))
|
||||
if refused:
|
||||
raise RuntimeError('目录读取需要升级中心库或选择流程;已拒绝,目标未获准自动升级。')
|
||||
if library is None or Path(str(library.FullName)).resolve() != Path(job['library']).resolve():
|
||||
@@ -541,6 +597,9 @@ def management_worker_main(request_path):
|
||||
_, desktop = _current_desktop()
|
||||
if desktop != job['desktop'] or not desktop.startswith('CbbManagement_'):
|
||||
raise RuntimeError('原生管理操作仅允许在本次私有桌面执行。')
|
||||
if job.get('mapped_drive') and job.get('mapped_remote_root'):
|
||||
from .network_path import ensure_mapped_drive_visible
|
||||
ensure_mapped_drive_visible(job['mapped_drive'], job['mapped_remote_root'])
|
||||
if job['operation'] in ('catalog', 'probe_create_add', 'probe_readd'):
|
||||
result = _catalog_native(job, root)
|
||||
elif job['operation'] == 'remove':
|
||||
|
||||
@@ -306,7 +306,9 @@ class MainWindow(QWidget):
|
||||
return
|
||||
def request(name, partition):
|
||||
return ManagementRequest(operation, Path(self.mentor_lmc_path or self.loaded_path), name,
|
||||
partition, evidence_dir=self.data_root/'management', timeout_seconds=self.timeout_spin.value())
|
||||
partition, evidence_dir=self.data_root/'management', timeout_seconds=self.timeout_spin.value(),
|
||||
mapped_drive=getattr(self.library_lease, 'drive', ''),
|
||||
mapped_remote_root=getattr(self.library_lease, 'remote_root', ''))
|
||||
requests = ([request('', 'Logical-Physical')] if operation == 'add' else
|
||||
[request(record.name, 'Logical-Physical' if record.logical_type == 'LP'
|
||||
and record.partition_name in ('Reusable Blocks', 'LP') else record.partition_name)
|
||||
|
||||
Reference in new issue
Block a user