fix: bind manual recovery entries and current native diagnostics
This commit is contained in:
1 parent
8374cabe5c
commit
601dd7b6b2
14 files changed
+694
-69
No files matched your search
@@ -97,9 +97,8 @@ def main(argv: Sequence[str] | None = None) -> int:
|
||||
from .owner_probe import owner_probe_main
|
||||
return owner_probe_main(args.owner_probe)
|
||||
if args.native_backup_worker:
|
||||
from .native_backup import native_backup_worker_main
|
||||
from .desktop_worker import run_native_worker
|
||||
return run_native_worker(native_backup_worker_main, args.native_backup_worker)
|
||||
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
|
||||
from .desktop_worker import run_native_worker
|
||||
|
||||
@@ -8,7 +8,7 @@ import re
|
||||
ERROR_CODE = 'ICDB_REPAIR_REQUIRED'
|
||||
LOG_LIMIT = 128 * 1024
|
||||
RECOVERY_ACTION = (
|
||||
'停止批次并确认原服务器及其他客户端已正常关闭;保留完整一致副本后,'
|
||||
'停止受影响工程的写入并确认原服务器及其他客户端已正常关闭;保留完整一致副本后,'
|
||||
"使用同版本 iCDB Project Backup 的 Repair project 检查并修复正确目标。"
|
||||
'共享符号库问题需核对中心库,不能只修复单个 CBB 的 Work 工程。'
|
||||
'不要删除 sAddress.adr/锁文件;修复后重新打开、校验并确认权威 READY。'
|
||||
@@ -16,6 +16,9 @@ RECOVERY_ACTION = (
|
||||
_SESSION_LOSS = re.compile(
|
||||
r'\bthe\s+last\s+server\s+session\s+on\s+different\s+server\s+machine\s+'
|
||||
r'lost\s+the\s+connection\s+to\s+the\s+database\b', re.IGNORECASE)
|
||||
_INCONSISTENT = re.compile(
|
||||
r"Project database \[([^\]\r\n]+)\] is inconsistent\. It has been manually copied while the iCDB Server was running\.\s*"
|
||||
r"Please use iCDB Project Backup 'Repair project' functionality to fix this issue\.", re.I)
|
||||
|
||||
_ICDB_MESSAGE = re.compile(r'(?<![A-Za-z0-9_])icdb(?![A-Za-z0-9_.\\/])', re.I)
|
||||
_FAILURE_MESSAGE = re.compile(
|
||||
@@ -78,11 +81,25 @@ def parse_session_loss(text):
|
||||
return record
|
||||
|
||||
|
||||
def parse_recovery_request(text):
|
||||
record = parse_session_loss(text)
|
||||
if record is not None:
|
||||
return record
|
||||
match = _INCONSISTENT.search(str(text or ''))
|
||||
if match is not None:
|
||||
shared = 'symbollibs' in ntpath.normpath(match[1]).casefold().split('\\')
|
||||
return {'error_code': ERROR_CODE, 'kind': 'database_inconsistent',
|
||||
'native_message': match[0], 'database_path': match[1], 'scope': 'central_library' if shared else 'project',
|
||||
'machine': '', 'session': ''}
|
||||
return None
|
||||
|
||||
|
||||
def recovery_detail(record):
|
||||
target = ('中心库共享符号数据库' if record['scope'] == 'central_library' else
|
||||
'工程数据库' if record['scope'] == 'project' else '报错中指定的数据库')
|
||||
reason = '数据库副本不一致' if record.get('kind') == 'database_inconsistent' else '上次服务器会话失联'
|
||||
return (
|
||||
f"{ERROR_CODE}: {target}的上次服务器会话失联。\n"
|
||||
f"{ERROR_CODE}: {target}{reason};发现问题,未修复。\n"
|
||||
f"{record['native_message']}\n"
|
||||
f'{RECOVERY_ACTION}'
|
||||
)
|
||||
@@ -100,7 +117,8 @@ def snapshot_log(path):
|
||||
return {'size': size, 'tail_sha256': hashlib.sha256(tail).hexdigest(),
|
||||
'truncated': size > LOG_LIMIT,
|
||||
'icdb_errors': [' '.join(message.split()) for message in _icdb_error_paragraphs(decode_log(tail))],
|
||||
'session_losses': losses}
|
||||
'session_losses': losses,
|
||||
'inconsistent_databases': [match[1] for match in _INCONSISTENT.finditer(decode_log(tail))]}
|
||||
except FileNotFoundError:
|
||||
return {'size': 0, 'tail_sha256': hashlib.sha256(b'').hexdigest(), 'icdb_errors': []}
|
||||
except OSError as error:
|
||||
@@ -161,6 +179,12 @@ def read_log_failure(path, baseline):
|
||||
historical = baseline.get('session_losses', []) if baseline else []
|
||||
recovery = next((record for record in _session_losses(text)
|
||||
if appended or _session_identity(record) not in historical), None)
|
||||
if recovery is None:
|
||||
old = baseline.get('inconsistent_databases') if baseline else None
|
||||
match = next((match for match in _INCONSISTENT.finditer(text)
|
||||
if appended or old is not None and match[1] not in old), None)
|
||||
if match is not None:
|
||||
recovery = parse_recovery_request(match[0])
|
||||
return text, recovery
|
||||
|
||||
|
||||
|
||||
@@ -19,22 +19,25 @@ def assert_native_idle(target=None):
|
||||
from .native_export_guard import assert_retained_exports_idle
|
||||
from .native_engineering_identity import _OWNER_NAMES
|
||||
from .library_lock import _key, _owner_matches_scope
|
||||
library = None
|
||||
library = Path(target.library) if target is not None and getattr(target, 'library', None) else None
|
||||
roots = ()
|
||||
if target is not None:
|
||||
from .backup_recovery import _project_text
|
||||
roots = (Path(target.project).parent, Path(target.database))
|
||||
try:
|
||||
lines = re.findall(r'^KEY CentralLibrary\b[^\r\n]*', _project_text(target.project), re.M)
|
||||
references = [re.fullmatch(r'KEY CentralLibrary "([^"\r\n]+)"\s*', line) for line in lines]
|
||||
if not references or any(match is None for match in references):
|
||||
raise ValueError('CentralLibrary references are missing or invalid.')
|
||||
libraries = {(Path(target.project).parent/match[1]).resolve(strict=True) for match in references}
|
||||
if len(libraries) == 1 and all(path.suffix.casefold() == '.lmc' and path.is_file() for path in libraries):
|
||||
library = libraries.pop()
|
||||
roots += (library.parent/'SymbolLibs',)
|
||||
except (OSError, ValueError):
|
||||
pass # Missing/ambiguous original references cannot narrow retained ownership.
|
||||
if library is not None:
|
||||
roots += (library.parent/'SymbolLibs',)
|
||||
else:
|
||||
try:
|
||||
lines = re.findall(r'^KEY CentralLibrary\b[^\r\n]*', _project_text(target.project), re.M)
|
||||
references = [re.fullmatch(r'KEY CentralLibrary "([^"\r\n]+)"\s*', line) for line in lines]
|
||||
if not references or any(match is None for match in references):
|
||||
raise ValueError('CentralLibrary references are missing or invalid.')
|
||||
libraries = {(Path(target.project).parent/match[1]).resolve(strict=True) for match in references}
|
||||
if len(libraries) == 1 and all(path.suffix.casefold() == '.lmc' and path.is_file() for path in libraries):
|
||||
library = libraries.pop()
|
||||
roots += (library.parent/'SymbolLibs',)
|
||||
except (OSError, ValueError):
|
||||
pass # Missing/ambiguous original references cannot narrow retained ownership.
|
||||
assert_retained_exports_idle(library)
|
||||
if any(worker.poll() is None and (library is None or not getattr(worker, 'cbb_library', None)
|
||||
or _key(worker.cbb_library) == _key(library)) for worker in _retained_workers):
|
||||
|
||||
@@ -68,6 +68,10 @@ def pcb_startup_timeout_seconds(timeout_seconds):
|
||||
return max(60.0, float(timeout_seconds))
|
||||
|
||||
|
||||
def lm_dispatch_timeout_seconds(timeout_seconds):
|
||||
return max(.1, min(45.0, float(timeout_seconds)))
|
||||
|
||||
|
||||
def same_path(first, second):
|
||||
return os.path.normcase(os.path.abspath(str(first))) == os.path.normcase(os.path.abspath(str(second)))
|
||||
|
||||
@@ -698,12 +702,10 @@ def execute_job(job, emit):
|
||||
from .diagnostic_open import snapshot_diagnostic_logs
|
||||
job['diagnostic_log_baseline'] = snapshot_diagnostic_logs(job)
|
||||
else:
|
||||
ensure_pcb_central_library(
|
||||
job['pcb'],
|
||||
job['lmc_file'],
|
||||
evidence_dir=Path(root) / 'diagnostics',
|
||||
emit=emit,
|
||||
)
|
||||
from .maintenance_entry import maintenance_project_files
|
||||
for index, config in enumerate(maintenance_project_files(job['project'], job['pcb'])):
|
||||
ensure_project_central_library(config, job['lmc_file'],
|
||||
evidence_dir=Path(root)/'diagnostics'/f'project-{index}', emit=emit)
|
||||
emit(
|
||||
stage='verify_mode',
|
||||
mode=('library_manager_native' if bool(job.get('native_lm_verify', False))
|
||||
@@ -716,12 +718,13 @@ def execute_job(job, emit):
|
||||
pcb_started_ns = time.time_ns()
|
||||
if bool(job.get('native_lm_verify', False)):
|
||||
from .library_manager_verify import launch_library_verify
|
||||
dispatch_deadline = time.monotonic()+lm_dispatch_timeout_seconds(job['timeout'])
|
||||
emit(stage='lm_launch', library=job['lmc_file'], block=job['block_name'])
|
||||
lm_session = launch_library_verify(
|
||||
job['lmc_file'],
|
||||
job['block_name'],
|
||||
emit,
|
||||
time.monotonic() + pcb_startup_timeout_seconds(job['timeout']),
|
||||
dispatch_deadline,
|
||||
mentor_bin=job.get('mentor_bin'),
|
||||
interactive_input=bool(job.get('interactive_input', False)),
|
||||
)
|
||||
@@ -737,8 +740,8 @@ def execute_job(job, emit):
|
||||
worker_parent_pid = int(launcher_process.pid)
|
||||
emit(stage='pcb_launcher_started', launcher_pid=worker_parent_pid,
|
||||
command=list(command), strategy='reusable_circuit_direct')
|
||||
pcb_deadline = reset_verify_activity_deadline(
|
||||
0.0, time.monotonic(), timeout_seconds=pcb_startup_timeout_seconds(job['timeout']))
|
||||
pcb_deadline = (dispatch_deadline if job.get('native_lm_verify') else
|
||||
time.monotonic()+pcb_startup_timeout_seconds(job['timeout']))
|
||||
while time.monotonic() < pcb_deadline:
|
||||
if job.get('cancel_signal') and Path(job['cancel_signal']).exists():
|
||||
raise RuntimeError('VERIFY_CANCELLED: PCB 启动期间收到停止请求')
|
||||
@@ -771,6 +774,8 @@ def execute_job(job, emit):
|
||||
break
|
||||
time.sleep(.2)
|
||||
if worker_pid is None:
|
||||
if job.get('native_lm_verify'):
|
||||
raise RuntimeError('VERIFY_DISPATCH_FAILED: LM 菜单返回但未观察到目标 PCB,未执行校验')
|
||||
raise RuntimeError('ReusableCircuit common 启动后未观察到 wg PCB 子进程')
|
||||
if job.get('diagnostic_only'):
|
||||
# Global PCB COM can wait on another design's modal window.
|
||||
@@ -926,6 +931,8 @@ def execute_job(job, emit):
|
||||
)
|
||||
if completed and lm_session is not None:
|
||||
lm_session.close()
|
||||
elif worker_pid is None and lm_session is not None:
|
||||
lm_session.close() # No PCB was dispatched; close only this owned LM.
|
||||
|
||||
|
||||
def cleanup_verify_processes(lm_pid, worker_pid, worker_parent_pid=None, *,
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
"""Open the official backup UI; version selection and writes stay native."""
|
||||
from dataclasses import dataclass
|
||||
import json
|
||||
import hashlib
|
||||
import os
|
||||
from pathlib import Path
|
||||
from pathlib import PureWindowsPath
|
||||
import re
|
||||
import stat
|
||||
import subprocess
|
||||
import sys
|
||||
@@ -39,6 +43,36 @@ def native_backup_project(library, block):
|
||||
return project
|
||||
|
||||
|
||||
def native_backup_target(request, *, mode='versions', target_database=None):
|
||||
"""Bind the official tool without requiring an openable/healthy PCB."""
|
||||
from .backup_recovery import _project_text
|
||||
from .maintenance_entry import maintenance_project_files
|
||||
if mode not in ('versions', 'repair'):
|
||||
raise ValueError('NATIVE_TARGET_MODE_INVALID')
|
||||
project = native_backup_project(request.lmc_file, request.block_name)
|
||||
candidates = (project,)
|
||||
if target_database is not None:
|
||||
pcbs = list((project.parent/'PCB').glob('*.pcb'))
|
||||
if len(pcbs) != 1:
|
||||
raise ValueError('NATIVE_TARGET_UNCONFIRMED: 无法唯一绑定 PCB 工程')
|
||||
candidates = maintenance_project_files(project, pcbs[0])
|
||||
matches = []
|
||||
for config in candidates:
|
||||
values = re.findall(r'^KEY iCDBDir "([^"\r\n]+)"\s*$', _project_text(config), re.M)
|
||||
if len(values) != 1 or not values[0] or PureWindowsPath(values[0]).root or PureWindowsPath(values[0]).drive:
|
||||
if config == project or target_database is None:
|
||||
raise ValueError('NATIVE_TARGET_UNCONFIRMED: 主 PRJ 的 iCDBDir 未唯一绑定')
|
||||
continue
|
||||
database = (config.parent/values[0]).resolve()
|
||||
if not database.is_relative_to(project.parent.resolve()):
|
||||
raise ValueError('NATIVE_TARGET_UNCONFIRMED: 数据库不在当前工程内')
|
||||
if target_database is None or database == Path(target_database).resolve():
|
||||
matches.append((config, database))
|
||||
if len(matches) != 1:
|
||||
raise ValueError('NATIVE_TARGET_UNCONFIRMED: 诊断数据库未绑定唯一工程 PRJ')
|
||||
return matches[0]
|
||||
|
||||
|
||||
@dataclass
|
||||
class NativeBackupSession:
|
||||
process: object
|
||||
@@ -46,10 +80,18 @@ class NativeBackupSession:
|
||||
library: Path
|
||||
block: str
|
||||
path_lease: object = None
|
||||
mode: str = 'versions'
|
||||
project: Path | None = None
|
||||
database: Path | None = None
|
||||
session_record_path: Path | None = None
|
||||
operation_id: str | None = None
|
||||
|
||||
|
||||
def launch_native_backup(request):
|
||||
project = native_backup_project(request.lmc_file, request.block_name)
|
||||
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
|
||||
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])
|
||||
library_root = Path(request.lmc_file).resolve().parent
|
||||
@@ -57,17 +99,54 @@ def launch_native_backup(request):
|
||||
raise ValueError('运行记录目录需位于中心库之外。')
|
||||
root.mkdir(parents=True)
|
||||
job = root/'request.json'
|
||||
job.write_text(json.dumps({'library': str(request.lmc_file), 'block': request.block_name,
|
||||
'project': str(project), 'mentor_bin': request.mentor_bin}, ensure_ascii=False), 'utf-8')
|
||||
recheck_previous_release(request.lmc_file, root/'previous-release',
|
||||
block_name=request.block_name, stop=task_stop(None))
|
||||
record = {'library': str(request.lmc_file), 'block': request.block_name,
|
||||
'project': str(project), 'database': str(database), 'mode': mode,
|
||||
'project_sha256': hashlib.sha256(project.read_bytes()).hexdigest(),
|
||||
'target_database': str(target_database) if target_database is not None else 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'),
|
||||
'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
|
||||
[sys.executable, '-m', 'cbb_refresh_verify'])+['--native-backup-worker', str(job)]
|
||||
process = subprocess.Popen(command, creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0))
|
||||
return NativeBackupSession(process, job, Path(request.lmc_file), request.block_name)
|
||||
try:
|
||||
check_active()
|
||||
process = subprocess.Popen(command, creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0))
|
||||
register_worker_session(process, record)
|
||||
with native_channel():
|
||||
check_active()
|
||||
Path(record['start_gate']).touch()
|
||||
except BaseException:
|
||||
Path(record['cancel_signal']).touch() # The unadmitted child exits without native launch.
|
||||
raise
|
||||
return NativeBackupSession(process, job, Path(request.lmc_file), request.block_name,
|
||||
mode=mode, project=project, database=database, session_record_path=Path(record['session_record_path']),
|
||||
operation_id=record['operation_id'])
|
||||
|
||||
|
||||
class _BackupJobWriter:
|
||||
"""Independent Job handle keeps future descendants inside the writer boundary."""
|
||||
def __init__(self, job):
|
||||
import win32api, win32con
|
||||
current = win32api.GetCurrentProcess()
|
||||
self.job = win32api.DuplicateHandle(current, job, current, 0, False, win32con.DUPLICATE_SAME_ACCESS)
|
||||
|
||||
def poll(self):
|
||||
import win32job
|
||||
if self.job is None:
|
||||
return 0
|
||||
if win32job.QueryInformationJobObject(self.job, win32job.JobObjectBasicProcessIdList):
|
||||
return None
|
||||
self.job.Close(); self.job = None
|
||||
return 0
|
||||
|
||||
|
||||
class _NativeBackupProcess:
|
||||
"""Track this visible tool and its descendants without killing on close."""
|
||||
def __init__(self, command, cwd):
|
||||
def __init__(self, command, cwd, *, before_resume=None):
|
||||
import win32con, win32job, win32process
|
||||
self.job = win32job.CreateJobObject(None, '')
|
||||
startup = win32process.STARTUPINFO()
|
||||
@@ -80,6 +159,8 @@ class _NativeBackupProcess:
|
||||
raise
|
||||
try:
|
||||
win32job.AssignProcessToJobObject(self.job, self.handle)
|
||||
if before_resume is not None:
|
||||
before_resume(self)
|
||||
win32process.ResumeThread(thread)
|
||||
except Exception:
|
||||
# No native code has run while suspended; there can be no DB write.
|
||||
@@ -102,11 +183,54 @@ class _NativeBackupProcess:
|
||||
self.handle.Close(); self.job.Close()
|
||||
|
||||
|
||||
def run_native_backup_worker(job):
|
||||
"""Publish admission refusal only when this exact worker never entered native work."""
|
||||
from .desktop_worker import run_native_worker
|
||||
from .management import _write_json
|
||||
from .session_record import IDENTITY_KEYS, process_identity, read_session_record
|
||||
job = Path(job)
|
||||
entered = False
|
||||
request = json.loads(job.read_text('utf-8'))
|
||||
identity = process_identity(os.getpid())
|
||||
def registered():
|
||||
try:
|
||||
path = Path(request['session_record_path'])
|
||||
session = read_session_record(path, evidence_root=job.parent)
|
||||
return (session['operation_id'] == request['operation_id']
|
||||
and session.get('operation') == 'native_backup'
|
||||
and session.get('library') == request['library'] and session.get('block') == request['block']
|
||||
and request.get('project') in session.get('resource_scope', {}).get('projects', ())
|
||||
and any(all(process.get(key) == identity[key] for key in IDENTITY_KEYS)
|
||||
for process in session.get('processes', ()) if process.get('role') == 'worker'))
|
||||
except (OSError, ValueError, KeyError, TypeError):
|
||||
return False # Unknown registration never establishes a safe terminal result.
|
||||
def execute(path):
|
||||
nonlocal entered
|
||||
if not registered():
|
||||
raise ValueError('NATIVE_BACKUP_ADMISSION_UNCONFIRMED: 当前工程与工作进程未登记')
|
||||
entered = True
|
||||
return native_backup_worker_main(path)
|
||||
try:
|
||||
return run_native_worker(execute, job)
|
||||
except Exception as error:
|
||||
bound = registered()
|
||||
_write_json(job.with_name('result.json'), {'status': 'FAILED', 'detail': str(error),
|
||||
'operation_id': request.get('operation_id'), 'worker_identity': identity,
|
||||
'library': request.get('library'), 'block': request.get('block'),
|
||||
'mode': request.get('mode', 'versions'), 'project': request.get('project'),
|
||||
'database': request.get('database'), 'worker_entered': entered,
|
||||
'native_started': None if entered else False,
|
||||
'safe_to_continue': bound and not entered, 'restore_confirmed': False,
|
||||
'repair_confirmed': False, 'validation_passed': False, 'automatic_repair': False})
|
||||
return 1
|
||||
|
||||
|
||||
def native_backup_worker_main(job, *, process_factory=None):
|
||||
from .library_lock import LibraryLock
|
||||
from .management import _write_json
|
||||
job = Path(job)
|
||||
result = {'status': 'FAILED', 'safe_to_continue': True, 'restore_confirmed': False}
|
||||
result = {'status': 'FAILED', 'safe_to_continue': True, 'restore_confirmed': False,
|
||||
'repair_confirmed': False, 'validation_passed': False, 'automatic_repair': False}
|
||||
native = None
|
||||
def write_evidence(name, value):
|
||||
try:
|
||||
@@ -117,14 +241,34 @@ def native_backup_worker_main(job, *, process_factory=None):
|
||||
try:
|
||||
record = json.loads(job.read_text('utf-8'))
|
||||
library, block = Path(record['library']), record['block']
|
||||
result.update(library=str(library), block=block)
|
||||
project = native_backup_project(library, block)
|
||||
result.update(library=str(library), block=block, operation_id=record.get('operation_id'))
|
||||
from types import SimpleNamespace
|
||||
mode = record.get('mode', 'versions')
|
||||
project, database = native_backup_target(SimpleNamespace(lmc_file=library, block_name=block),
|
||||
mode=mode, target_database=record.get('target_database'))
|
||||
if project != Path(record['project']):
|
||||
raise ValueError('工程身份已变化,未打开原生工具。')
|
||||
if record.get('project_sha256') and hashlib.sha256(project.read_bytes()).hexdigest() != record['project_sha256']:
|
||||
raise ValueError('工程内容身份已变化,未打开原生工具。')
|
||||
if record.get('database') and database != Path(record['database']):
|
||||
raise ValueError('数据库身份已变化,未打开原生工具。')
|
||||
result.update(mode=mode, project=str(project), database=str(database),
|
||||
session_record_path=record.get('session_record_path'))
|
||||
executable = native_backup_executable(record.get('mentor_bin', ''))
|
||||
released = True
|
||||
with LibraryLock(library, checkpoint=False, safe_to_release=lambda: released):
|
||||
native = (process_factory or _NativeBackupProcess)([str(executable), '-p', str(project)], project.parent)
|
||||
with LibraryLock(library, checkpoint=bool(record.get('session_record_path')),
|
||||
block_name=block, safe_to_release=lambda: released):
|
||||
from .maintenance_entry import _assert_native_idle_for
|
||||
_assert_native_idle_for(SimpleNamespace(project=project, database=database, library=library))
|
||||
def admitted(process):
|
||||
from .session_record import update_worker_state
|
||||
from .desktop_worker import register_native_writer
|
||||
if record.get('session_record_path'):
|
||||
update_worker_state(record, 'NATIVE_CALL', identities=(('native', process.pid),), required=True)
|
||||
register_native_writer(_BackupJobWriter(process.job))
|
||||
command = [str(executable), '-p', str(project)] # User alone invokes Repair in the official UI.
|
||||
native = (process_factory(command, project.parent) if process_factory else
|
||||
_NativeBackupProcess(command, project.parent, before_resume=admitted))
|
||||
released = False
|
||||
result.update(status='OPEN', native_pid=native.pid, project=str(project), safe_to_continue=False)
|
||||
write_evidence('state.json', result)
|
||||
@@ -145,6 +289,7 @@ def native_backup_worker_main(job, *, process_factory=None):
|
||||
time.sleep(.25)
|
||||
released = True
|
||||
result.update(status='CLOSED', native_exit_code=exit_code, safe_to_continue=True)
|
||||
result['release'] = {'native_exited': True, 'remaining_pids': [], 'safe_to_continue': True}
|
||||
return 0 if result['native_exit_code'] == 0 else 1
|
||||
except Exception as error:
|
||||
result.update(status='FAILED', detail=str(error), safe_to_continue=native is None)
|
||||
|
||||
@@ -192,6 +192,10 @@ def _inspect_project(job, process, emit):
|
||||
result = {'status': 'UNCONFIRMED', 'project': str(project), 'database': str(database),
|
||||
'native_pid': process.pid, 'inspection_only': True, 'repair_requested': False,
|
||||
'repair_required': False, 'output': ''}
|
||||
if getattr(process, '_handle', None) is not None:
|
||||
from .residual_sessions import _handle_identity, _force_ownership
|
||||
result['native_identity'] = dict(pid=process.pid,
|
||||
**_handle_identity(process._handle), **_force_ownership(process._handle, process.pid))
|
||||
deadline = time.monotonic() + max(1, float(job['timeout']))
|
||||
closing = False
|
||||
last_state = None
|
||||
|
||||
@@ -48,8 +48,14 @@ def validate_owner(job, target_pid, launcher_pid, worker_pid):
|
||||
|
||||
@contextmanager
|
||||
def resource_guard(job, allowed_pids):
|
||||
import win32con, win32file
|
||||
from .icdb_ownership import database_directories, unreleased_addresses
|
||||
import hashlib
|
||||
from .file_probe import hold_release_files
|
||||
from .maintenance_entry import maintenance_project_files
|
||||
from .native_repair import RepairTarget, run_native_repair
|
||||
from .native_occupancy import confirmed_inspection
|
||||
from .session_record import IDENTITY_KEYS
|
||||
from .operation_queue import task_stop
|
||||
from .management import _write_json
|
||||
from .owner_probe import query_process_snapshot
|
||||
from .library_lock import _owner_is_blocking
|
||||
from .verify_runner import preflight, VerifyRequest
|
||||
@@ -58,21 +64,48 @@ def resource_guard(job, allowed_pids):
|
||||
if project.resolve() != Path(job['project']).resolve() or pcb.resolve() != Path(job['pcb']).resolve():
|
||||
raise ValueError('PCB_OPEN_PROJECT_CHANGED')
|
||||
roots = (project.parent, library.parent/'SymbolLibs')
|
||||
configs = maintenance_project_files(project, pcb)
|
||||
def binding():
|
||||
return {str(path.resolve()): hashlib.sha256(path.read_bytes()).hexdigest() for path in (pcb, *configs)}
|
||||
original_binding = binding()
|
||||
def check():
|
||||
if unreleased_addresses(library, project, pcb):
|
||||
raise ValueError('目标仍有数据库地址记录,暂不能确认读写打开。')
|
||||
for row in query_process_snapshot():
|
||||
if row['pid'] not in allowed_pids and _owner_is_blocking(row, library, roots):
|
||||
raise ValueError(f'目标还有其他会话,PID={row["pid"]};未确认读写打开。')
|
||||
check()
|
||||
paths = [library, pcb.parent/'Layout/LayoutDB.lyt',
|
||||
*(d/'icdb.dat' for d in database_directories(library, project, pcb) if (d/'icdb.dat').is_file())]
|
||||
stop = task_stop(None)
|
||||
with ExitStack() as stack:
|
||||
for path in dict.fromkeys(paths):
|
||||
handle = win32file.CreateFile(str(path), win32con.GENERIC_READ, 0, None,
|
||||
win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None)
|
||||
stack.callback(handle.Close)
|
||||
files = stack.enter_context(hold_release_files(library, roots, stop=stop))
|
||||
inspections = []
|
||||
if files['addresses']:
|
||||
targets = files['inspection_targets']
|
||||
if any(Path(item['project']).resolve() not in {p.resolve() for p in configs} for item in targets):
|
||||
raise ValueError('PCB_OPEN_DATABASE_UNCONFIRMED: 地址未绑定实际工程配置,需人工核对')
|
||||
stack.close() # Native inspection must access the DB; repeat exact proof afterwards.
|
||||
for index, item in enumerate(targets):
|
||||
target = RepairTarget(Path(item['project']), Path(item['database']))
|
||||
evidence = Path(job['root'])/('open-inspection-'+str(index))
|
||||
result = run_native_repair(target, evidence, mentor_bin=job.get('mentor_bin'),
|
||||
timeout_seconds=min(45, float(job.get('timeout', 45))), inspection_only=True, stop=stop)
|
||||
identity = result.get('native_identity') or {}
|
||||
if (not confirmed_inspection(target, result) or result['status'] != 'NOT_IN_USE'
|
||||
or identity.get('pid') != result.get('native_pid')
|
||||
or any(identity.get(key) is None for key in IDENTITY_KEYS)
|
||||
or not identity.get('image') or not identity.get('owner_sid')):
|
||||
raise ValueError('PCB_OPEN_DATABASE_UNCONFIRMED: 原生检查未确认当前数据库未占用')
|
||||
inspections.append(result)
|
||||
current = stack.enter_context(hold_release_files(library, roots, stop=stop))
|
||||
if any(current[key] != files[key] for key in (
|
||||
'exclusive_files', 'binding_files', 'addresses', 'signatures', 'inspection_targets', 'resource_scope')):
|
||||
raise ValueError('PCB_OPEN_RESOURCE_CHANGED: 原生检查期间资源或地址身份变化')
|
||||
if binding() != original_binding:
|
||||
raise ValueError('PCB_OPEN_PROJECT_CHANGED: 原生检查期间工程引用变化')
|
||||
check()
|
||||
_write_json(Path(job['root'])/'pcb-open-resource-proof.json', {
|
||||
'operation_id': job.get('operation_id'), 'library': str(library),
|
||||
'project': str(project), 'pcb': str(pcb), 'binding': original_binding,
|
||||
'exclusive_files': files['exclusive_files'], 'addresses': files['addresses'],
|
||||
'native_inspections': inspections, 'repair_confirmed': False})
|
||||
yield
|
||||
|
||||
|
||||
|
||||
@@ -548,6 +548,8 @@ def run_verify(request, *, progress=None, flag_reader=None, process_runner=None,
|
||||
dialog_supervisor_factory=None, version_prompt=None, stop=None, context=None,
|
||||
admission_timeout_seconds=10):
|
||||
from .operation_queue import BatchTaskContext, TaskHandoff, current_context, task_stop
|
||||
if stop is not None and stop.is_set() or context is not None and context.stop.is_set():
|
||||
return VerifyResult('CANCELLED', stderr='已取消,未启动原生操作。', safe_to_continue=True)
|
||||
options = dict(progress=progress, flag_reader=flag_reader, process_runner=process_runner,
|
||||
port_check=port_check, dialog_supervisor_factory=dialog_supervisor_factory,
|
||||
version_prompt=version_prompt)
|
||||
@@ -776,13 +778,13 @@ def _run_verify_serialized(request, *, progress=None, flag_reader=None, process_
|
||||
finally:
|
||||
timing.end('failure_diagnostics')
|
||||
if result.status not in {'PASS', 'SKIPPED', 'QUEUE_STOP'}:
|
||||
from .icdb_recovery import ERROR_CODE, RECOVERY_ACTION, parse_session_loss, recovery_detail
|
||||
recovery = parse_session_loss(result.stderr)
|
||||
from .icdb_recovery import ERROR_CODE, RECOVERY_ACTION, parse_recovery_request, recovery_detail
|
||||
recovery = parse_recovery_request(result.stderr)
|
||||
if recovery is None and result.evidence_path:
|
||||
try:
|
||||
saved = json.loads(result.evidence_path.with_name('diagnostics').joinpath(
|
||||
'icdb-recovery.json').read_text('utf-8'))
|
||||
recovery = parse_session_loss(saved.get('native_message', ''))
|
||||
recovery = parse_recovery_request(saved.get('native_message', ''))
|
||||
except (OSError, ValueError, AttributeError):
|
||||
pass
|
||||
if recovery or ERROR_CODE.casefold() in result.stderr.casefold():
|
||||
@@ -952,6 +954,7 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
launcher_pid = None
|
||||
lm_pid = None
|
||||
verify_invoked = False
|
||||
lm_dispatch_deadline = None
|
||||
invoke_returned = False
|
||||
pcb_baseline = set()
|
||||
last_observation = 0.0
|
||||
@@ -1045,6 +1048,9 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
if event.get('launcher_pid'): launcher_pid = event['launcher_pid']
|
||||
if event.get('lm_pid'): lm_pid = event['lm_pid']
|
||||
stage = event.get('stage')
|
||||
if stage == 'lm_launch' and lm_dispatch_deadline is None:
|
||||
from .mentor_adapter import lm_dispatch_timeout_seconds
|
||||
lm_dispatch_deadline = (event.get('monotonic_seconds') or time.monotonic()) + lm_dispatch_timeout_seconds(request.timeout_seconds)
|
||||
if stage == 'verify_invoke': verify_invoked = True
|
||||
if stage == 'verify_invoke_returned': invoke_returned = True
|
||||
if stage == 'pcb_baseline': pcb_baseline = set(event.get('pids', ()))
|
||||
@@ -1162,7 +1168,8 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
error_stage=phase.value,
|
||||
safe_to_continue=False,
|
||||
))
|
||||
if deadline.expired():
|
||||
if deadline.expired() or (lm_dispatch_deadline is not None and target_pid is None
|
||||
and time.monotonic() >= lm_dispatch_deadline):
|
||||
_write_failure_windows(root, latest_snapshots)
|
||||
# Stop automation without killing PCB/iCDB during a write.
|
||||
_write_process_tree(root, process, target_pid)
|
||||
|
||||
Reference in new issue
Block a user