fix: fence final worker admission against UI shutdown
This commit is contained in:
1 parent
dbc685b9a5
commit
eabf61c73b
13 files changed
+356
-46
No files matched your search
@@ -100,9 +100,12 @@ def main(argv: Sequence[str] | None = None) -> int:
|
||||
from .native_backup import run_native_backup_worker
|
||||
return run_native_backup_worker(args.native_backup_worker)
|
||||
if args.management_worker:
|
||||
from .native_management import management_worker_main
|
||||
import json
|
||||
from .native_management import catalog_worker_main, management_worker_main
|
||||
from .desktop_worker import run_native_worker
|
||||
return run_native_worker(management_worker_main, args.management_worker)
|
||||
job = json.loads(args.management_worker.read_text(encoding='utf-8'))
|
||||
action = catalog_worker_main if job.get('worker_role') == 'catalog_readonly' else management_worker_main
|
||||
return run_native_worker(action, args.management_worker)
|
||||
if args.repair_worker:
|
||||
from .native_repair_ui import repair_worker_main
|
||||
from .desktop_worker import run_native_worker
|
||||
|
||||
@@ -197,14 +197,36 @@ def run_native_worker(action, request_path):
|
||||
raise RuntimeError('WORKER_CANCELLED: 未取得启动许可。')
|
||||
threading.Event().wait(.05)
|
||||
lease_handle = None
|
||||
record = None
|
||||
if job.get('session_record_path'):
|
||||
from .session_record import read_session_record
|
||||
from .session_record import read_session_record, process_identity, IDENTITY_KEYS
|
||||
path = Path(job['session_record_path'])
|
||||
record = read_session_record(path, evidence_root=path.parent)
|
||||
identity = process_identity(os.getpid())
|
||||
if (record['operation_id'] != job['operation_id']
|
||||
or not any(p['pid'] == os.getpid() for p in record.get('processes', ()) )):
|
||||
or any(record.get(key) != job.get(key) for key in (
|
||||
'operation', 'library', 'block', 'desktop', 'worker_role', 'start_gate_protocol', 'start_gate'))
|
||||
or not any(p.get('role') == 'worker' and all(p.get(k) == identity[k] for k in IDENTITY_KEYS)
|
||||
for p in record.get('processes', ()))):
|
||||
raise RuntimeError('WORKER_ADMISSION_IDENTITY_CHANGED')
|
||||
lease_handle = record.get('worker_lease_handle')
|
||||
if job.get('start_gate_protocol') == 'event-v1':
|
||||
import win32api
|
||||
handle = record.get('worker_start_handle') if record else None
|
||||
if not handle:
|
||||
raise RuntimeError('WORKER_ADMISSION_UNCONFIRMED: 缺少启动事件。')
|
||||
try:
|
||||
deadline = time.monotonic()+30
|
||||
while win32event.WaitForSingleObject(int(handle), 50) != win32con.WAIT_OBJECT_0:
|
||||
if (job.get('cancel_signal') and Path(job['cancel_signal']).exists()
|
||||
or time.monotonic() >= deadline):
|
||||
raise RuntimeError('WORKER_CANCELLED: 启动事件未提交。')
|
||||
finally:
|
||||
win32api.CloseHandle(int(handle))
|
||||
if job.get('worker_role') == 'catalog_readonly':
|
||||
from .native_management import catalog_worker_main
|
||||
if action is not catalog_worker_main or job.get('operation') != 'catalog':
|
||||
raise RuntimeError('WORKER_READONLY_ROLE_MISMATCH')
|
||||
inspection = (action.__module__ == 'cbb_refresh_verify.native_repair_ui'
|
||||
and action.__name__ == 'repair_worker_main' and job.get('inspection_only') is True)
|
||||
with worker_native_channel(lease_handle=lease_handle, inspection_only=inspection):
|
||||
|
||||
@@ -90,7 +90,7 @@ class NativeBackupSession:
|
||||
def launch_native_backup(request, *, mode='versions', target_database=None):
|
||||
from .library_lock import recheck_previous_release
|
||||
from .session_record import register_worker_session
|
||||
from .operation_queue import check_active, native_channel, task_stop
|
||||
from .operation_queue import check_active, native_channel, task_stop, commit_worker_start
|
||||
project, database = native_backup_target(request, mode=mode, target_database=target_database)
|
||||
native_backup_executable(request.mentor_bin)
|
||||
root = Path(request.evidence_dir).resolve()/('native-backup-'+uuid4().hex[:12])
|
||||
@@ -108,6 +108,7 @@ def launch_native_backup(request, *, mode='versions', target_database=None):
|
||||
'mentor_bin': request.mentor_bin, 'automatic_repair': False,
|
||||
'operation': 'native_backup', 'operation_id': root.name,
|
||||
'session_record_path': str(root/'session.json'), 'start_gate': str(root/'start-worker.signal'),
|
||||
'start_gate_protocol': 'event-v1',
|
||||
'cancel_signal': str(root/'cancel-worker.signal'), 'supervisor_pid': os.getpid(), 'desktop': None}
|
||||
job.write_text(json.dumps(record, ensure_ascii=False), 'utf-8')
|
||||
command = ([sys.executable] if getattr(sys, 'frozen', False) else
|
||||
@@ -118,7 +119,7 @@ def launch_native_backup(request, *, mode='versions', target_database=None):
|
||||
register_worker_session(process, record)
|
||||
with native_channel():
|
||||
check_active()
|
||||
Path(record['start_gate']).touch()
|
||||
commit_worker_start(process, record)
|
||||
except BaseException:
|
||||
Path(record['cancel_signal']).touch() # The unadmitted child exits without native launch.
|
||||
raise
|
||||
|
||||
@@ -53,9 +53,10 @@ def removal_output_ok(code, output, name, partition):
|
||||
+ r"' from partition '" + re.escape(partition) + r"'\.", output) is not None)
|
||||
|
||||
|
||||
def catalog_dialog_action(title, text):
|
||||
def catalog_dialog_action(title, text, *, read_only=False):
|
||||
value = (title + '\n' + text).casefold()
|
||||
if ('this central library must be updated' in value or 'select flow type' in value):
|
||||
if ('this central library must be updated' in value or 'select flow type' in value
|
||||
or read_only and ('save' in value or 'upgrade' in value)):
|
||||
return 'cancel'
|
||||
return 'observe'
|
||||
|
||||
@@ -222,6 +223,7 @@ class NativeManagementAdapter:
|
||||
from .session_record import process_identity
|
||||
job = {**job, 'cancel_signal': str(evidence/'cancel-management.signal'),
|
||||
'start_gate': str(evidence/'start-management.signal'),
|
||||
'start_gate_protocol': 'event-v1',
|
||||
'session_record_path': str(evidence/'session.json'), 'operation_id': uuid4().hex,
|
||||
'supervisor_pid': os.getpid(), 'supervisor_identity': process_identity(os.getpid()),
|
||||
'block': job.get('name')}
|
||||
@@ -242,7 +244,8 @@ class NativeManagementAdapter:
|
||||
worker.bind_cancellation(job['cancel_signal'])
|
||||
if hasattr(worker, 'bind_session'):
|
||||
worker.bind_session(job)
|
||||
Path(job['start_gate']).touch()
|
||||
from .operation_queue import commit_worker_start
|
||||
commit_worker_start(worker, job)
|
||||
while worker.poll() is None and time.monotonic() < deadline:
|
||||
if self.stop is not None and self.stop.is_set():
|
||||
Path(job['cancel_signal']).touch()
|
||||
@@ -275,7 +278,8 @@ class NativeManagementAdapter:
|
||||
worker.close()
|
||||
|
||||
def catalog(self, library, evidence):
|
||||
result = self._worker({'operation': 'catalog', 'library': str(absolute_preserving_drive(library))}, evidence)
|
||||
result = self._worker({'operation': 'catalog', 'worker_role': 'catalog_readonly',
|
||||
'library': str(absolute_preserving_drive(library))}, evidence)
|
||||
if not result.get('success') or not result.get('safe_to_continue'):
|
||||
raise NativeOperationError(result.get('detail', '原生目录复读未确认,禁止文件夹回退。'),
|
||||
safe_to_continue=result.get('safe_to_continue') is True)
|
||||
@@ -1069,6 +1073,8 @@ def _catalog_native(job, root):
|
||||
|
||||
|
||||
def _catalog_com(job, root):
|
||||
if job.get('worker_role') == 'catalog_readonly' and job.get('operation') != 'catalog':
|
||||
raise RuntimeError('WORKER_READONLY_ROLE_MISMATCH')
|
||||
import pythoncom, win32com.client, win32con, win32gui, win32process
|
||||
from .mentor_adapter import _process_details
|
||||
try:
|
||||
@@ -1102,7 +1108,7 @@ def _catalog_com(job, root):
|
||||
win32gui.EnumChildWindows(hwnd, lambda child, _: children.append(child), None)
|
||||
title = win32gui.GetWindowText(hwnd)
|
||||
text = '\n'.join(win32gui.GetWindowText(child) for child in children)
|
||||
if catalog_dialog_action(title, text) == 'cancel':
|
||||
if catalog_dialog_action(title, text, read_only=job.get('worker_role') == 'catalog_readonly') == 'cancel':
|
||||
if hwnd not in observed:
|
||||
observed.append(hwnd)
|
||||
refused.append({'title': title, 'text': text})
|
||||
@@ -1236,11 +1242,23 @@ def _catalog_com(job, root):
|
||||
return result
|
||||
|
||||
|
||||
def management_worker_main(request_path):
|
||||
def catalog_worker_main(request_path):
|
||||
"""A catalog-only entry: never allow this read role to select a write branch."""
|
||||
job = json.loads(Path(request_path).read_text(encoding='utf-8'))
|
||||
if job.get('operation') != 'catalog' or job.get('worker_role') != 'catalog_readonly':
|
||||
raise RuntimeError('WORKER_READONLY_ROLE_MISMATCH')
|
||||
return management_worker_main(request_path, catalog_readonly=True)
|
||||
|
||||
|
||||
def management_worker_main(request_path, *, catalog_readonly=False):
|
||||
"""Internal worker. Desktop identity and capability gates are rechecked here."""
|
||||
request_path = Path(request_path)
|
||||
root = request_path.parent
|
||||
job = json.loads(request_path.read_text(encoding='utf-8'))
|
||||
if job.get('worker_role') == 'catalog_readonly' and not catalog_readonly:
|
||||
raise RuntimeError('WORKER_READONLY_ROLE_MISMATCH')
|
||||
if catalog_readonly and (job.get('operation') != 'catalog' or job.get('worker_role') != 'catalog_readonly'):
|
||||
raise RuntimeError('WORKER_READONLY_ROLE_MISMATCH')
|
||||
result = {'success': False, 'safe_to_continue': True}
|
||||
try:
|
||||
_, desktop = _current_desktop()
|
||||
|
||||
@@ -275,6 +275,7 @@ def run_native_repair(target, root, *, mentor_bin='', timeout_seconds=300, progr
|
||||
'operation': 'inspect' if inspection_only else 'repair',
|
||||
'block': (maintenance_context or {}).get('block'),
|
||||
'session_record_path': str(root/'session.json'), 'start_gate': str(root/'start-repair.signal')}
|
||||
job['start_gate_protocol'] = 'event-v1'
|
||||
job_path.write_text(json.dumps(job, ensure_ascii=False), encoding='utf-8')
|
||||
command = ([sys.executable] if getattr(sys, 'frozen', False) else
|
||||
[sys.executable, '-m', 'cbb_refresh_verify']) + ['--repair-worker', str(job_path)]
|
||||
@@ -286,9 +287,7 @@ def _supervise_repair(command, desktop, cancel, root, timeout_seconds, progress,
|
||||
from .desktop_worker import DesktopWorker
|
||||
worker = DesktopWorker(command, desktop)
|
||||
worker.bind_cancellation(cancel)
|
||||
if hasattr(worker, 'bind_session'):
|
||||
worker.bind_session(job)
|
||||
from .operation_queue import check_active, native_channel
|
||||
from .operation_queue import check_active, native_channel, commit_worker_start
|
||||
native = native_channel(inspection_only=job.get('inspection_only') is True)
|
||||
entered = False
|
||||
# Worker admission includes filesystem/ownership checks before the native
|
||||
@@ -297,10 +296,12 @@ def _supervise_repair(command, desktop, cancel, root, timeout_seconds, progress,
|
||||
event_count = 0
|
||||
cancelled = False
|
||||
try:
|
||||
if hasattr(worker, 'bind_session'):
|
||||
worker.bind_session(job)
|
||||
check_active()
|
||||
native.__enter__()
|
||||
entered = True
|
||||
Path(job['start_gate']).touch()
|
||||
commit_worker_start(worker, job)
|
||||
while worker.poll() is None and time.monotonic()<deadline:
|
||||
if not cancelled and stop is not None and stop.is_set():
|
||||
worker.request_stop()
|
||||
@@ -331,6 +332,9 @@ def _supervise_repair(command, desktop, cancel, root, timeout_seconds, progress,
|
||||
if worker.returncode != 0 and result.get('status') in ('REPAIRED', 'NOT_IN_USE', 'IN_USE'):
|
||||
result['status'] = 'UNCONFIRMED'
|
||||
return {**result, 'evidence_path': str(root)}
|
||||
except BaseException:
|
||||
worker.request_stop()
|
||||
raise
|
||||
finally:
|
||||
if entered:
|
||||
native.__exit__(None, None, None)
|
||||
|
||||
@@ -27,7 +27,8 @@ class _StopSignal:
|
||||
self._event = Event()
|
||||
|
||||
def set(self):
|
||||
self._event.set()
|
||||
with _tasks_guard:
|
||||
self._event.set()
|
||||
|
||||
def is_set(self):
|
||||
return self._event.is_set()
|
||||
@@ -120,10 +121,35 @@ def check_worker_admission(job):
|
||||
check_active()
|
||||
call = getattr(_local, 'call', None)
|
||||
if (call is not None and call.readonly_depth and job.get('inspection_only') is not True
|
||||
and job.get('operation') != 'catalog'):
|
||||
and not (job.get('operation') == 'catalog' and job.get('worker_role') == 'catalog_readonly')):
|
||||
raise RuntimeError('NATIVE_ROLE_REQUIRED: 只读观察不能启动原生写入进程。')
|
||||
|
||||
|
||||
def commit_worker_start(worker, job):
|
||||
"""Prepare evidence outside the shutdown fence; only SetEvent grants admission."""
|
||||
from pathlib import Path
|
||||
import win32event
|
||||
try:
|
||||
check_worker_admission(job)
|
||||
event = getattr(worker, '_start_event', None)
|
||||
context = current_context()
|
||||
if context is not None and context.native_policy == 'external' and event is None:
|
||||
raise RuntimeError('WORKER_ADMISSION_UNCONFIRMED: 缺少已登记的启动事件。')
|
||||
if event is not None and worker._start_binding != (
|
||||
str(job['session_record_path']), job['operation_id'], job['start_gate']):
|
||||
raise RuntimeError('WORKER_ADMISSION_IDENTITY_CHANGED')
|
||||
Path(job['start_gate']).touch()
|
||||
with _tasks_guard:
|
||||
check_worker_admission(job)
|
||||
if event is not None:
|
||||
win32event.SetEvent(event)
|
||||
except BaseException:
|
||||
# A stalled evidence volume cannot delay shutdown or grant admission.
|
||||
if job.get('cancel_signal'):
|
||||
Path(job['cancel_signal']).touch()
|
||||
raise
|
||||
|
||||
|
||||
def hold_native_handoff(process, session_record_path):
|
||||
"""Yield parent admission to controls; the gated worker retains write exclusion.
|
||||
|
||||
@@ -233,19 +259,19 @@ class BatchTaskContext:
|
||||
def shutdown(self):
|
||||
"""Yield UI supervision, never a native worker's write/lease ownership.
|
||||
|
||||
External-role code only dispatches through register_worker_session. An
|
||||
empty binding list means pre-dispatch preparation; its late gate is
|
||||
cancelled by that hook. Legacy in-process transactions cannot opt in.
|
||||
External workers commit their kernel start event under this same fence.
|
||||
Registration and all filesystem preparation remain outside the fence.
|
||||
Legacy in-process transactions cannot opt in.
|
||||
"""
|
||||
self._closed.set()
|
||||
self.cancel()
|
||||
with _tasks_guard:
|
||||
self._closed.set()
|
||||
self.cancel()
|
||||
calls = [c for c in _calls.values() if c.context is self and not c.done.is_set()]
|
||||
for call in calls:
|
||||
readonly = call.native_depth and call.readonly_depth == call.native_depth
|
||||
external = (self.native_policy == 'external' and
|
||||
call.supervised_depth == call.native_depth and
|
||||
all(s.get('worker_protection') in ('duplicated_lease', 'worker_owned_lease', 'inspection_only')
|
||||
all(s.get('worker_protection') in ('duplicated_lease', 'worker_owned_lease', 'inspection_only', 'catalog_readonly')
|
||||
for s in call.worker_sessions))
|
||||
if not call.native_depth or readonly or external:
|
||||
call.shutdown_handoff = call.abandoned = True
|
||||
|
||||
@@ -133,17 +133,33 @@ def register_worker_session(worker, job):
|
||||
context = current_context()
|
||||
protection = ('duplicated_lease' if job.get('worker_lease_handle') else
|
||||
'worker_owned_lease' if job.get('operation') == 'native_backup' else
|
||||
'inspection_only' if job.get('inspection_only') is True else None)
|
||||
'inspection_only' if job.get('inspection_only') is True else
|
||||
'catalog_readonly' if job.get('worker_role') == 'catalog_readonly'
|
||||
and job.get('operation') == 'catalog' else None)
|
||||
if context is not None and context.native_policy == 'external':
|
||||
if protection is None or worker.pid == os.getpid():
|
||||
raise RuntimeError('WORKER_OWNERSHIP_REQUIRED: 原生写入未登记独立进程和租约。')
|
||||
from .icdb_ownership import session_resource_scope
|
||||
record = ({k: job.get(k) for k in (
|
||||
'operation_id', 'operation', 'library', 'block', 'desktop', 'cancel_signal', 'worker_lease_handle')}
|
||||
'operation_id', 'operation', 'library', 'block', 'desktop', 'cancel_signal', 'worker_lease_handle',
|
||||
'worker_role', 'start_gate_protocol', 'start_gate')}
|
||||
| {'processes': [{'role': 'worker', **process_identity(worker.pid)}],
|
||||
'lease_state': 'ACTIVE', 'resource_scope': session_resource_scope(job),
|
||||
'worker_protection': protection, 'task_operation_id': context.operation_id if context else None,
|
||||
'blocked_resources': [], 'data_recovery_required': None})
|
||||
if job.get('start_gate_protocol') == 'event-v1':
|
||||
import win32api, win32con, win32event
|
||||
event = win32event.CreateEvent(None, True, False, None)
|
||||
process = getattr(worker, 'handle', None) or getattr(worker, '_handle', None)
|
||||
if process is None:
|
||||
raise RuntimeError('WORKER_ADMISSION_UNCONFIRMED: 缺少工作进程句柄。')
|
||||
# Use the launch handle, never a reopened PID. The child's event survives
|
||||
# supervisor exit even before Python startup or journal reads finish.
|
||||
remote = win32api.DuplicateHandle(win32api.GetCurrentProcess(), event,
|
||||
process, 0, False, win32con.DUPLICATE_SAME_ACCESS)
|
||||
record['worker_start_handle'] = remote.Detach()
|
||||
worker._start_event = event
|
||||
worker._start_binding = (str(path), job['operation_id'], job['start_gate'])
|
||||
write_session_record(path, record)
|
||||
bind_supervised_worker(path, record)
|
||||
worker.session_record_path = path
|
||||
|
||||
@@ -933,7 +933,7 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
'cancel_signal': str(root/'cancel-worker.signal'),
|
||||
'start_gate': str(root/'start-worker.signal')}
|
||||
job.update(operation_id=root.name, operation='verify', library=str(request.lmc_file),
|
||||
block=request.block_name, session_record_path=str(root/'session.json'))
|
||||
block=request.block_name, session_record_path=str(root/'session.json'), start_gate_protocol='event-v1')
|
||||
from .session_record import process_identity
|
||||
job['supervisor_identity'] = process_identity(os.getpid())
|
||||
consent = None
|
||||
@@ -1023,7 +1023,8 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
except RuntimeError as error:
|
||||
return finish(VerifyResult('BLOCKED', stderr=str(error), safe_to_continue=False,
|
||||
error_category='NATIVE_CHANNEL_BUSY'))
|
||||
Path(job['start_gate']).touch()
|
||||
from .operation_queue import commit_worker_start
|
||||
commit_worker_start(process, job)
|
||||
while process.poll() is None:
|
||||
if stop is not None and stop.is_set():
|
||||
save_markers = timing._save_markers
|
||||
|
||||
Reference in new issue
Block a user