fix: scope runtime release proof and bound native file probes
This commit is contained in:
1 parent
a1b38c242f
commit
b070837acb
10 files changed
+816
-77
No files matched your search
@@ -11,6 +11,13 @@ from uuid import uuid4
|
||||
|
||||
_guard = threading.RLock()
|
||||
_owners = {}
|
||||
_library_guards = {}
|
||||
|
||||
|
||||
def _library_guard(key):
|
||||
"""Serialize one lease without making slow resource probes global."""
|
||||
with _guard:
|
||||
return _library_guards.setdefault(key, threading.RLock())
|
||||
|
||||
|
||||
class LibraryBusy(OSError):
|
||||
@@ -82,10 +89,10 @@ def has_retained_library(library):
|
||||
return bool(owner and owner['retained'])
|
||||
|
||||
|
||||
def recheck_previous_release(library, evidence_dir, *, block_name=None, required=False, progress=None):
|
||||
def recheck_previous_release(library, evidence_dir, *, block_name=None, required=False, progress=None, stop=None):
|
||||
"""Historical records trigger fresh proof, never process termination or repair."""
|
||||
if not required:
|
||||
with _guard:
|
||||
with _library_guard(LibraryLock(library).key):
|
||||
owner = _owners.get(LibraryLock(library).key)
|
||||
marker = blocker_path(library)
|
||||
record = checkpoint_record(marker)
|
||||
@@ -108,7 +115,8 @@ def recheck_previous_release(library, evidence_dir, *, block_name=None, required
|
||||
logging.getLogger(__name__).warning('Release progress observer failed', exc_info=True)
|
||||
notify('previous_release_check', detail='正在复核历史记录对应的实际占用')
|
||||
try:
|
||||
proof = release_retained_library(library, evidence_dir, block_name=block_name)
|
||||
options = {'stop': stop} if stop is not None else {}
|
||||
proof = release_retained_library(library, evidence_dir, block_name=block_name, **options)
|
||||
except Exception as error:
|
||||
notify('previous_release_unconfirmed', detail=str(error))
|
||||
raise
|
||||
@@ -128,9 +136,14 @@ def _persist_blocker(library, status='OWNER_RELEASE_UNCONFIRMED', *, lease_id, b
|
||||
export_record['block_name'] = block_name
|
||||
elif previous and previous['lease_id'] == lease_id and 'block_name' in previous:
|
||||
export_record['block_name'] = previous['block_name']
|
||||
from .icdb_ownership import session_resource_scope
|
||||
scope = (previous.get('resource_scope') if previous and previous['lease_id'] == lease_id else None)
|
||||
scope = scope or session_resource_scope({'library': library, 'block': export_record.get('block_name')})
|
||||
with pending.open('w', encoding='utf-8') as stream:
|
||||
json.dump({**export_record, 'protocol': 'cbb-refresh-verify-library-lease', 'version': 1,
|
||||
'lease_id': lease_id, 'library': str(library), 'status': status,
|
||||
'lease_state': 'ACTIVE' if status == 'OPERATION_IN_PROGRESS' else 'RETAINED',
|
||||
'resource_scope': scope, 'blocked_resources': [], 'data_recovery_required': None,
|
||||
'machine': socket.gethostname(),
|
||||
'supervisor_created': win32process.GetProcessTimes(win32api.GetCurrentProcess())['CreationTime'].isoformat(),
|
||||
'pid': os.getpid(), 'time': datetime.now(timezone.utc).isoformat()}, stream)
|
||||
@@ -159,7 +172,7 @@ class LibraryLock:
|
||||
return lease
|
||||
|
||||
def __enter__(self):
|
||||
with _guard:
|
||||
with _library_guard(self.key):
|
||||
owner = _owners.get(self.key)
|
||||
if owner and owner['retained'] and owner['depth'] == 0 and owner.get('release_probe'):
|
||||
try:
|
||||
@@ -180,7 +193,7 @@ class LibraryLock:
|
||||
if self.maintenance_guard is not None:
|
||||
return _enter_maintenance(self)
|
||||
import win32con, win32file
|
||||
with _guard:
|
||||
with _library_guard(self.key):
|
||||
owner = _owners.get(self.key)
|
||||
if owner:
|
||||
if owner['thread'] != threading.get_ident() or owner['retained']:
|
||||
@@ -246,7 +259,7 @@ class LibraryLock:
|
||||
self.maintenance_mutex = None
|
||||
|
||||
def _exit_owned(self):
|
||||
with _guard:
|
||||
with _library_guard(self.key):
|
||||
if not self.entered:
|
||||
return
|
||||
owner = _owners[self.key]
|
||||
@@ -402,7 +415,7 @@ def _enter_maintenance(lease):
|
||||
try:
|
||||
acquired = win32event.WaitForSingleObject(mutex, 0) in (win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED)
|
||||
if not acquired: raise LibraryBusy('已有 CBB 操作运行,维护不能接续')
|
||||
with _guard:
|
||||
with _library_guard(lease.key):
|
||||
marker = blocker_path(lease.library)
|
||||
if marker.with_suffix('.pending').exists():
|
||||
raise LibraryBusy('未完成检查点写入,不能自动接续')
|
||||
@@ -455,7 +468,7 @@ def _enter_maintenance(lease):
|
||||
def owned_snapshot(path):
|
||||
"""Read only a lease held by this thread, never reopen an exclusive file."""
|
||||
import win32con, win32file
|
||||
with _guard:
|
||||
with _library_guard(_key(path)):
|
||||
owner = _owners.get(_key(path))
|
||||
if not owner or owner['thread'] != threading.get_ident() or owner['retained']:
|
||||
return None
|
||||
@@ -470,19 +483,16 @@ def owned_snapshot(path):
|
||||
|
||||
|
||||
@contextmanager
|
||||
def _prove_library_released(library, block_name=None, *, allow_unknown_checkpoint=False):
|
||||
def _prove_library_released(library, block_name=None, *, block_names=(), allow_unknown_checkpoint=False, stop=None):
|
||||
"""Hold all native database read handles during explicit lease release."""
|
||||
import stat
|
||||
import win32con, win32file
|
||||
from .owner_probe import query_owners
|
||||
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
|
||||
library = Path(library).resolve()
|
||||
assert_retained_exports_idle(library)
|
||||
if any(worker.poll() is None and (allow_unknown_checkpoint
|
||||
or not getattr(worker, 'cbb_library', None) or _key(worker.cbb_library) == _key(library))
|
||||
if any(worker.poll() is None and (not getattr(worker, 'cbb_library', None)
|
||||
or _key(worker.cbb_library) == _key(library))
|
||||
for worker in _retained_workers):
|
||||
raise LibraryBusy('原生管理工作进程尚未返回,不能解除协调阻止。')
|
||||
from .com_runtime import initialize_com, uninitialize_com
|
||||
@@ -492,12 +502,17 @@ def _prove_library_released(library, block_name=None, *, allow_unknown_checkpoin
|
||||
'iCDBProjectBackup.exe', 'ReuseBlockImporter.exe', 'CleanWGLib.exe',
|
||||
'cscript.exe', 'wscript.exe', 'python.exe', 'pythonw.exe',
|
||||
'CbbRefreshVerify.exe', *sorted(_OWNER_NAMES))
|
||||
scope_root = (Path(library).resolve().parent/'ReusableBlocksLP'/block_name/'Work').resolve() if block_name else None
|
||||
blocks = tuple(dict.fromkeys(block_names or ((block_name,) if block_name else ())))
|
||||
if any(not name or name in ('.', '..') or any(c in name for c in '\\/:*?"<>|') for name in blocks):
|
||||
raise ValueError('释放检查的工程名称无效')
|
||||
scope_roots = tuple(library.parent/'ReusableBlocksLP'/name/'Work' for name in blocks)
|
||||
shared_root = Path(library).resolve().parent/'SymbolLibs'
|
||||
if allow_unknown_checkpoint and scope_root is not None:
|
||||
if allow_unknown_checkpoint and scope_roots:
|
||||
raise LibraryBusy('未知检查点必须执行完整库释放证明。')
|
||||
observed = []
|
||||
def check_owners():
|
||||
if stop is not None and stop.is_set():
|
||||
raise InterruptedError('已停止释放检查')
|
||||
owners = []
|
||||
observed.clear()
|
||||
from .session_record import active_write_records
|
||||
@@ -506,12 +521,11 @@ def _prove_library_released(library, block_name=None, *, allow_unknown_checkpoin
|
||||
for item in query_owners(names):
|
||||
if item['pid'] == os.getpid():
|
||||
continue
|
||||
if not allow_unknown_checkpoint:
|
||||
roots = (scope_root, shared_root) if scope_root is not None else (Path(library).parent,)
|
||||
if not _owner_is_blocking(item, library, roots):
|
||||
if _owner_matches_scope(item, library, roots) is None:
|
||||
observed.append(item)
|
||||
continue
|
||||
roots = (*scope_roots, shared_root) if scope_roots else (library.parent,)
|
||||
if not _owner_is_blocking(item, library, roots):
|
||||
if _owner_matches_scope(item, library, roots) is None:
|
||||
observed.append(item)
|
||||
continue
|
||||
automation = item['name'].casefold() in ('python.exe', 'pythonw.exe', 'cbbrefreshverify.exe')
|
||||
command = item['command'].casefold()
|
||||
if not automation or not command or any(flag in command for flag in (
|
||||
@@ -521,44 +535,48 @@ def _prove_library_released(library, block_name=None, *, allow_unknown_checkpoin
|
||||
raise LibraryBusy(f'原生进程仍存在,不能解除协调阻止:{owners}')
|
||||
return owners
|
||||
check_owners()
|
||||
if scope_root is None:
|
||||
entries = scan_tree(Path(library).parent)
|
||||
else:
|
||||
entries = {Path(library): Path(library).lstat()}
|
||||
for root in (scope_root, shared_root):
|
||||
if root.exists():
|
||||
entries.update(scan_tree(root))
|
||||
addresses = [str(path) for path in entries if path.name.casefold() == 'saddress.adr'
|
||||
and (scope_root is None or path.is_relative_to(scope_root)
|
||||
or path.is_relative_to(shared_root))]
|
||||
if addresses:
|
||||
raise LibraryBusy(f'库中仍有数据库地址记录,不能自动解除:{addresses}')
|
||||
# scan_tree already rejects links; only native candidates need file opens.
|
||||
native = [path for path, metadata in entries.items() if stat.S_ISREG(metadata.st_mode) and (
|
||||
path == library
|
||||
or (path.name.casefold() in ('icdb.dat', 'layoutdb.lyt')
|
||||
and (scope_root is None or path.is_relative_to(scope_root)
|
||||
or path.is_relative_to(shared_root))))]
|
||||
if library not in native:
|
||||
raise LibraryBusy('目标库身份缺失,不能解除协调阻止。')
|
||||
from .file_probe import hold_release_files
|
||||
roots = (*scope_roots, shared_root) if scope_roots else None
|
||||
inspections = []
|
||||
with ExitStack() as stack:
|
||||
try:
|
||||
files = stack.enter_context(hold_release_files(library, roots, stop=stop))
|
||||
except OSError as error:
|
||||
blocked = LibraryBusy(str(error))
|
||||
blocked.winerror = getattr(error, 'winerror', None)
|
||||
raise blocked from error
|
||||
if files['addresses']:
|
||||
# Native inspection needs the database; reacquire proof handles
|
||||
# and compare the exact address/project binding before commit.
|
||||
stack.close()
|
||||
from .icdb_ownership import inspect_release_addresses
|
||||
inspections = inspect_release_addresses(files, stop=stop)
|
||||
try:
|
||||
current = stack.enter_context(hold_release_files(library, roots, stop=stop))
|
||||
except OSError as error:
|
||||
blocked = LibraryBusy(str(error))
|
||||
blocked.winerror = getattr(error, 'winerror', None)
|
||||
raise blocked from error
|
||||
if any(current[key] != files[key] for key in (
|
||||
'exclusive_files', 'addresses', 'signatures', 'inspection_targets')):
|
||||
raise LibraryBusy('原生检查期间资源范围或地址身份变化。')
|
||||
files = current
|
||||
export_proof = (prove_export_copies_released(library, allow_unknown_checkpoint=True)
|
||||
if allow_unknown_checkpoint else prove_export_copies_released(library))
|
||||
export_copies = stack.enter_context(export_proof)
|
||||
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)
|
||||
owners = check_owners()
|
||||
yield {'native_owners': owners, 'observed_owners': list(observed),
|
||||
'addresses': addresses, 'export_copies': export_copies,
|
||||
'unknown_checkpoint_recovery': allow_unknown_checkpoint,
|
||||
'exclusive_files': [str(path) for path in native]}
|
||||
yield {**{k: v for k, v in files.items() if k not in ('status', 'token')},
|
||||
'native_owners': owners, 'observed_owners': list(observed),
|
||||
'export_copies': export_copies, 'native_inspections': inspections,
|
||||
'data_recovery_required': any(item['repair_required'] for item in inspections) if inspections else None,
|
||||
'data_recovery_resources': [item['database'] for item in inspections if item['repair_required']],
|
||||
'unknown_checkpoint_recovery': allow_unknown_checkpoint}
|
||||
|
||||
finally:
|
||||
uninitialize_com(initialized)
|
||||
|
||||
|
||||
def release_retained_library(library, evidence_dir, *, block_name=None):
|
||||
def release_retained_library(library, evidence_dir, *, block_name=None, block_names=(), stop=None):
|
||||
"""Reconcile historical leases after fresh owner/address/access proof.
|
||||
|
||||
The upload sidecar is never deleted. This acknowledges process release,
|
||||
@@ -569,6 +587,9 @@ def release_retained_library(library, evidence_dir, *, block_name=None):
|
||||
from .session_record import (retained_session_snapshot, acknowledge_library_release,
|
||||
reconciled_retained_sessions)
|
||||
retained = retained_session_snapshot(library)
|
||||
requested_blocks = tuple(dict.fromkeys(block_names or ((block_name,) if block_name else ())))
|
||||
if any(not name or name in ('.', '..') or any(c in name for c in '\\/:*?"<>|') for name in requested_blocks):
|
||||
raise ValueError('释放检查的工程名称无效')
|
||||
evidence = Path(evidence_dir).resolve()
|
||||
if evidence.is_relative_to(library.parent) or library.parent.is_relative_to(evidence):
|
||||
raise ValueError('释放检查证据必须位于目标库之外。')
|
||||
@@ -577,10 +598,12 @@ def release_retained_library(library, evidence_dir, *, block_name=None):
|
||||
acquired = False
|
||||
external = None
|
||||
try:
|
||||
if stop is not None and stop.is_set():
|
||||
raise InterruptedError('已停止释放检查')
|
||||
acquired = win32event.WaitForSingleObject(mutex, 0) in (win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED)
|
||||
if not acquired:
|
||||
raise LibraryBusy('另一个 CBB 操作仍在运行。')
|
||||
with _guard:
|
||||
with _library_guard(lease.key):
|
||||
owner = _owners.get(lease.key)
|
||||
if owner and (not owner['retained'] or owner['depth']):
|
||||
raise LibraryBusy('本应用操作仍在使用库锁。')
|
||||
@@ -598,8 +621,10 @@ def release_retained_library(library, evidence_dir, *, block_name=None):
|
||||
before = {path: path.read_bytes() if path.exists() else None for path in checkpoints}
|
||||
unknown = any(data is not None and checkpoint_record(path) is None for path, data in before.items())
|
||||
records = [checkpoint_record(path) for path, data in before.items() if data is not None]
|
||||
scoped = (block_name if block_name and all(record and record.get('block_name') == block_name
|
||||
for record in records) and (owner is None or owner.get('block_name') == block_name) else None)
|
||||
scoped_blocks = (requested_blocks if requested_blocks and all(record
|
||||
and record.get('block_name') in requested_blocks for record in records)
|
||||
and (owner is None or owner.get('block_name') in requested_blocks) else ())
|
||||
scoped = scoped_blocks[0] if len(scoped_blocks) == 1 else None
|
||||
reconciled = [{'kind': 'checkpoint', 'path': str(path), 'recognized': metadata is not None,
|
||||
**{key: (metadata or {}).get(key) for key in ('block_name', 'lease_id', 'pid', 'status', 'time')}}
|
||||
for path, data in before.items() if data is not None
|
||||
@@ -610,27 +635,46 @@ def release_retained_library(library, evidence_dir, *, block_name=None):
|
||||
'status': 'OWNER_RELEASE_UNCONFIRMED'})
|
||||
foreign = sorted({item['block_name'] for item in reconciled
|
||||
if block_name and item.get('block_name') and item['block_name'] != block_name})
|
||||
proof_context = (_prove_library_released(library, allow_unknown_checkpoint=True) if unknown else
|
||||
_prove_library_released(library, block_name=scoped)
|
||||
if scoped else _prove_library_released(library))
|
||||
options = {'stop': stop} if stop is not None else {}
|
||||
if len(scoped_blocks) > 1:
|
||||
options['block_names'] = scoped_blocks
|
||||
proof_context = (_prove_library_released(library, allow_unknown_checkpoint=True, **options) if unknown else
|
||||
_prove_library_released(library, block_name=scoped, **options)
|
||||
if scoped else _prove_library_released(library, **options))
|
||||
with proof_context as proof:
|
||||
if stop is not None and stop.is_set():
|
||||
raise InterruptedError('已停止释放检查')
|
||||
with _guard:
|
||||
if _owners.get(lease.key) is not owner:
|
||||
raise LibraryBusy('释放检查期间租约身份变化,保留当前任务。')
|
||||
if unknown and proof.get('unknown_checkpoint_recovery') is not True:
|
||||
raise LibraryBusy('未知检查点缺少完整库释放证明,保留原文件。')
|
||||
if any((path.read_bytes() if path.exists() else None) != data for path, data in before.items()):
|
||||
raise LibraryBusy('释放检查期间协调检查点变化,保留原文件。')
|
||||
root = evidence/('release-' + uuid4().hex)
|
||||
root.mkdir(parents=True, exist_ok=False)
|
||||
reconciled_sessions = reconciled_retained_sessions(retained, block_name=scoped)
|
||||
matching_retained = ({path: value for path, value in retained.items()
|
||||
if value[1] in scoped_blocks} if scoped_blocks else retained)
|
||||
reconciled_sessions = reconciled_retained_sessions(matching_retained, block_name=scoped)
|
||||
reconciled_blocks = sorted({item['block_name'] for item in (*reconciled, *reconciled_sessions)
|
||||
if item.get('block_name')})
|
||||
record = {'library': str(library), 'status': 'RELEASE_CONFIRMED', **proof,
|
||||
'requested_block_name': block_name, 'proof_scope': 'BLOCK' if scoped else 'LIBRARY',
|
||||
'proof_block_name': scoped, 'reconciled_checkpoints': reconciled,
|
||||
'requested_block_name': block_name, 'requested_block_names': list(requested_blocks),
|
||||
'proof_scope': 'BLOCK' if scoped else 'BLOCKS' if scoped_blocks else 'LIBRARY',
|
||||
'proof_block_name': scoped, 'proof_block_names': list(scoped_blocks),
|
||||
'reconciled_checkpoints': reconciled,
|
||||
'reconciled_foreign_blockers': sorted(set(foreign) | {
|
||||
block for block in reconciled_blocks if block_name and block != block_name}),
|
||||
'reconciled_blocks': reconciled_blocks, 'reconciled_sessions': reconciled_sessions,
|
||||
'unknown_checkpoint_archived': unknown,
|
||||
'lease_state': 'RELEASED', 'blocked_resources': [],
|
||||
'data_recovery_required': proof.get('data_recovery_required', None),
|
||||
'data_recovery_confirmed': False, 'evidence_path': str(root/'release.json')}
|
||||
record['resource_scope'] = {**proof.get('resource_scope', {}),
|
||||
'scope_state': 'OBSERVED', 'library': str(library), 'block_name': scoped,
|
||||
'block_names': list(scoped_blocks),
|
||||
'lease_id': owner['lease_id'] if owner else None,
|
||||
'operation_ids': [item['operation_id'] for item in reconciled_sessions]}
|
||||
(root/'release.json').write_text(json.dumps(record, ensure_ascii=False, indent=2), encoding='utf-8')
|
||||
for index, checkpoint in enumerate(checkpoints):
|
||||
if checkpoint.exists():
|
||||
@@ -643,7 +687,7 @@ def release_retained_library(library, evidence_dir, *, block_name=None):
|
||||
if owner:
|
||||
owner['handle'].Close()
|
||||
del _owners[lease.key]
|
||||
acknowledge_library_release(record, retained, block_name=scoped)
|
||||
acknowledge_library_release(record, matching_retained, block_name=scoped)
|
||||
return record
|
||||
finally:
|
||||
if external is not None:
|
||||
|
||||
Reference in new issue
Block a user