fix: preserve unknown assets and retained export-copy ownership
This commit is contained in:
1 parent
55a82fdc5f
commit
f21781f170
8 files changed
+312
-10
No files matched your search
@@ -66,8 +66,11 @@ def has_blocker(library):
|
||||
def _persist_blocker(library, status='OWNER_RELEASE_UNCONFIRMED', *, lease_id):
|
||||
path = blocker_path(library)
|
||||
pending = path.with_suffix('.pending')
|
||||
previous = checkpoint_record(path)
|
||||
export_record = ({'export_analysis': previous['export_analysis']}
|
||||
if previous and previous['lease_id'] == lease_id and 'export_analysis' in previous else {})
|
||||
with pending.open('w', encoding='utf-8') as stream:
|
||||
json.dump({'protocol': 'cbb-refresh-verify-library-lease', 'version': 1,
|
||||
json.dump({**export_record, 'protocol': 'cbb-refresh-verify-library-lease', 'version': 1,
|
||||
'lease_id': lease_id, 'library': str(library), 'status': status,
|
||||
'pid': os.getpid(), 'time': datetime.now(timezone.utc).isoformat()}, stream)
|
||||
stream.flush(); os.fsync(stream.fileno())
|
||||
@@ -159,6 +162,9 @@ class LibraryLock:
|
||||
if not self.entered:
|
||||
return
|
||||
owner = _owners[self.key]
|
||||
checkpoint = checkpoint_record(blocker_path(self.library))
|
||||
if checkpoint is not None and 'export_analysis' in checkpoint:
|
||||
owner['retained'] = True
|
||||
if self.safe_to_release is not None:
|
||||
try:
|
||||
safe = self.safe_to_release() is True
|
||||
@@ -237,7 +243,8 @@ def _enter_maintenance(lease):
|
||||
0, None, win32con.OPEN_ALWAYS, win32con.FILE_ATTRIBUTE_NORMAL, None)
|
||||
# All target/process/address/exclusive-file checks finish BEFORE
|
||||
# any old checkpoint replacement. Keep the exact sidecar open.
|
||||
with lease.maintenance_guard() as proof:
|
||||
from .native_export_guard import prove_export_copies_released
|
||||
with prove_export_copies_released(lease.library), lease.maintenance_guard() as proof:
|
||||
if (marker.read_bytes() if marker.exists() else None) != old:
|
||||
raise LibraryBusy('维护检查期间检查点变化')
|
||||
if old is not None:
|
||||
@@ -284,6 +291,9 @@ def _prove_library_released(library):
|
||||
import pythoncom, win32com.client, win32con, win32file
|
||||
from .scoped_manifest import scan_tree
|
||||
from .native_management import _retained_workers
|
||||
from .native_export_guard import assert_retained_exports_idle, prove_export_copies_released
|
||||
from .native_engineering_identity import _OWNER_NAMES
|
||||
assert_retained_exports_idle()
|
||||
if any(worker.poll() is None for worker in _retained_workers):
|
||||
raise LibraryBusy('原生管理工作进程尚未返回,不能解除协调阻止。')
|
||||
from .com_runtime import initialize_com, uninitialize_com
|
||||
@@ -291,7 +301,7 @@ def _prove_library_released(library):
|
||||
try:
|
||||
service = win32com.client.GetObject('winmgmts:')
|
||||
names = ('LibraryManager.exe', 'ExpeditionPCB.exe', 'viewdraw.exe',
|
||||
'iCDBProjectBackup.exe', 'ReuseBlockImporter.exe', 'CleanWGLib.exe')
|
||||
'iCDBProjectBackup.exe', 'ReuseBlockImporter.exe', 'CleanWGLib.exe', *sorted(_OWNER_NAMES))
|
||||
query = 'SELECT ProcessId, Name FROM Win32_Process WHERE ' + ' OR '.join(
|
||||
f"Name='{name}'" for name in names)
|
||||
owners = [{'pid': int(item.ProcessId), 'name': str(item.Name)} for item in service.ExecQuery(query)]
|
||||
@@ -307,11 +317,12 @@ def _prove_library_released(library):
|
||||
if Path(library).resolve() not in native:
|
||||
raise LibraryBusy('目标库身份缺失,不能解除协调阻止。')
|
||||
with ExitStack() as stack:
|
||||
export_copies = stack.enter_context(prove_export_copies_released(library))
|
||||
for path in native:
|
||||
handle = win32file.CreateFile(str(path), win32con.GENERIC_READ, 0, None,
|
||||
win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None)
|
||||
stack.callback(handle.Close)
|
||||
yield {'native_owners': owners, 'addresses': addresses,
|
||||
yield {'native_owners': owners, 'addresses': addresses, 'export_copies': export_copies,
|
||||
'exclusive_files': [str(path) for path in native]}
|
||||
finally:
|
||||
uninitialize_com(initialized)
|
||||
|
||||
@@ -15,11 +15,14 @@ from uuid import uuid4
|
||||
def assert_native_idle():
|
||||
import win32com.client
|
||||
from .native_management import _retained_workers
|
||||
from .native_export_guard import assert_retained_exports_idle
|
||||
from .native_engineering_identity import _OWNER_NAMES
|
||||
assert_retained_exports_idle()
|
||||
if any(worker.poll() is None for worker in _retained_workers):
|
||||
raise ValueError('MAINTENANCE_OWNER_ACTIVE: 管理工作进程尚未返回')
|
||||
names = ('ExpeditionPCB.exe', 'LibraryManager.exe', 'viewdraw.exe', 'iCDBProjectBackup.exe',
|
||||
'ReuseBlockImporter.exe', 'CleanWGLib.exe', 'cscript.exe', 'wscript.exe',
|
||||
'python.exe', 'pythonw.exe', 'CbbRefreshVerify.exe')
|
||||
'python.exe', 'pythonw.exe', 'CbbRefreshVerify.exe', *sorted(_OWNER_NAMES))
|
||||
service = win32com.client.GetObject('winmgmts:')
|
||||
query = 'SELECT ProcessId, Name, CommandLine FROM Win32_Process WHERE ' + ' OR '.join(
|
||||
f"Name='{name}'" for name in names)
|
||||
|
||||
@@ -203,7 +203,17 @@ def asset_identity(source, expected_library):
|
||||
assets = {}
|
||||
for relative, record in files.items():
|
||||
path = root/relative
|
||||
if path == main_database/'icdb.dat' or any(path.is_relative_to(p) for p in runtime):
|
||||
known_runtime = False
|
||||
for server_root in runtime:
|
||||
if not path.is_relative_to(server_root): continue
|
||||
parts = path.relative_to(server_root).parts
|
||||
folded = tuple(p.casefold() for p in parts)
|
||||
known_runtime = (len(parts) > 1 and folded[0] in ('log', 'dbcheck', 'dbrestore', 'dbupgrade', 'pimlog')
|
||||
or folded in (('events', 'events.dat'), ('events', 'events.idx'))
|
||||
or len(parts) == 2 and folded[0] == 'plog'
|
||||
and re.fullmatch(r'\d{4}\.\d{2}\.\d{2}\.guid\.\d+\.txt', parts[1]) is not None)
|
||||
break
|
||||
if path == main_database/'icdb.dat' or known_runtime:
|
||||
continue
|
||||
if path in projects:
|
||||
data = _normalized_project(path, expected_library)
|
||||
@@ -273,6 +283,7 @@ def _run_exports(project, root, mentor_home, timeout_seconds):
|
||||
"""Observe exact exporter/descendant handles; never kill a database owner."""
|
||||
import win32api, win32con, win32event, pywintypes
|
||||
root = Path(root)
|
||||
_write_json(root/'export-launch.json', {'started': False})
|
||||
before = _process_snapshot()
|
||||
if any(p['name'].casefold() in _OWNER_NAMES for p in before):
|
||||
return {'success': False, 'safe_to_continue': False, 'detail': 'An existing iCDB owner prevents isolated identity export.'}
|
||||
@@ -300,6 +311,7 @@ def _run_exports(project, root, mentor_home, timeout_seconds):
|
||||
try:
|
||||
deadline = time.monotonic()+float(timeout_seconds)
|
||||
with (root/(kind+'-stdout.txt')).open('wb') as output:
|
||||
_write_json(root/'export-launch.json', {'started': True})
|
||||
process = subprocess.Popen(command, stdout=output, stderr=subprocess.STDOUT,
|
||||
creationflags=subprocess.CREATE_NO_WINDOW)
|
||||
record['pid'] = process.pid
|
||||
@@ -348,6 +360,7 @@ def capture_identity(source, evidence_root, *, expected_library, owner_library,
|
||||
from .backup_recovery import _align_library
|
||||
from .library_lock import LibraryLock, owned_snapshot
|
||||
from .scoped_manifest import copy_verified
|
||||
from .native_export_guard import begin_export_analysis, finish_export_analysis
|
||||
import win32event, win32con
|
||||
source, pcb, top = source_project(source)
|
||||
root = Path(evidence_root).absolute()
|
||||
@@ -375,10 +388,13 @@ def capture_identity(source, evidence_root, *, expected_library, owner_library,
|
||||
_align_library(clone, clone_pcb, Path(expected_library))
|
||||
if any((root/'project').rglob('sAddress.adr')):
|
||||
raise ValueError('Analysis source contains an unresolved database address.')
|
||||
export_token = begin_export_analysis(library, root, clone)
|
||||
owner_safe = False
|
||||
native = _run_exports(clone, root, mentor_home, timeout_seconds)
|
||||
owner_safe = native.get('safe_to_continue') is True
|
||||
_write_json(root/'native-outcome.json', native)
|
||||
if native.get('safe_to_continue') is True:
|
||||
finish_export_analysis(library, export_token)
|
||||
owner_safe = True
|
||||
if not owner_safe or not native.get('success'):
|
||||
outcome = IdentityOutcome(None, owner_safe, native.get('detail', 'Native export failed.'), root)
|
||||
else:
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
"""Export-copy ownership bound to the existing per-library lease checkpoint."""
|
||||
from contextlib import contextmanager, ExitStack
|
||||
import json
|
||||
from pathlib import Path
|
||||
from uuid import uuid4
|
||||
|
||||
from .management import _write_json
|
||||
|
||||
|
||||
def assert_retained_exports_idle():
|
||||
import win32con, win32event
|
||||
from .native_engineering_identity import _retained_exports
|
||||
from .library_lock import LibraryBusy
|
||||
for process, handles in _retained_exports:
|
||||
if process.poll() is None or any(win32event.WaitForSingleObject(handle, 0) != win32con.WAIT_OBJECT_0
|
||||
for handle in handles.values()):
|
||||
raise LibraryBusy('Native identity exporter or descendant has not released.')
|
||||
|
||||
|
||||
def begin_export_analysis(library, root, project):
|
||||
from .library_lock import _guard, blocker_path, checkpoint_record, LibraryBusy
|
||||
from .management_transaction import current_lease
|
||||
library, root, project = Path(library).resolve(), Path(root).resolve(), Path(project).resolve()
|
||||
owner = current_lease(library)
|
||||
if (project.parent != root/'project' or not project.is_file()
|
||||
or root.is_relative_to(library.parent) or library.parent.is_relative_to(root)):
|
||||
raise LibraryBusy('Export-copy ownership paths are not independent and exact.')
|
||||
record = {'protocol': 'cbb-native-export-analysis', 'version': 1, 'token': uuid4().hex,
|
||||
'library': str(library), 'lease_id': owner['lease_id'], 'supervisor_pid': owner['supervisor_pid'],
|
||||
'analysis_root': str(root), 'project': str(project)}
|
||||
with _guard:
|
||||
marker = blocker_path(library)
|
||||
checkpoint = checkpoint_record(marker)
|
||||
if (checkpoint is None or checkpoint['lease_id'] != owner['lease_id']
|
||||
or 'export_analysis' in checkpoint):
|
||||
raise LibraryBusy('A prior export analysis is unresolved or the lease changed.')
|
||||
_write_json(root/'export-owner.json', record)
|
||||
_write_json(marker, {**checkpoint, 'export_analysis': [record]})
|
||||
return record['token']
|
||||
|
||||
|
||||
@contextmanager
|
||||
def prove_export_copies_released(library):
|
||||
"""Fresh process and exclusive-copy proof, including after interpreter exit."""
|
||||
import win32file, win32con, pywintypes
|
||||
from .library_lock import blocker_path, checkpoint_record, _supervisor_alive, LibraryBusy
|
||||
from .native_engineering_identity import _process_snapshot, _OWNER_NAMES
|
||||
from .scoped_manifest import scan_tree
|
||||
assert_retained_exports_idle()
|
||||
library = Path(library).resolve()
|
||||
marker = blocker_path(library)
|
||||
checkpoint = checkpoint_record(marker)
|
||||
if marker.exists() and checkpoint is None:
|
||||
raise LibraryBusy('Invalid library checkpoint cannot release export ownership.')
|
||||
if checkpoint is None or 'export_analysis' not in checkpoint:
|
||||
yield []
|
||||
return
|
||||
records = checkpoint['export_analysis']
|
||||
if not isinstance(records, list) or not records:
|
||||
raise LibraryBusy('Invalid export-analysis ownership record.')
|
||||
owners = [p for p in _process_snapshot() if p['name'].casefold() in _OWNER_NAMES]
|
||||
if owners: raise LibraryBusy(f'Native identity owners remain active: {owners}')
|
||||
copies = []
|
||||
with ExitStack() as stack:
|
||||
for record in records:
|
||||
try:
|
||||
root, project = Path(record['analysis_root']), Path(record['project'])
|
||||
if (record.get('protocol') != 'cbb-native-export-analysis' or record.get('version') != 1
|
||||
or not record.get('token') or record['lease_id'] != checkpoint['lease_id']
|
||||
or record['supervisor_pid'] != checkpoint['pid']
|
||||
or Path(record['library']).resolve() != library
|
||||
or not root.is_absolute() or not project.is_absolute() or root.resolve() != root
|
||||
or project.parent != root/'project' or not project.is_file()
|
||||
or root.resolve().is_relative_to(library.parent)
|
||||
or library.parent.is_relative_to(root.resolve())
|
||||
or json.loads((root/'export-owner.json').read_text(encoding='utf-8')) != record):
|
||||
raise ValueError('Export record does not match the exact library, lease and copy.')
|
||||
processes = [root/(kind+'-process.json') for kind in ('ascii', 'csv', 'edif')
|
||||
if (root/(kind+'-process.json')).exists()]
|
||||
if not processes:
|
||||
launch = json.loads((root/'export-launch.json').read_text(encoding='utf-8'))
|
||||
if launch != {'started': False}:
|
||||
raise ValueError('Export launch has no confirmed process record.')
|
||||
for path in processes:
|
||||
process = json.loads(path.read_text(encoding='utf-8'))
|
||||
pids = process.get('observed_pids', []) + [process['pid']]
|
||||
if any(not isinstance(pid, int) or pid <= 0 for pid in pids):
|
||||
raise ValueError('Invalid export process identity.')
|
||||
if any(_supervisor_alive(pid) for pid in pids):
|
||||
raise LibraryBusy('A recorded export process or descendant remains alive.')
|
||||
entries = scan_tree(root/'project')
|
||||
if any(path.name.casefold() == 'saddress.adr' for path in entries):
|
||||
raise LibraryBusy('The retained analysis copy still has a database address.')
|
||||
databases = [path for path in entries if path.is_file()
|
||||
and path.name.casefold() in ('icdb.dat', 'layoutdb.lyt')]
|
||||
if not any(path.name.casefold() == 'icdb.dat' for path in databases):
|
||||
raise ValueError('The recorded analysis database is missing.')
|
||||
for path in databases:
|
||||
handle = win32file.CreateFile(str(path), win32con.GENERIC_READ, 0, None,
|
||||
win32con.OPEN_EXISTING, 0, None)
|
||||
stack.callback(handle.Close)
|
||||
copies.append(str(root/'project'))
|
||||
except (KeyError, TypeError, ValueError, OSError, pywintypes.error) as error:
|
||||
raise LibraryBusy(f'Export analysis release is not proven: {error}') from error
|
||||
yield copies
|
||||
|
||||
|
||||
def finish_export_analysis(library, token):
|
||||
from .library_lock import _guard, blocker_path, checkpoint_record, LibraryBusy
|
||||
with _guard, prove_export_copies_released(library):
|
||||
marker = blocker_path(library)
|
||||
checkpoint = checkpoint_record(marker)
|
||||
records = checkpoint.get('export_analysis', []) if checkpoint else []
|
||||
if len(records) != 1 or records[0].get('token') != token:
|
||||
raise LibraryBusy('Export ownership changed before confirmed cleanup.')
|
||||
del checkpoint['export_analysis']
|
||||
_write_json(marker, checkpoint)
|
||||
Reference in new issue
Block a user