fix: isolate ICDB checks and recover scoped native sessions
This commit is contained in:
1 parent
1acfbd6374
commit
1bd7589fef
82 files changed
+7770
-1583
No files matched your search
@@ -17,6 +17,16 @@ class LibraryBusy(OSError):
|
||||
pass
|
||||
|
||||
|
||||
def inspect_residual_sessions(library, *, block_names=()):
|
||||
from .residual_sessions import inspect_residual_sessions as inspect
|
||||
return inspect(library, block_names=block_names)
|
||||
|
||||
|
||||
def release_residual_sessions(plan, evidence_dir, *, stop=None, force=False):
|
||||
from .residual_sessions import release_residual_sessions as release
|
||||
return release(plan, evidence_dir, stop=stop, force=force)
|
||||
|
||||
|
||||
def _key(path):
|
||||
return str(Path(path).resolve()).casefold()
|
||||
|
||||
@@ -53,32 +63,48 @@ def checkpoint_record(path):
|
||||
|
||||
def has_blocker(library):
|
||||
path = blocker_path(library)
|
||||
if path.with_suffix('.pending').exists():
|
||||
return True
|
||||
if not path.exists():
|
||||
return False
|
||||
record = checkpoint_record(path)
|
||||
# Complete snapshots retain every file, including their source lease
|
||||
# checkpoint. Only a valid relocated snapshot record can be ignored.
|
||||
return record is None or _key(record['library']) == _key(library)
|
||||
for marker in (path, path.with_suffix('.pending')):
|
||||
if marker.exists():
|
||||
record = checkpoint_record(marker)
|
||||
if record is None or _key(record['library']) == _key(library):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _persist_blocker(library, status='OWNER_RELEASE_UNCONFIRMED', *, lease_id):
|
||||
def has_retained_library(library):
|
||||
"""Include leases retained without a JSON checkpoint, such as PCB checks."""
|
||||
path = Path(library).resolve()
|
||||
key = _key(path.with_name('.' + path.stem + '.cbb-upload.lock'))
|
||||
with _guard:
|
||||
owner = _owners.get(key)
|
||||
return bool(owner and owner['retained'])
|
||||
|
||||
|
||||
def _persist_blocker(library, status='OWNER_RELEASE_UNCONFIRMED', *, lease_id, block_name=None):
|
||||
import win32api, win32process
|
||||
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 {})
|
||||
if block_name is not None:
|
||||
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']
|
||||
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,
|
||||
'machine': socket.gethostname(),
|
||||
'supervisor_created': win32process.GetProcessTimes(win32api.GetCurrentProcess())['CreationTime'].isoformat(),
|
||||
'pid': os.getpid(), 'time': datetime.now(timezone.utc).isoformat()}, stream)
|
||||
stream.flush(); os.fsync(stream.fileno())
|
||||
pending.replace(path)
|
||||
|
||||
|
||||
class LibraryLock:
|
||||
def __init__(self, library, *, safe_to_release=None, checkpoint=True):
|
||||
def __init__(self, library, *, safe_to_release=None, checkpoint=True, block_name=None):
|
||||
library = Path(library).resolve()
|
||||
self.library = library
|
||||
self.path = library.with_name('.' + library.stem + '.cbb-upload.lock')
|
||||
@@ -86,6 +112,7 @@ class LibraryLock:
|
||||
self.entered = False
|
||||
self.safe_to_release = safe_to_release
|
||||
self.checkpoint = checkpoint
|
||||
self.block_name = block_name
|
||||
self.maintenance_guard = None
|
||||
self.maintenance_mutex = None
|
||||
|
||||
@@ -105,6 +132,13 @@ class LibraryLock:
|
||||
except Exception:
|
||||
released = False
|
||||
if released:
|
||||
if owner.get('checkpoint', True):
|
||||
marker = blocker_path(self.library)
|
||||
record = checkpoint_record(marker)
|
||||
if (record is None or record['lease_id'] != owner['lease_id']
|
||||
or 'export_analysis' in record or marker.with_suffix('.pending').exists()):
|
||||
raise LibraryBusy('协调检查点身份或导出会话尚未确认,保持库锁。')
|
||||
marker.unlink()
|
||||
owner['handle'].Close()
|
||||
del _owners[self.key]
|
||||
owner = None
|
||||
@@ -126,6 +160,8 @@ class LibraryLock:
|
||||
win32con.GENERIC_READ | win32con.GENERIC_WRITE, 0, None,
|
||||
win32con.OPEN_ALWAYS, win32con.FILE_ATTRIBUTE_NORMAL, None)
|
||||
except Exception as error:
|
||||
if getattr(error, 'winerror', None) not in (32, 33):
|
||||
raise
|
||||
raise LibraryBusy(f'中心库已锁定或无法创建协调锁:{self.path}: {error}') from error
|
||||
try:
|
||||
data = (f'machine={socket.gethostname()}; pid={os.getpid()}; '
|
||||
@@ -140,14 +176,16 @@ class LibraryLock:
|
||||
import pywintypes
|
||||
win32file.SetFileTime(handle, None, None, pywintypes.Time(datetime.now()))
|
||||
if self.checkpoint:
|
||||
_persist_blocker(self.library, 'OPERATION_IN_PROGRESS', lease_id=lease_id)
|
||||
_persist_blocker(self.library, 'OPERATION_IN_PROGRESS', lease_id=lease_id,
|
||||
block_name=self.block_name)
|
||||
except Exception:
|
||||
handle.Close()
|
||||
raise
|
||||
_owners[self.key] = {'thread': threading.get_ident(), 'depth': 1,
|
||||
'handle': handle, 'retained': False, 'lease_id': lease_id,
|
||||
'checkpoint': self.checkpoint,
|
||||
'release_probe': self.safe_to_release if not self.checkpoint else None}
|
||||
'block_name': self.block_name,
|
||||
'release_probe': self.safe_to_release}
|
||||
self.entered = True
|
||||
return self
|
||||
|
||||
@@ -241,6 +279,67 @@ def _supervisor_alive(pid):
|
||||
handle.Close()
|
||||
|
||||
|
||||
def _recorded_supervisor_alive(record):
|
||||
"""None means legacy/unknown identity; the native/file guard still applies."""
|
||||
if record.get('machine') != socket.gethostname() or not record.get('supervisor_created'):
|
||||
return None
|
||||
import pywintypes, win32api, win32con, win32process
|
||||
try:
|
||||
handle = win32api.OpenProcess(win32con.SYNCHRONIZE | 0x1000, False, record['pid'])
|
||||
except pywintypes.error as error:
|
||||
return False if error.winerror == 87 else None
|
||||
try:
|
||||
return (win32process.GetProcessTimes(handle)['CreationTime'].isoformat() == record['supervisor_created']
|
||||
and _supervisor_alive(record['pid']))
|
||||
finally:
|
||||
handle.Close()
|
||||
|
||||
|
||||
def _owner_matches_scope(item, library, roots):
|
||||
"""False requires an explicit other project; a missing path stays unknown."""
|
||||
import ntpath
|
||||
from .failed_session import _command_args
|
||||
command = str(item.get('command') or '')
|
||||
if not command:
|
||||
return None
|
||||
try:
|
||||
args = _command_args(command)
|
||||
except (OSError, ValueError):
|
||||
return None
|
||||
candidates = []
|
||||
worker_flags = {'--verify-worker', '--repair-worker', '--management-worker', '--native-backup-worker'}
|
||||
for index, arg in enumerate(args[1:], 1):
|
||||
if arg.casefold() in worker_flags and index + 1 < len(args):
|
||||
try:
|
||||
request = Path(args[index + 1])
|
||||
if request.stat().st_size > 1024 * 1024:
|
||||
return None
|
||||
record = json.loads(request.read_text(encoding='utf-8'))
|
||||
for key in ('library', 'lmc_file', 'project', 'database'):
|
||||
if isinstance(record.get(key), str):
|
||||
candidates.append(record[key])
|
||||
except (OSError, ValueError, TypeError, AttributeError):
|
||||
return None
|
||||
value = arg.split('=', 1)[1] if arg.startswith('-') and '=' in arg else arg
|
||||
if (ntpath.isabs(value) and (ntpath.splitext(value)[1].casefold() in ('.prj', '.pcb', '.lmc')
|
||||
or arg.casefold().startswith(('-project=', '-icdb='))
|
||||
or args[index - 1].casefold() in ('-icdb', '-project', '-p'))):
|
||||
candidates.append(value)
|
||||
normalized_roots = [ntpath.normcase(ntpath.normpath(str(root))) for root in roots]
|
||||
expected_library = ntpath.normcase(ntpath.normpath(str(library)))
|
||||
for candidate in candidates:
|
||||
path = ntpath.normcase(ntpath.normpath(candidate))
|
||||
if path == expected_library:
|
||||
return True
|
||||
for root in normalized_roots:
|
||||
try:
|
||||
if ntpath.commonpath((path, root)) == root:
|
||||
return True
|
||||
except ValueError:
|
||||
pass
|
||||
return False if candidates else None
|
||||
|
||||
|
||||
def _enter_maintenance(lease):
|
||||
"""Transfer only a valid known lease, after project admission under lock."""
|
||||
import win32con, win32event, win32file
|
||||
@@ -266,13 +365,16 @@ def _enter_maintenance(lease):
|
||||
raise LibraryBusy('本进程库锁仍在使用或检查点身份不符')
|
||||
handle = existing['handle']
|
||||
else:
|
||||
if record is not None and record['pid'] != os.getpid() and _supervisor_alive(record['pid']):
|
||||
if record is not None and record['pid'] != os.getpid() and _recorded_supervisor_alive(record) is True:
|
||||
raise LibraryBusy('原监督进程仍存在,不能接续其库锁')
|
||||
handle = win32file.CreateFile(str(lease.path), win32con.GENERIC_READ | win32con.GENERIC_WRITE,
|
||||
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.
|
||||
from .native_export_guard import prove_export_copies_released
|
||||
if record is not None and _recorded_supervisor_alive(record) is None:
|
||||
from .maintenance_entry import assert_native_idle
|
||||
assert_native_idle()
|
||||
with prove_export_copies_released(lease.library), lease.maintenance_guard() as proof:
|
||||
if (marker.read_bytes() if marker.exists() else None) != old:
|
||||
raise LibraryBusy('维护检查期间检查点变化')
|
||||
@@ -285,7 +387,8 @@ def _enter_maintenance(lease):
|
||||
lease_id = uuid4().hex
|
||||
_persist_blocker(lease.library, 'OPERATION_IN_PROGRESS', lease_id=lease_id)
|
||||
_owners[lease.key] = {'thread': threading.get_ident(), 'depth': 1, 'handle': handle,
|
||||
'retained': False, 'lease_id': lease_id}
|
||||
'retained': False, 'lease_id': lease_id, 'checkpoint': True,
|
||||
'release_probe': lease.safe_to_release, 'block_name': None}
|
||||
lease.maintenance_proof = proof
|
||||
lease.entered = True
|
||||
lease.maintenance_mutex = mutex
|
||||
@@ -315,16 +418,20 @@ def owned_snapshot(path):
|
||||
|
||||
|
||||
@contextmanager
|
||||
def _prove_library_released(library, block_name=None):
|
||||
def _prove_library_released(library, block_name=None, *, allow_unknown_checkpoint=False):
|
||||
"""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
|
||||
assert_retained_exports_idle()
|
||||
if any(worker.poll() is None for worker in _retained_workers):
|
||||
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))
|
||||
for worker in _retained_workers):
|
||||
raise LibraryBusy('原生管理工作进程尚未返回,不能解除协调阻止。')
|
||||
from .com_runtime import initialize_com, uninitialize_com
|
||||
initialized = initialize_com()
|
||||
@@ -334,43 +441,58 @@ def _prove_library_released(library, block_name=None):
|
||||
'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
|
||||
shared_root = Path(library).resolve().parent/'SymbolLibs'
|
||||
if allow_unknown_checkpoint and scope_root is not None:
|
||||
raise LibraryBusy('未知检查点必须执行完整库释放证明。')
|
||||
def check_owners():
|
||||
owners = []
|
||||
for item in query_owners(names):
|
||||
if item['pid'] == os.getpid():
|
||||
continue
|
||||
if scope_root is not None and item.get('command'):
|
||||
command = str(item['command']).casefold().replace('/', '\\')
|
||||
if str(scope_root).casefold().replace('/', '\\') not in command:
|
||||
if not allow_unknown_checkpoint:
|
||||
roots = (scope_root, shared_root) if scope_root is not None else (Path(library).parent,)
|
||||
if _owner_matches_scope(item, library, roots) is False:
|
||||
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 (
|
||||
'--verify-worker', '--repair-worker', '--management-worker')):
|
||||
'--verify-worker', '--repair-worker', '--management-worker', '--native-backup-worker')):
|
||||
owners.append(item)
|
||||
if owners:
|
||||
raise LibraryBusy(f'原生进程仍存在,不能解除协调阻止:{owners}')
|
||||
return owners
|
||||
check_owners()
|
||||
entries = scan_tree(Path(library).parent)
|
||||
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.resolve().is_relative_to(scope_root))]
|
||||
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}')
|
||||
native = [path for path in entries if path.is_file() and (
|
||||
path.suffix.casefold() == '.lmc'
|
||||
# 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.resolve().is_relative_to(scope_root))))]
|
||||
if Path(library).resolve() not in native:
|
||||
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('目标库身份缺失,不能解除协调阻止。')
|
||||
with ExitStack() as stack:
|
||||
export_copies = stack.enter_context(prove_export_copies_released(library))
|
||||
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, 'addresses': addresses, 'export_copies': export_copies,
|
||||
'unknown_checkpoint_recovery': allow_unknown_checkpoint,
|
||||
'exclusive_files': [str(path) for path in native]}
|
||||
finally:
|
||||
uninitialize_com(initialized)
|
||||
@@ -405,17 +527,28 @@ def release_retained_library(library, evidence_dir, *, block_name=None):
|
||||
win32con.GENERIC_READ | win32con.GENERIC_WRITE, 0, None,
|
||||
win32con.OPEN_ALWAYS, win32con.FILE_ATTRIBUTE_NORMAL, None)
|
||||
except Exception as error:
|
||||
if getattr(error, 'winerror', None) not in (32, 33):
|
||||
raise
|
||||
raise LibraryBusy('其他进程仍持有库锁,不能解除。') from error
|
||||
proof_context = (_prove_library_released(library, block_name=block_name)
|
||||
if block_name else _prove_library_released(library))
|
||||
marker = blocker_path(library)
|
||||
checkpoints = (marker, marker.with_suffix('.pending'))
|
||||
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)
|
||||
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))
|
||||
with proof_context as proof:
|
||||
marker = blocker_path(library)
|
||||
checkpoints = (marker, marker.with_suffix('.pending'))
|
||||
if any(path.exists() and checkpoint_record(path) is None for path in checkpoints):
|
||||
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)
|
||||
record = {'library': str(library), 'status': 'RELEASE_CONFIRMED', **proof,
|
||||
'unknown_checkpoint_archived': unknown,
|
||||
'data_recovery_confirmed': False, 'evidence_path': str(root/'release.json')}
|
||||
(root/'release.json').write_text(json.dumps(record, ensure_ascii=False, indent=2), encoding='utf-8')
|
||||
for index, checkpoint in enumerate(checkpoints):
|
||||
|
||||
Reference in new issue
Block a user