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
@@ -29,14 +29,55 @@ def _paths(root):
|
||||
|
||||
|
||||
def _idle_check(library, project, pcb):
|
||||
from .mentor_adapter import pcb_processes, _process_details
|
||||
from .icdb_ownership import unreleased_addresses
|
||||
if pcb_processes() or any(_process_details(name) for name in (
|
||||
'LibraryManager.exe', 'viewdraw.exe')):
|
||||
raise ValueError('请先正常关闭 PCB、Library Manager 和原理图编辑器,再恢复备份。')
|
||||
from .mentor_adapter import _process_details
|
||||
from .icdb_ownership import database_directories, unreleased_addresses
|
||||
from contextlib import ExitStack
|
||||
import win32con, win32file
|
||||
directories = database_directories(library, project, pcb)
|
||||
scope = (Path(project).parent, *directories)
|
||||
for name in ('ExpeditionPCB.exe', 'LibraryManager.exe', 'viewdraw.exe',
|
||||
'iCDBProjectBackup.exe', 'ReuseBlockImporter.exe'):
|
||||
for pid, executable, command, parent in _process_details(name):
|
||||
match = _native_scope_match(command, roots=scope, files=(library, project, pcb))
|
||||
if match is True:
|
||||
raise ValueError(f'TARGET_NATIVE_OWNER_ACTIVE: 目标工程或共享库有原生会话,PID={pid}')
|
||||
if match is None:
|
||||
raise ValueError(f'TARGET_NATIVE_OWNER_UNCONFIRMED: 无法确认原生会话所属工程,PID={pid}')
|
||||
addresses = unreleased_addresses(library, project, pcb)
|
||||
if addresses:
|
||||
raise ValueError(f'数据库会话尚未释放,停止恢复:{addresses}')
|
||||
raise ValueError(f'TARGET_DATABASE_ADDRESS_UNCONFIRMED: 地址记录需原生确认;未据此判定正在占用:{addresses}')
|
||||
with ExitStack() as stack:
|
||||
paths = [Path(library), Path(pcb).parent/'Layout/LayoutDB.lyt',
|
||||
*(directory/'icdb.dat' for directory in directories)]
|
||||
for path in dict.fromkeys(paths):
|
||||
if path.is_file():
|
||||
handle = win32file.CreateFile(str(path), win32con.GENERIC_READ, 0, None,
|
||||
win32con.OPEN_EXISTING, 0, None)
|
||||
stack.callback(handle.Close)
|
||||
|
||||
|
||||
def _native_scope_match(command, *, roots=(), files=()):
|
||||
"""Match complete native path arguments; a missing identity remains unknown."""
|
||||
from .failed_session import _command_args
|
||||
if not command:
|
||||
return None
|
||||
expected_files = {Path(path).resolve() for path in files}
|
||||
expected_roots = tuple(Path(path).resolve() for path in roots)
|
||||
identities = []
|
||||
for arg in _command_args(command)[1:]:
|
||||
value = arg.split('=', 1)[-1].strip('"')
|
||||
path = Path(value)
|
||||
if not path.is_absolute():
|
||||
continue
|
||||
key = arg.split('=', 1)[0].lstrip('-/').casefold() if '=' in arg else ''
|
||||
if (path.suffix.casefold() in ('.prj', '.pcb', '.lmc')
|
||||
or path.name.casefold() in ('database', '__reusableblockssymb', 'icdb.dat')
|
||||
or key in ('project', 'icdb', 'database', 'db', 'lmc', 'prj', 'pcb')):
|
||||
identities.append(path.resolve())
|
||||
if not identities:
|
||||
return None
|
||||
return any(path in expected_files or any(path == root or path.is_relative_to(root)
|
||||
for root in expected_roots) for path in identities)
|
||||
|
||||
|
||||
def _project_text(path):
|
||||
@@ -140,9 +181,12 @@ def recover_from_backup(request, source, *, progress=None, verifier=None, idle_c
|
||||
return report
|
||||
def save(result):
|
||||
record.update({'installed': installed, 'result': asdict(result)})
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
report = root/'recovery-result.json'
|
||||
report.write_text(json.dumps(record, ensure_ascii=False, default=str, indent=2), encoding='utf-8')
|
||||
try:
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
report.write_text(json.dumps(record, ensure_ascii=False, default=str, indent=2), encoding='utf-8')
|
||||
except OSError as error:
|
||||
return replace(result, stderr=(result.stderr+'\n恢复报告写入失败:'+str(error)).strip())
|
||||
return replace(result, evidence_path=report)
|
||||
from .com_runtime import initialize_com, uninitialize_com
|
||||
initialized = initialize_com()
|
||||
@@ -239,7 +283,7 @@ def recover_from_backup(request, source, *, progress=None, verifier=None, idle_c
|
||||
return save(final)
|
||||
except Exception as error:
|
||||
return save(VerifyResult('FAIL' if installed else 'BLOCKED', stderr=str(error),
|
||||
safe_to_continue=False))
|
||||
safe_to_continue=release_confirmed))
|
||||
finally:
|
||||
try:
|
||||
if library_lock is not None:
|
||||
|
||||
@@ -48,6 +48,7 @@ class BatchStatusRecord:
|
||||
detail: str = ""
|
||||
fingerprint: str = ""
|
||||
timestamp: str = ""
|
||||
block_type: str = "RULP"
|
||||
|
||||
@property
|
||||
def completed(self) -> bool:
|
||||
@@ -109,6 +110,8 @@ def fingerprint_library(lmc: Path) -> LmcFingerprint:
|
||||
# digest so a changed central library can never reuse an old status row.
|
||||
content_sha256 = _sha256_file(path)
|
||||
combined = hashlib.sha256()
|
||||
combined.update(str(path).casefold().encode('utf-8', errors='surrogatepass'))
|
||||
combined.update(b'\0')
|
||||
combined.update(content_sha256.encode("ascii"))
|
||||
combined.update(b"\0" + str(stat.st_size).encode("ascii"))
|
||||
combined.update(b"\0" + str(stat.st_mtime_ns).encode("ascii") + b"\0")
|
||||
@@ -165,6 +168,7 @@ class BatchCheckpoint:
|
||||
detail=str(payload.get("detail") or ""),
|
||||
fingerprint=str(payload.get("fingerprint") or ""),
|
||||
timestamp=str(payload.get("timestamp") or ""),
|
||||
block_type=str(payload.get("block_type") or "RULP"),
|
||||
)
|
||||
return cls(records)
|
||||
|
||||
@@ -212,7 +216,7 @@ class BatchStatusSession:
|
||||
for index, name in enumerate(names):
|
||||
previous = checkpoint.get(name)
|
||||
if (previous and previous.status in {'READY', 'PENDING'}
|
||||
and previous.fingerprint == fingerprint.sha256):
|
||||
and previous.fingerprint == fingerprint.sha256 and previous.block_type == block_type):
|
||||
results.append(previous)
|
||||
continue
|
||||
try:
|
||||
@@ -224,11 +228,12 @@ class BatchStatusSession:
|
||||
block_name=name, status=result.status, source=result.source,
|
||||
raw_status=result.raw_status, detail=result.detail,
|
||||
fingerprint=fingerprint.sha256, timestamp=_now(),
|
||||
block_type=block_type,
|
||||
)
|
||||
except BridgeUnavailable as error:
|
||||
record = BatchStatusRecord(block_name=name, status="UNAVAILABLE",
|
||||
detail=str(error), fingerprint=fingerprint.sha256,
|
||||
timestamp=_now())
|
||||
timestamp=_now(), block_type=block_type)
|
||||
except BridgeResponseError as error:
|
||||
message = str(error)
|
||||
lower_message = message.casefold()
|
||||
@@ -242,15 +247,15 @@ class BatchStatusSession:
|
||||
else "UNAVAILABLE" if unavailable
|
||||
else "MALFORMED" if malformed else "ERROR")
|
||||
record = BatchStatusRecord(block_name=name, status=status, detail=message,
|
||||
fingerprint=fingerprint.sha256, timestamp=_now())
|
||||
if server is not None and status not in {"UNAVAILABLE", "MALFORMED"}:
|
||||
fingerprint=fingerprint.sha256, timestamp=_now(), block_type=block_type)
|
||||
if server is not None and status != "UNAVAILABLE":
|
||||
try:
|
||||
server.restart()
|
||||
except BridgeUnavailable:
|
||||
pass
|
||||
except Exception as error: # bridge failures isolate one CBB
|
||||
record = BatchStatusRecord(block_name=name, status="ERROR", detail=str(error),
|
||||
fingerprint=fingerprint.sha256, timestamp=_now())
|
||||
fingerprint=fingerprint.sha256, timestamp=_now(), block_type=block_type)
|
||||
if server is not None:
|
||||
try:
|
||||
server.restart()
|
||||
@@ -258,7 +263,7 @@ class BatchStatusSession:
|
||||
pass
|
||||
checkpoint.append(checkpoint_path, record)
|
||||
results.append(record)
|
||||
if record.status in {"UNAVAILABLE", "MALFORMED"} and index + 1 < len(names):
|
||||
if record.status == "UNAVAILABLE" and index + 1 < len(names):
|
||||
# Startup/protocol failures cannot be repaired by retrying
|
||||
# the same request contract for every CBB.
|
||||
# Preserve a terminal record for each remaining name so a
|
||||
@@ -267,6 +272,7 @@ class BatchStatusSession:
|
||||
unavailable_record = BatchStatusRecord(
|
||||
block_name=remaining, status=record.status, detail=record.detail,
|
||||
fingerprint=fingerprint.sha256, timestamp=_now(),
|
||||
block_type=block_type,
|
||||
)
|
||||
checkpoint.append(checkpoint_path, unavailable_record)
|
||||
results.append(unavailable_record)
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
"""Shared execution defaults for GUI, batch requests and integration."""
|
||||
|
||||
DEFAULT_TIMEOUT_SECONDS = 600
|
||||
DIALOG_AGENT_STARTUP_TIMEOUT_SECONDS = 30
|
||||
WORKER_START_GATE_TIMEOUT_SECONDS = DIALOG_AGENT_STARTUP_TIMEOUT_SECONDS + 15
|
||||
@@ -74,27 +74,58 @@ class DesktopWorker:
|
||||
def __init__(self, command, name, *, interactive_input=False):
|
||||
self.name = name
|
||||
self.interactive_input = bool(interactive_input)
|
||||
self.desktop = None if self.interactive_input else win32service.CreateDesktop(
|
||||
name, 0, win32con.GENERIC_ALL, None)
|
||||
# Track the session, but never use kill-on-close: PCB descendants can
|
||||
# still own a database transaction when the Python supervisor exits.
|
||||
self.job = win32job.CreateJobObject(None, '')
|
||||
self.job_bound = False
|
||||
self.desktop = None
|
||||
self.job = None
|
||||
self.handle = None
|
||||
self.companions = []
|
||||
self.companion_pids = []
|
||||
startup = win32process.STARTUPINFO()
|
||||
# subprocess.STARTUPINFO does NOT pass lpDesktop to CreateProcess.
|
||||
startup.lpDesktop = startup_desktop_name(name, interactive_input=self.interactive_input)
|
||||
self.handle, thread, self.pid, _ = win32process.CreateProcess(
|
||||
command[0], subprocess.list2cmdline(command), None, None, False,
|
||||
win32con.CREATE_NO_WINDOW, None, None, startup)
|
||||
thread.Close()
|
||||
self.job_bound = False
|
||||
# Track the session, but never use kill-on-close: PCB descendants can
|
||||
# still own a database transaction when the Python supervisor exits.
|
||||
try:
|
||||
win32job.AssignProcessToJobObject(self.job, self.handle)
|
||||
self.job_bound = True
|
||||
except Exception:
|
||||
# Kill-through-job is a cleanup guarantee, not a launch requirement.
|
||||
self.job_bound = False
|
||||
self.desktop = None if self.interactive_input else win32service.CreateDesktop(
|
||||
name, 0, win32con.GENERIC_ALL, None)
|
||||
self.job = win32job.CreateJobObject(None, '')
|
||||
startup = win32process.STARTUPINFO()
|
||||
# subprocess.STARTUPINFO does NOT pass lpDesktop to CreateProcess.
|
||||
startup.lpDesktop = startup_desktop_name(name, interactive_input=self.interactive_input)
|
||||
self.handle, thread, self.pid, _ = win32process.CreateProcess(
|
||||
command[0], subprocess.list2cmdline(command), None, None, False,
|
||||
win32con.CREATE_NO_WINDOW, None, None, startup)
|
||||
thread.Close()
|
||||
try:
|
||||
win32job.AssignProcessToJobObject(self.job, self.handle)
|
||||
self.job_bound = True
|
||||
except Exception:
|
||||
# Kill-through-job is a cleanup guarantee, not a launch requirement.
|
||||
self.job_bound = False
|
||||
except Exception as error:
|
||||
# No worker means no native descendants; a partial launch is uncertain.
|
||||
error.worker_launch_release = {
|
||||
'process_created': self.handle is not None,
|
||||
'safe_to_continue': self.handle is None,
|
||||
'worker_exited': self.handle is None,
|
||||
'remaining_pids': [self.pid] if self.handle is not None else []}
|
||||
if self.handle is not None:
|
||||
try:
|
||||
win32process.TerminateProcess(self.handle, 1)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
self.handle.Close()
|
||||
except Exception:
|
||||
pass
|
||||
if self.job is not None:
|
||||
try:
|
||||
self.job.Close()
|
||||
except Exception:
|
||||
pass
|
||||
if self.desktop is not None:
|
||||
try:
|
||||
self.desktop.CloseDesktop()
|
||||
except Exception:
|
||||
pass
|
||||
raise
|
||||
|
||||
def start_companion(self, command):
|
||||
startup = win32process.STARTUPINFO()
|
||||
@@ -131,7 +162,8 @@ class DesktopWorker:
|
||||
expected = {Path(__file__).with_name(name).resolve()
|
||||
for name in ('save_verified_block.vbs', 'close_failed_block.vbs')}
|
||||
clients = []
|
||||
for row in query_owners(('cscript.exe',), timeout_seconds=3):
|
||||
# Interpreter + COM startup measures ~4.75s on the field machine.
|
||||
for row in query_owners(('cscript.exe',), timeout_seconds=10):
|
||||
if row.get('parent') != self.pid:
|
||||
continue
|
||||
args = _command_args(row['command'])
|
||||
|
||||
@@ -0,0 +1,377 @@
|
||||
"""Process-bound native opening check. This module never acquires PCB COM.
|
||||
|
||||
The caller must bind the newly launched PCB command/PID before entering here.
|
||||
The check runs in that worker's private desktop and closes only that session.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import ctypes
|
||||
from ctypes import wintypes
|
||||
import heapq
|
||||
import hashlib
|
||||
import ntpath
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import time
|
||||
|
||||
from .dialog_probe import _bounded_call
|
||||
from .icdb_recovery import LOG_LIMIT, _read_log_delta, decode_log, snapshot_log
|
||||
|
||||
_MAX_WINDOWS = 128
|
||||
_MAX_CHILDREN = 512
|
||||
|
||||
|
||||
def _normal(path):
|
||||
return ntpath.normcase(ntpath.normpath(str(path).strip()))
|
||||
|
||||
|
||||
def _log_paths(job):
|
||||
project = Path(job['project']).parent
|
||||
pcb_logs = Path(job['pcb']).parent / 'LogFiles'
|
||||
paths = [pcb_logs / 'PCBAutoSave.txt', pcb_logs / 'PCBLogFile.txt']
|
||||
directory = project / 'database/cdbsvr/log'
|
||||
directories = []
|
||||
if directory.is_dir():
|
||||
with os.scandir(directory) as entries:
|
||||
directories = [entry.name for entry in entries if entry.is_dir(follow_symlinks=False)]
|
||||
# Native names start with sortable YYYY-MM-DD HH.MM.SS. Only the
|
||||
# newest candidates can describe this launch; history is never read.
|
||||
for name in heapq.nlargest(8, directories):
|
||||
with os.scandir(directory / name) as entries:
|
||||
logs = heapq.nlargest(2, (entry.name for entry in entries
|
||||
if entry.is_file(follow_symlinks=False) and entry.name.casefold().endswith('.txt')))
|
||||
paths.extend(directory / name / log for log in logs)
|
||||
return paths, directories
|
||||
|
||||
|
||||
def _read_logs(job):
|
||||
result = {}
|
||||
paths, directories = _log_paths(job)
|
||||
for path in paths:
|
||||
try:
|
||||
record = snapshot_log(path)
|
||||
record['mtime_ns'] = path.stat().st_mtime_ns
|
||||
result[str(path)] = record
|
||||
except FileNotFoundError:
|
||||
result[str(path)] = snapshot_log(path)
|
||||
return {'files': result, 'server_directories': directories}
|
||||
|
||||
|
||||
def _read_bounded(function):
|
||||
try:
|
||||
return _bounded_call(function, 2)
|
||||
except TimeoutError as error:
|
||||
# Abort this check, rather than spawning another reader while a slow
|
||||
# share still owns the previous read. The daemon performs reads only.
|
||||
raise RuntimeError('DIAGNOSTIC_LOG_READ_TIMEOUT: native evidence unavailable') from error
|
||||
|
||||
|
||||
def snapshot_diagnostic_logs(job) -> dict:
|
||||
"""Capture pre-launch content, so copied/stale successes cannot pass.
|
||||
|
||||
Store the returned JSON-compatible value at job['diagnostic_log_baseline'].
|
||||
File count, content size and the entire read are bounded; failure is closed.
|
||||
"""
|
||||
started = time.time_ns()
|
||||
return {'started_ns': started, **_read_bounded(lambda: _read_logs(job))}
|
||||
|
||||
|
||||
def _fresh_logs_read(job, baseline):
|
||||
paths, _ = _log_paths(job)
|
||||
fresh = {}
|
||||
for path in paths:
|
||||
try:
|
||||
stat = path.stat()
|
||||
old = baseline['files'].get(str(path))
|
||||
if stat.st_mtime_ns < baseline['started_ns']:
|
||||
continue
|
||||
if old is None:
|
||||
if path.parent.name in baseline.get('server_directories', ()):
|
||||
continue # An unobserved historical file cannot prove freshness.
|
||||
old = {'size': 0, 'tail_sha256': hashlib.sha256(b'').hexdigest()}
|
||||
if 'error' in old or (old.get('mtime_ns') == stat.st_mtime_ns and old['size'] == stat.st_size):
|
||||
continue
|
||||
content, appended = _read_log_delta(path, old)
|
||||
if not content and stat.st_mtime_ns != old.get('mtime_ns') and stat.st_size == old['size']:
|
||||
# Native PCBLog is overwritten with the same successful text.
|
||||
content, _ = _read_log_delta(path, {'size': 0, 'tail_sha256': ''})
|
||||
if not appended and old.get('truncated') and stat.st_size > LOG_LIMIT:
|
||||
continue
|
||||
fresh[str(path)] = decode_log(content)
|
||||
except FileNotFoundError:
|
||||
continue
|
||||
return fresh
|
||||
|
||||
|
||||
def _fresh_logs(job, baseline):
|
||||
return _read_bounded(lambda: _fresh_logs_read(job, baseline))
|
||||
|
||||
|
||||
def _load_evidence(job, pcb_pid, baseline, *, require_autosave=True):
|
||||
logs = _fresh_logs(job, baseline)
|
||||
project = Path(job['project']).parent
|
||||
pcb = str(Path(job['pcb']))
|
||||
auto_path = str(Path(job['pcb']).parent / 'LogFiles/PCBAutoSave.txt')
|
||||
read_path = str(Path(job['pcb']).parent / 'LogFiles/PCBLogFile.txt')
|
||||
names = re.findall(r'^Job Name:\s*(.*?)\s*$', logs.get(auto_path, ''), re.M | re.I)
|
||||
if names and any(_normal(name) != _normal(pcb) for name in names):
|
||||
return None
|
||||
if require_autosave and not names:
|
||||
return None
|
||||
if 'Successfully read the design.' not in logs.get(read_path, ''):
|
||||
return None
|
||||
database = _normal(project / 'database')
|
||||
project_file = _normal(job['project'])
|
||||
for path, text in logs.items():
|
||||
if path in (auto_path, read_path):
|
||||
continue
|
||||
db_paths = re.findall(r'S: Project path \[(.*?)\]', text)
|
||||
prj_paths = re.findall(r'S: Project file \(\.prj\) path \[(.*?)\]', text)
|
||||
startup = re.search(r'S: Started up automatically by iCDB Client: [^\r\n]*:' + str(pcb_pid) + r'\s*$', text, re.M)
|
||||
client = re.search(r'Registered sub-client \[Expedition PCB[^\r\n]*process ID \[' + str(pcb_pid) + r'\]', text)
|
||||
if (db_paths and all(_normal(value) == database for value in db_paths)
|
||||
and prj_paths and all(_normal(value) == project_file for value in prj_paths)
|
||||
and startup and client and 'S: iCDB database loaded' in text):
|
||||
return {'pcb': pcb, 'pcb_pid': pcb_pid,
|
||||
'logs': [auto_path, read_path, path], 'document_identity': 'native_path_pid_logs'}
|
||||
return None
|
||||
|
||||
|
||||
def _target_frame(windows, name):
|
||||
matches = []
|
||||
for window in windows:
|
||||
if not window['class'].casefold().startswith('afx:') or not window.get('enabled', True):
|
||||
continue
|
||||
if not window['text'].casefold().startswith('expedition pcb') or f'[{name}]'.casefold() not in window['text'].casefold():
|
||||
continue
|
||||
mdi = {child['hwnd'] for child in window['children'] if child['class'].casefold() == 'mdiclient'}
|
||||
if any(child.get('parent') in mdi and child['text'].casefold() == name.casefold()
|
||||
and child['class'].casefold().startswith('afx:') for child in window['children']):
|
||||
matches.append(window)
|
||||
return matches[0] if len(matches) == 1 else None
|
||||
|
||||
|
||||
def _windows(pid):
|
||||
"""Read only this PID on the current desktop; cap text and enumeration work."""
|
||||
import win32api
|
||||
import win32gui
|
||||
import win32process
|
||||
user = ctypes.WinDLL('user32', use_last_error=True)
|
||||
user.GetWindowTextW.argtypes = [wintypes.HWND, wintypes.LPWSTR, ctypes.c_int]
|
||||
user.GetWindowTextW.restype = ctypes.c_int
|
||||
deadline = time.monotonic() + .2
|
||||
def text(hwnd):
|
||||
if time.monotonic() >= deadline:
|
||||
raise RuntimeError('DIAGNOSTIC_WINDOW_LIMIT: window scan exceeded 0.2s')
|
||||
buffer = ctypes.create_unicode_buffer(4096)
|
||||
# All handles belong to the external PCB PID: GetWindowText reads
|
||||
# Windows' cached caption without sending a message to its UI thread.
|
||||
# Custom controls may have no cached text; missing evidence fails closed.
|
||||
user.GetWindowTextW(hwnd, buffer, len(buffer))
|
||||
return buffer.value
|
||||
result = []
|
||||
seen = 0
|
||||
def collect(hwnd, _):
|
||||
nonlocal seen
|
||||
if win32process.GetWindowThreadProcessId(hwnd)[1] != pid or not win32gui.IsWindowVisible(hwnd):
|
||||
return True
|
||||
seen += 1
|
||||
if seen > _MAX_WINDOWS:
|
||||
raise RuntimeError('DIAGNOSTIC_WINDOW_LIMIT: too many windows')
|
||||
cls = win32gui.GetClassName(hwnd)
|
||||
if cls.casefold() in {'uac_inputindicatoroverlaywnd', 'uac input indicator'}:
|
||||
return True
|
||||
children = []
|
||||
count = 0
|
||||
def child(ch, _):
|
||||
nonlocal count
|
||||
count += 1
|
||||
if count > _MAX_CHILDREN:
|
||||
raise RuntimeError('DIAGNOSTIC_WINDOW_LIMIT: too many controls')
|
||||
child_cls = win32gui.GetClassName(ch)
|
||||
if (cls == '#32770' or cls.casefold() == 'internet explorer_hidden'
|
||||
or child_cls.casefold() == 'mdiclient' or child_cls.casefold().startswith('afx:')):
|
||||
children.append({'hwnd': ch, 'class': child_cls, 'text': text(ch),
|
||||
'id': win32gui.GetDlgCtrlID(ch), 'parent': win32gui.GetParent(ch),
|
||||
'enabled': bool(win32gui.IsWindowEnabled(ch))})
|
||||
return True
|
||||
if cls == '#32770' or cls.casefold().startswith('afx:') or cls.casefold() == 'internet explorer_hidden':
|
||||
win32gui.EnumChildWindows(hwnd, child, None)
|
||||
caption = text(hwnd)
|
||||
if cls.casefold() == 'internet explorer_hidden' and not caption and not children:
|
||||
left, top, right, bottom = win32gui.GetWindowRect(hwnd)
|
||||
if left == right and top == bottom:
|
||||
return True
|
||||
result.append({'hwnd': hwnd, 'pid': pid, 'class': cls, 'text': caption,
|
||||
'enabled': bool(win32gui.IsWindowEnabled(hwnd)), 'children': children,
|
||||
'owner': int(win32gui.GetWindow(hwnd, 4) or 0)})
|
||||
return True
|
||||
win32api.SetLastError(0)
|
||||
try:
|
||||
win32gui.EnumWindows(collect, None)
|
||||
except Exception as error:
|
||||
if getattr(error, 'winerror', None) not in (0, 2) or result:
|
||||
raise
|
||||
return result
|
||||
|
||||
|
||||
class _NativeSession:
|
||||
def __init__(self, job, pid, launcher):
|
||||
if launcher is None or not callable(getattr(launcher, 'poll', None)):
|
||||
raise RuntimeError('DIAGNOSTIC_LAUNCHER_REQUIRED: retain the exact launch process handle')
|
||||
import win32api
|
||||
import win32service
|
||||
import win32con
|
||||
import win32event
|
||||
import win32gui
|
||||
self.handles = []
|
||||
self.pid = int(pid)
|
||||
self.launcher = launcher
|
||||
self.gui = win32gui
|
||||
self.event = win32event
|
||||
desktop = win32service.GetThreadDesktop(win32api.GetCurrentThreadId())
|
||||
actual = win32service.GetUserObjectInformation(desktop, 2)
|
||||
expected = str(job.get('desktop', '')).split('\\')[-1]
|
||||
if not expected or expected.casefold() in {'default', 'winlogon', 'disconnect'} or actual.casefold() != expected.casefold():
|
||||
raise RuntimeError('DIAGNOSTIC_DESKTOP_MISMATCH')
|
||||
self.pcb = win32api.OpenProcess(win32con.SYNCHRONIZE, False, int(pid))
|
||||
self.handles.append(self.pcb)
|
||||
|
||||
def pcb_alive(self):
|
||||
return self.event.WaitForSingleObject(self.pcb, 0) != 0
|
||||
|
||||
def launcher_alive(self):
|
||||
return self.launcher.poll() is None
|
||||
|
||||
def post(self, hwnd, message):
|
||||
import win32process
|
||||
if not self.pcb_alive() or win32process.GetWindowThreadProcessId(hwnd)[1] != self.pid:
|
||||
raise RuntimeError('DIAGNOSTIC_STALE_WINDOW: target window identity changed')
|
||||
self.gui.PostMessage(hwnd, message, 0, 0)
|
||||
|
||||
def close(self):
|
||||
for handle in self.handles:
|
||||
handle.Close()
|
||||
self.handles.clear()
|
||||
|
||||
|
||||
def _cancel(job):
|
||||
if job.get('cancel_signal') and Path(job['cancel_signal']).exists():
|
||||
raise RuntimeError('VERIFY_CANCELLED: native opening check cancelled')
|
||||
|
||||
|
||||
def _pending_prompt(windows, *, closing=False, frame=None, session=None, clicked=None, pcb_name=''):
|
||||
for window in windows:
|
||||
known_titles = {'expedition pcb', 'expedition pcb - reusable block'}
|
||||
if (window['class'].casefold().startswith('afx:') and not window.get('owner')
|
||||
and (window['text'].casefold() in known_titles
|
||||
or frame is not None and window['hwnd'] == frame['hwnd'])):
|
||||
continue
|
||||
text = ' '.join([window['text'], *(child['text'] for child in window['children'])]).casefold()
|
||||
if not closing and ('select the desired product license' in text or window['text'] == 'Tip of the Day'):
|
||||
return True # The caller's PID-scoped DialogAgent owns startup choices.
|
||||
standard_save = (pcb_name and window['class'] == '#32770' and window['text'] == 'Expedition PCB'
|
||||
and any(child['class'].casefold() == 'static'
|
||||
and child['text'].strip().casefold() == f'Save changes to {pcb_name}?'.casefold()
|
||||
for child in window['children'])
|
||||
and {child.get('id') for child in window['children'] if child['class'].casefold() == 'button'} == {2, 6, 7})
|
||||
if closing and window.get('owner') == frame['hwnd'] and (standard_save or 'do you want to save the reusable block cell' in text):
|
||||
targets = [child for child in window['children'] if child['class'].casefold() == 'button'
|
||||
and child.get('id') == 7 and child['text'].replace('&', '').strip().casefold() in {'no', '否(n)', '否'}
|
||||
and child.get('enabled', True)]
|
||||
if len(targets) == 1:
|
||||
if window['hwnd'] not in clicked:
|
||||
session.post(targets[0]['hwnd'], 0xF5)
|
||||
clicked.add(window['hwnd'])
|
||||
continue
|
||||
raise RuntimeError('DIAGNOSTIC_CLOSE_UNCONFIRMED: unknown native prompt preserved; '
|
||||
f"pid={window['pid']} hwnd={window['hwnd']} class={window['class']!r} "
|
||||
f"title={window['text']!r}")
|
||||
return False
|
||||
|
||||
|
||||
def check_target_window(job, pcb_pid, *, emit, error_reader, launcher_process=None) -> dict:
|
||||
"""Prove this launch opened its native document, close it, and prove exit.
|
||||
|
||||
PASS describes opening only; it does not imply refresh READY or unoccupied
|
||||
shared library data. Unknown prompts are preserved for existing recovery.
|
||||
"""
|
||||
baseline = job.get('diagnostic_log_baseline')
|
||||
if not isinstance(baseline, dict) or 'started_ns' not in baseline or 'files' not in baseline:
|
||||
raise RuntimeError('DIAGNOSTIC_BASELINE_REQUIRED: snapshot before native launch')
|
||||
session = _NativeSession(job, int(pcb_pid), launcher_process)
|
||||
try:
|
||||
deadline = time.monotonic() + max(.01, float(job['timeout']))
|
||||
while True:
|
||||
_cancel(job)
|
||||
error = _read_bounded(error_reader) if error_reader else None
|
||||
if error:
|
||||
raise RuntimeError(str(error))
|
||||
if not session.pcb_alive():
|
||||
raise RuntimeError('DIAGNOSTIC_OPEN_UNCONFIRMED: target PCB exited before loaded evidence')
|
||||
windows = _windows(int(pcb_pid))
|
||||
if any(window['pid'] != int(pcb_pid) for window in windows):
|
||||
raise RuntimeError('DIAGNOSTIC_PID_MISMATCH')
|
||||
frame = _target_frame(windows, Path(job['pcb']).stem)
|
||||
# Startup splash/control windows are transient. Unknown windows
|
||||
# veto closing only once the target actually has loaded evidence.
|
||||
pending = (_pending_prompt(windows, frame=frame, pcb_name=Path(job['pcb']).name)
|
||||
if frame is not None else True)
|
||||
evidence = (_load_evidence(job, int(pcb_pid), baseline, require_autosave=False)
|
||||
if frame is not None and not pending else None)
|
||||
if evidence is not None:
|
||||
emit(stage='diagnostic_native_loaded_candidate', **evidence)
|
||||
break
|
||||
if time.monotonic() >= deadline:
|
||||
raise RuntimeError('DIAGNOSTIC_OPEN_UNCONFIRMED: current target MDI/path/PID logs missing')
|
||||
time.sleep(.1)
|
||||
# Re-read the exact PID/frame before the sole close request.
|
||||
_cancel(job)
|
||||
windows = _windows(int(pcb_pid))
|
||||
_pending_prompt(windows, frame=frame, pcb_name=Path(job['pcb']).name)
|
||||
current = _target_frame(windows, Path(job['pcb']).stem)
|
||||
if current is None or current['hwnd'] != frame['hwnd']:
|
||||
raise RuntimeError('DIAGNOSTIC_CLOSE_UNCONFIRMED: target frame changed')
|
||||
session.post(frame['hwnd'], 0x10)
|
||||
emit(stage='diagnostic_wm_close', pcb_pid=int(pcb_pid), hwnd=frame['hwnd'])
|
||||
close_deadline = time.monotonic() + 30
|
||||
clicked = set()
|
||||
last_pending = ''
|
||||
while session.pcb_alive() or session.launcher_alive():
|
||||
# Cancellation stops future work; an accepted normal close must
|
||||
# still finish before its queue slot can be safely released.
|
||||
windows = _windows(int(pcb_pid)) if session.pcb_alive() else []
|
||||
previous_clicks = set(clicked)
|
||||
pending_error = None
|
||||
try:
|
||||
_pending_prompt(windows, closing=True, frame=frame, session=session, clicked=clicked,
|
||||
pcb_name=Path(job['pcb']).name)
|
||||
except RuntimeError as error:
|
||||
if not str(error).startswith('DIAGNOSTIC_CLOSE_UNCONFIRMED: unknown native prompt'):
|
||||
raise
|
||||
# WM_CLOSE creates and destroys native windows asynchronously;
|
||||
# preserve them and wait for populated controls or process exit.
|
||||
pending_error = error
|
||||
if str(error) != last_pending:
|
||||
last_pending = str(error)
|
||||
emit(stage='diagnostic_close_pending', detail=last_pending)
|
||||
for hwnd in clicked - previous_clicks:
|
||||
emit(stage='diagnostic_save_no', pcb_pid=int(pcb_pid), hwnd=hwnd)
|
||||
if time.monotonic() >= close_deadline:
|
||||
if pending_error is not None:
|
||||
raise pending_error
|
||||
raise RuntimeError('DIAGNOSTIC_CLOSE_UNCONFIRMED: target PCB/launcher still running')
|
||||
time.sleep(.1)
|
||||
# EE7.9 buffers PCBAutoSave's complete Job Name until normal close.
|
||||
# The candidate permits closing only; PASS still needs that exact path.
|
||||
evidence = _load_evidence(job, int(pcb_pid), baseline)
|
||||
if evidence is None:
|
||||
raise RuntimeError('DIAGNOSTIC_OPEN_UNCONFIRMED: fresh full PCB path not confirmed after close')
|
||||
emit(stage='diagnostic_native_open_confirmed', **evidence)
|
||||
return {'status': 'PASS', 'check': 'native_open_only', 'native_processes_exited': True,
|
||||
'library_ownership': 'NOT_ASSESSED', 'pcb_pid': int(pcb_pid),
|
||||
'launcher_pid': getattr(launcher_process, 'pid', None), 'evidence': evidence,
|
||||
'detail': 'Native target opened and its PCB/launcher exited; refresh readiness and shared library ownership not assessed.'}
|
||||
finally:
|
||||
session.close()
|
||||
@@ -324,6 +324,7 @@ class DialogAgentServer:
|
||||
self.channel = JsonChannel(connection)
|
||||
self.channel.send({"token": paths.token}, timeout_seconds=10)
|
||||
self.observed_snapshots = {}
|
||||
self.observed_pids = None
|
||||
|
||||
@classmethod
|
||||
def from_config(cls, config_path: Path, *, probe, executor=None):
|
||||
@@ -348,7 +349,15 @@ class DialogAgentServer:
|
||||
try:
|
||||
phase = DialogPhase(request["phase"])
|
||||
if request.get("op") == "observe":
|
||||
snapshots = self.probe.capture(phase)
|
||||
pids = request.get('pids')
|
||||
if pids is not None and (not isinstance(pids, list)
|
||||
or any(type(pid) is not int or pid <= 0 for pid in pids)):
|
||||
raise ValueError('DIALOG_PID_SCOPE_INVALID')
|
||||
self.observed_pids = set(pids) if pids is not None else None
|
||||
snapshots = (self.probe.capture(phase, pids=self.observed_pids) if pids is not None
|
||||
else self.probe.capture(phase))
|
||||
if pids is not None:
|
||||
snapshots = tuple(w for w in snapshots if w.pid in self.observed_pids)
|
||||
self.observed_snapshots.clear()
|
||||
for snapshot in snapshots:
|
||||
self.observed_snapshots[stable_fingerprint(snapshot)] = snapshot
|
||||
@@ -356,7 +365,9 @@ class DialogAgentServer:
|
||||
return
|
||||
if request.get("op") == "perform":
|
||||
expected = self.observed_snapshots.get(request.get("fingerprint"))
|
||||
if expected is None:
|
||||
if (expected is None or int(request.get('hwnd', 0)) != expected.hwnd
|
||||
or self.observed_pids is not None and (expected.pid not in self.observed_pids
|
||||
or not self.probe.matches_identity(expected))):
|
||||
self._response(request, result=ActionResult(
|
||||
error_code="STALE_DIALOG",
|
||||
detail="窗口已消失或指纹已变化",
|
||||
@@ -422,27 +433,45 @@ class DialogAgentClient:
|
||||
raise
|
||||
|
||||
@classmethod
|
||||
def start(cls, worker, root: Path, *, timeout_seconds: float = 2.0):
|
||||
def start(cls, worker, root: Path, *, timeout_seconds: float = 2.0, stop=None):
|
||||
client = cls.prepare(root, desktop_name=worker.name, timeout_seconds=timeout_seconds)
|
||||
try:
|
||||
from .defaults import DIALOG_AGENT_STARTUP_TIMEOUT_SECONDS
|
||||
worker.start_companion(dialog_agent_command(client.paths.config))
|
||||
client._accept(timeout_seconds=10.0)
|
||||
# Frozen imports can exceed ten seconds; PCB remains behind its gate.
|
||||
client._accept(timeout_seconds=DIALOG_AGENT_STARTUP_TIMEOUT_SECONDS, stop=stop)
|
||||
return client
|
||||
except Exception:
|
||||
client.close()
|
||||
raise
|
||||
|
||||
def _accept(self, timeout_seconds):
|
||||
def _accept(self, timeout_seconds, *, stop=None):
|
||||
if self.channel is not None:
|
||||
return
|
||||
self.listener.settimeout(timeout_seconds)
|
||||
connection, _address = self.listener.accept()
|
||||
deadline = time.monotonic() + timeout_seconds
|
||||
while True:
|
||||
if stop is not None and stop.is_set():
|
||||
raise InterruptedError('VERIFY_CANCELLED: 弹窗代理启动已取消,未启动 PCB')
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
raise TimeoutError('dialog-agent startup timed out')
|
||||
self.listener.settimeout(min(.2, remaining))
|
||||
try:
|
||||
connection, _address = self.listener.accept()
|
||||
break
|
||||
except socket.timeout:
|
||||
continue
|
||||
channel = JsonChannel(connection)
|
||||
try:
|
||||
connection.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
|
||||
hello = channel.receive(timeout_seconds)
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
raise TimeoutError('dialog-agent handshake timed out')
|
||||
hello = channel.receive(min(self.timeout_seconds, remaining))
|
||||
if hello.get("token") != self.paths.token:
|
||||
raise DialogAgentProtocolError("dialog-agent authentication failed")
|
||||
if stop is not None and stop.is_set():
|
||||
raise InterruptedError('VERIFY_CANCELLED: 弹窗代理启动已取消,未启动 PCB')
|
||||
self.channel = channel
|
||||
except Exception:
|
||||
channel.close()
|
||||
@@ -473,8 +502,8 @@ class DialogAgentClient:
|
||||
raise DialogAgentProtocolError(f"{response['error_code']}: {response.get('detail', '')}")
|
||||
return response.get("result")
|
||||
|
||||
def observe(self, phase: DialogPhase) -> tuple[WindowSnapshot, ...]:
|
||||
result = self._request("observe", phase)
|
||||
def observe(self, phase: DialogPhase, *, pids=None) -> tuple[WindowSnapshot, ...]:
|
||||
result = self._request("observe", phase, **({'pids': sorted(pids)} if pids is not None else {}))
|
||||
return tuple(WindowSnapshot.from_record(item) for item in (result or ()))
|
||||
|
||||
def perform(self, *, hwnd: int, fingerprint: str, action: dict,
|
||||
|
||||
@@ -265,9 +265,23 @@ class WindowProbe:
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
def capture(self, phase: DialogPhase) -> tuple[WindowSnapshot, ...]:
|
||||
def matches_identity(self, snapshot):
|
||||
try:
|
||||
return (self.win32gui.IsWindowVisible(snapshot.hwnd)
|
||||
and self.win32process.GetWindowThreadProcessId(snapshot.hwnd)[1] == snapshot.pid
|
||||
and self.win32gui.GetClassName(snapshot.hwnd) == snapshot.window_class)
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
def capture(self, phase: DialogPhase, *, pids=None) -> tuple[WindowSnapshot, ...]:
|
||||
snapshots = []
|
||||
for hwnd in self._handles():
|
||||
if pids is not None:
|
||||
try:
|
||||
if self.win32process.GetWindowThreadProcessId(hwnd)[1] not in pids:
|
||||
continue
|
||||
except Exception:
|
||||
continue
|
||||
try:
|
||||
window_class = str(self.win32gui.GetClassName(hwnd) or "")
|
||||
except Exception:
|
||||
|
||||
@@ -100,11 +100,15 @@ class DialogBackend(Protocol):
|
||||
class AgentDialogBackend:
|
||||
"""Adapt the private-desktop JSONL client to the supervisor backend."""
|
||||
|
||||
def __init__(self, client) -> None:
|
||||
def __init__(self, client, *, pids=None) -> None:
|
||||
self.client = client
|
||||
self.pids = pids
|
||||
|
||||
def observe(self, phase: DialogPhase):
|
||||
return self.client.observe(phase)
|
||||
if self.pids is None:
|
||||
return self.client.observe(phase)
|
||||
pids = set(self.pids())
|
||||
return tuple(w for w in self.client.observe(phase, pids=pids) if w.pid in pids)
|
||||
|
||||
def perform(self, snapshot: WindowSnapshot, action: dict, phase: DialogPhase) -> ActionResult:
|
||||
return self.client.perform(
|
||||
|
||||
@@ -24,13 +24,42 @@ def _command_args(command):
|
||||
kernel.LocalFree(ctypes.cast(args, wintypes.HLOCAL))
|
||||
|
||||
|
||||
def _startup_snapshot(hwnd, pcb_pid):
|
||||
import win32gui, win32process
|
||||
from .dialog_models import ControlSnapshot, DialogPhase, WindowSnapshot
|
||||
if win32process.GetWindowThreadProcessId(hwnd)[1] != pcb_pid:
|
||||
raise ValueError('STARTUP_WINDOW_OWNER_CHANGED')
|
||||
children = []
|
||||
win32gui.EnumChildWindows(hwnd, lambda child, _: children.append(child), None)
|
||||
controls = tuple(ControlSnapshot(child, win32gui.GetDlgCtrlID(child) & 0xffff,
|
||||
win32gui.GetClassName(child), win32gui.GetWindowText(child),
|
||||
enabled=bool(win32gui.IsWindowEnabled(child))) for child in children)
|
||||
return WindowSnapshot(hwnd, pcb_pid, 'ExpeditionPCB.exe', 'pcb',
|
||||
win32gui.GetClassName(hwnd), win32gui.GetWindowText(hwnd), DialogPhase.PCB_STARTING, controls)
|
||||
|
||||
|
||||
def _cancel_target(snapshot):
|
||||
from .post_repair_consent import exact_prompt
|
||||
from .dialog_rules import pcb_version_choice
|
||||
if exact_prompt(snapshot):
|
||||
return 'read_write_access', next(c for c in snapshot.controls if c.control_id == 7)
|
||||
if pcb_version_choice(snapshot) is not None:
|
||||
buttons = [c for c in snapshot.controls if c.class_name == 'Button']
|
||||
cancel = [c for c in buttons if c.control_id == 2 and c.name == 'Cancel' and c.enabled]
|
||||
if (len(cancel) == 1 and {c.control_id for c in buttons} == {6212, 6213, 6206, 1, 2}
|
||||
and any(c.control_id == 6211 and c.name == '* Cancelling will load no design.'
|
||||
for c in snapshot.controls)):
|
||||
return 'pcb_version_choice', cancel[0]
|
||||
return None
|
||||
|
||||
|
||||
def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event: None,
|
||||
timeout_seconds=20, launcher_process=None):
|
||||
"""Normally close our empty PCB after a diagnosed database startup failure.
|
||||
|
||||
No COM attach: there is no document, and the global ROT can name another
|
||||
session. Unknown windows, live database addresses and other desktops are
|
||||
retained. WM_CLOSE is cooperative; no save prompt is accepted or killed.
|
||||
No COM attach: the global ROT can name another session. Only the exact
|
||||
read/write question is declined; no ownership is taken or version restored.
|
||||
Unknown windows and documents are retained. WM_CLOSE is cooperative.
|
||||
"""
|
||||
import win32api, win32con, win32gui, win32process
|
||||
from .mentor_adapter import _process_details
|
||||
@@ -43,23 +72,6 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
|
||||
if launcher_process is not None:
|
||||
result['launcher_pid'] = launcher_process.pid
|
||||
try:
|
||||
diagnosed = False
|
||||
diagnosis_path = root/'diagnostics/icdb-recovery.json'
|
||||
if diagnosis_path.is_file():
|
||||
diagnosis = json.loads(diagnosis_path.read_text('utf-8'))
|
||||
diagnosed = diagnosis.get('error_code') == 'ICDB_REPAIR_REQUIRED'
|
||||
dialogs_path = root/'dialogs.jsonl'
|
||||
if not diagnosed and dialogs_path.is_file():
|
||||
for line in dialogs_path.read_text('utf-8').splitlines():
|
||||
try:
|
||||
dialog = json.loads(line)
|
||||
except ValueError:
|
||||
continue
|
||||
if (dialog.get('pid') == pcb_pid and dialog.get('phase') == 'PCB_STARTING'
|
||||
and dialog.get('error_code') == 'MENTOR_DATABASE_LOAD_FAILED'):
|
||||
diagnosed = True
|
||||
if not diagnosed:
|
||||
raise ValueError('STARTUP_FAILURE_UNCONFIRMED')
|
||||
desktop = job.get('desktop', '')
|
||||
if (job.get('interactive_input') or not desktop.startswith('CbbVerify_')
|
||||
or _current_desktop_name() != desktop):
|
||||
@@ -69,14 +81,20 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
|
||||
expected = os.path.normcase(os.path.abspath(job['pcb']))
|
||||
deadline = time.monotonic() + max(0, timeout_seconds)
|
||||
sent = False
|
||||
declined_hwnd = None
|
||||
declined_kind = None
|
||||
cancelled_open = False
|
||||
while True:
|
||||
records = [r for r in _process_details('ExpeditionPCB.exe') if r[0] == pcb_pid]
|
||||
if not records:
|
||||
if declined_hwnd is not None:
|
||||
cancelled_open = True
|
||||
result['cancelled_prompt'] = declined_kind
|
||||
addresses = unreleased_addresses(job['lmc_file'], job['project'], job['pcb'])
|
||||
launcher_exited = launcher_process is None or launcher_process.poll() is not None
|
||||
result['release'] = {'pcb_exited': True, 'launcher_exited': launcher_exited,
|
||||
'addresses': addresses,
|
||||
'safe_to_continue': launcher_exited and not addresses}
|
||||
'safe_to_continue': launcher_exited and (cancelled_open or not addresses)}
|
||||
if result['release']['safe_to_continue']:
|
||||
result['status'] = 'CLOSED'
|
||||
result.pop('detail', None)
|
||||
@@ -100,6 +118,29 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
|
||||
windows.append(hwnd)
|
||||
win32api.SetLastError(0)
|
||||
win32gui.EnumWindows(observe, None)
|
||||
if declined_hwnd is not None and declined_hwnd not in windows:
|
||||
cancelled_open = True
|
||||
result['cancelled_prompt'] = declined_kind
|
||||
if declined_hwnd is None:
|
||||
for hwnd in windows:
|
||||
if win32gui.GetClassName(hwnd) != '#32770':
|
||||
continue
|
||||
snapshot = _startup_snapshot(hwnd, pcb_pid)
|
||||
target = _cancel_target(snapshot)
|
||||
if target is None:
|
||||
continue
|
||||
# Re-read immediately before declining; never select a version.
|
||||
current = _startup_snapshot(hwnd, pcb_pid)
|
||||
if _cancel_target(current) != target or current != snapshot:
|
||||
raise ValueError('STARTUP_CANCEL_PROMPT_CHANGED')
|
||||
declined_kind, cancel = target
|
||||
win32gui.PostMessage(cancel.handle, win32con.BM_CLICK, 0, 0)
|
||||
declined_hwnd = hwnd
|
||||
emit(stage='startup_open_declined', pcb_pid=pcb_pid, hwnd=hwnd,
|
||||
control_id=cancel.control_id, prompt=declined_kind)
|
||||
break
|
||||
if declined_hwnd is not None:
|
||||
continue
|
||||
main = [w for w in windows if win32gui.GetClassName(w).startswith('Afx:')
|
||||
and win32gui.GetWindowText(w).strip() in (
|
||||
'Expedition PCB', 'Expedition PCB - Reusable Block')
|
||||
@@ -131,7 +172,7 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
|
||||
win32api.SetLastError(0)
|
||||
win32gui.EnumChildWindows(main[0], child, None)
|
||||
addresses = unreleased_addresses(job['lmc_file'], job['project'], job['pcb'])
|
||||
if len(main) == 1 and not unknown and not documents and not addresses:
|
||||
if len(main) == 1 and not unknown and not documents and (cancelled_open or not addresses):
|
||||
win32gui.PostMessage(main[0], win32con.WM_CLOSE, 0, 0)
|
||||
sent = True
|
||||
emit(stage='startup_close_requested', pcb_pid=pcb_pid, hwnd=main[0])
|
||||
|
||||
@@ -17,6 +17,37 @@ _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)
|
||||
|
||||
_ICDB_MESSAGE = re.compile(r'(?<![A-Za-z0-9_])icdb(?![A-Za-z0-9_.\\/])', re.I)
|
||||
_FAILURE_MESSAGE = re.compile(
|
||||
r'\b(?:error|failed|failure|unable|cannot|could\s+not|lost|corrupt(?:ed|ion)?|'
|
||||
r'inconsistent|unsupported|refused|denied)\b|失败|错误|异常|无法|损坏|失联|拒绝|未完成', re.I)
|
||||
|
||||
|
||||
def _icdb_error_paragraphs(text, *, error_message=False):
|
||||
text = str(text or '').replace('\r', '')
|
||||
for record in _session_losses(text):
|
||||
yield record['native_message'].strip()
|
||||
for paragraph in text.splitlines():
|
||||
# A pathname or our own category label is not native error content.
|
||||
message = re.sub(r'\[[^\]\n]*[\\/][^\]\n]*\]', '', paragraph)
|
||||
if _ICDB_MESSAGE.search(message) and (error_message or _FAILURE_MESSAGE.search(message)):
|
||||
yield paragraph.strip()
|
||||
|
||||
|
||||
def icdb_error_content(text, *, error_message=False):
|
||||
"""Extract failure paragraphs mentioning iCDB; codes/healthy text do not qualify."""
|
||||
return '\n\n'.join(dict.fromkeys(_icdb_error_paragraphs(text, error_message=error_message)))
|
||||
|
||||
|
||||
def read_icdb_error(path, baseline):
|
||||
"""Retain only new native error content, with the same bounded freshness rules."""
|
||||
data, appended = _read_log_delta(path, baseline)
|
||||
if not appended and (not baseline or baseline.get('truncated') or 'icdb_errors' not in baseline):
|
||||
return ''
|
||||
previous = baseline.get('icdb_errors', [])
|
||||
return '\n\n'.join(message for message in _icdb_error_paragraphs(decode_log(data))
|
||||
if appended or ' '.join(message.split()) not in previous)
|
||||
|
||||
|
||||
def parse_session_loss(text):
|
||||
"""Keep the native target verbatim; never infer a local repair target."""
|
||||
@@ -68,9 +99,10 @@ def snapshot_log(path):
|
||||
losses = [_session_identity(record) for record in _session_losses(decode_log(tail))]
|
||||
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}
|
||||
except FileNotFoundError:
|
||||
return {'size': 0, 'tail_sha256': hashlib.sha256(b'').hexdigest()}
|
||||
return {'size': 0, 'tail_sha256': hashlib.sha256(b'').hexdigest(), 'icdb_errors': []}
|
||||
except OSError as error:
|
||||
return {'error': str(error)}
|
||||
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -15,12 +15,29 @@ from uuid import uuid4
|
||||
|
||||
def assert_native_idle(target=None):
|
||||
from .owner_probe import query_owners
|
||||
from .failed_session import _command_args
|
||||
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):
|
||||
from .library_lock import _key, _owner_matches_scope
|
||||
library = 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.
|
||||
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):
|
||||
raise ValueError('MAINTENANCE_OWNER_ACTIVE: 管理工作进程尚未返回')
|
||||
names = ('ExpeditionPCB.exe', 'LibraryManager.exe', 'viewdraw.exe', 'iCDBProjectBackup.exe',
|
||||
'ReuseBlockImporter.exe', 'CleanWGLib.exe', 'cscript.exe', 'wscript.exe',
|
||||
@@ -32,18 +49,10 @@ def assert_native_idle(target=None):
|
||||
name, command = item['name'].casefold(), item['command'].casefold()
|
||||
automation = name in ('python.exe', 'pythonw.exe', 'cbbrefreshverify.exe')
|
||||
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 target is not None:
|
||||
expected = os.path.normcase(os.path.abspath(str(target.project)))
|
||||
scoped = []
|
||||
for item in owners:
|
||||
command = str(item.get('command') or '')
|
||||
if not command:
|
||||
scoped.append(item)
|
||||
elif expected in [os.path.normcase(os.path.abspath(arg)) for arg in _command_args(command)[1:]]:
|
||||
scoped.append(item)
|
||||
owners = scoped
|
||||
owners = [item for item in owners if _owner_matches_scope(item, library, roots) is not False]
|
||||
if owners:
|
||||
raise ValueError(f'MAINTENANCE_OWNER_ACTIVE: 请正常关闭原生程序/操作助手:{owners}')
|
||||
|
||||
@@ -215,13 +224,9 @@ def maintenance_target_guard(request, expected=None, *, stop=None):
|
||||
|
||||
|
||||
def run_icdb_check(request, *, progress=None, stop=None):
|
||||
"""Inspect through Project Backup; never launch PCB, Repair or Restore."""
|
||||
from .verify_runner import VerifyResult
|
||||
from .library_lock import LibraryLock, LibraryBusy
|
||||
from .native_repair import run_native_repair, RepairTarget
|
||||
from .native_backup import native_backup_project
|
||||
from .backup_recovery import _project_text
|
||||
from .native_occupancy import confirmed_inspection
|
||||
"""Open PCB diagnostically and classify this attempt's native error content."""
|
||||
from .verify_runner import VerifyResult, run_verify
|
||||
from .icdb_recovery import icdb_error_content
|
||||
root = Path(request.evidence_dir).resolve()/('icdb-check-'+uuid4().hex[:12])
|
||||
library_root = Path(request.lmc_file).resolve().parent
|
||||
if root.is_relative_to(library_root) or library_root.is_relative_to(root):
|
||||
@@ -229,10 +234,7 @@ def run_icdb_check(request, *, progress=None, stop=None):
|
||||
stderr='检查记录目录需位于中心库之外。')
|
||||
record = {'operation': 'icdb_batch_check', 'automatic_repair': False,
|
||||
'library': str(request.lmc_file), 'block': request.block_name}
|
||||
released = True
|
||||
def check():
|
||||
if stop is not None and stop.is_set():
|
||||
raise InterruptedError('已取消检查。')
|
||||
started = False
|
||||
def save(result):
|
||||
report = root/'result.json'
|
||||
recorded = replace(result, evidence_path=report)
|
||||
@@ -245,51 +247,46 @@ def run_icdb_check(request, *, progress=None, stop=None):
|
||||
return result
|
||||
return recorded
|
||||
try:
|
||||
check()
|
||||
root.mkdir(parents=True, exist_ok=False)
|
||||
with LibraryLock(request.lmc_file, checkpoint=False, safe_to_release=lambda: released):
|
||||
project = native_backup_project(request.lmc_file, request.block_name)
|
||||
values = re.findall(r'^KEY iCDBDir "([^"\r\n]*)"', _project_text(project), re.M)
|
||||
if (len(values) != 1 or not values[0] or PureWindowsPath(values[0]).drive
|
||||
or PureWindowsPath(values[0]).root
|
||||
or (project.parent/values[0]).resolve() != (project.parent/'database').resolve()):
|
||||
raise ValueError('无法确认工程的 ICDB 数据库路径。')
|
||||
target = RepairTarget(project, project.parent/'database')
|
||||
record['target'] = asdict(target)
|
||||
check()
|
||||
if progress:
|
||||
progress({'stage': 'icdb_ownership_check', 'block': request.block_name,
|
||||
'detail': '正在检查 ICDB 状态'})
|
||||
released = False
|
||||
inspection = run_native_repair(target, root/'native-inspection',
|
||||
mentor_bin=request.mentor_bin, timeout_seconds=min(30, request.timeout_seconds),
|
||||
progress=progress, inspection_only=True, stop=stop)
|
||||
record['native_inspection'] = inspection
|
||||
released = (inspection.get('release', {}).get('native_exited') is True
|
||||
or inspection.get('native_started') is False
|
||||
and inspection.get('native_pid') is None and inspection.get('worker_pid') is None)
|
||||
if ((stop is not None and stop.is_set())
|
||||
or inspection.get('status') in ('CANCELLED', 'CANCELLED_UNRELEASED')):
|
||||
return save(VerifyResult('CANCELLED', safe_to_continue=released, stderr='已取消 ICDB 检查。'))
|
||||
if not confirmed_inspection(target, inspection):
|
||||
return save(VerifyResult('FAIL', safe_to_continue=released,
|
||||
error_category='ICDB_INSPECTION_UNCONFIRMED',
|
||||
stderr='无法确认 ICDB 状态。' + str(inspection.get('detail', ''))))
|
||||
if inspection['status'] == 'IN_USE':
|
||||
return save(VerifyResult('BLOCKED', safe_to_continue=released,
|
||||
error_category='ICDB_DATABASE_IN_USE', stderr='工程正在使用,暂未完成 ICDB 检查。'))
|
||||
if inspection['repair_required']:
|
||||
return save(VerifyResult('FAIL', safe_to_continue=released,
|
||||
error_category='ICDB_REPAIR_REQUIRED', stderr='发现 ICDB 问题,未执行修复。'))
|
||||
return save(VerifyResult('CHECKED', safe_to_continue=released,
|
||||
stdout='ICDB 检查未发现异常,无需修复。'))
|
||||
except InterruptedError:
|
||||
return save(VerifyResult('CANCELLED', safe_to_continue=released, stderr='已取消 ICDB 检查。'))
|
||||
except LibraryBusy as error:
|
||||
return save(VerifyResult('BLOCKED', safe_to_continue=False,
|
||||
error_category='LIBRARY_IN_USE', stderr=str(error)))
|
||||
if stop is not None and stop.is_set():
|
||||
return save(VerifyResult('CANCELLED', stderr='已取消 ICDB 检查。'))
|
||||
if progress:
|
||||
progress({'stage': 'icdb_startup_check', 'block': request.block_name,
|
||||
'detail': '正在打开工程并检查本次错误信息'})
|
||||
started = True
|
||||
startup = run_verify(replace(request, maintenance=False, auto_repair=False,
|
||||
diagnostic_only=True, native_lm_verify=False, post_repair_proof=None,
|
||||
evidence_dir=root/'pcb-open'), progress=progress, stop=stop)
|
||||
record['native_open'] = asdict(startup)
|
||||
if startup.status == 'CANCELLED' or stop is not None and stop.is_set():
|
||||
return save(replace(startup, status='CANCELLED', recovery_attempts=()))
|
||||
if startup.status == 'PASS' and startup.safe_to_continue:
|
||||
return save(replace(startup, status='CHECKED', library_flag='UNKNOWN',
|
||||
stdout='工程打开正常,未发现 ICDB 错误;未执行 CBB 校验。', recovery_attempts=()))
|
||||
content = icdb_error_content(startup.stderr, error_message=True)
|
||||
if (startup.evidence_path
|
||||
and startup.evidence_path.resolve().is_relative_to(root/'pcb-open')):
|
||||
try:
|
||||
saved = json.loads(startup.evidence_path.with_name('diagnostics').joinpath(
|
||||
'icdb-error-content.json').read_text('utf-8'))
|
||||
native = icdb_error_content(saved.get('native_message', ''))
|
||||
if native:
|
||||
content = '\n'.join(dict.fromkeys(filter(None, (content, native))))
|
||||
record['native_error'] = saved
|
||||
except (OSError, ValueError, AttributeError):
|
||||
pass
|
||||
if content:
|
||||
return save(replace(startup, status='FAIL', library_flag='UNKNOWN',
|
||||
error_category='ICDB_REPAIR_REQUIRED',
|
||||
stderr='发现 ICDB 错误,未执行修复。\n'+content, recovery_attempts=()))
|
||||
category = startup.error_category
|
||||
if not category or category.startswith('ICDB_'):
|
||||
category = 'ICDB_INSPECTION_UNCONFIRMED'
|
||||
return save(replace(startup, status='FAIL' if startup.status=='PASS' else startup.status,
|
||||
error_category=category, library_flag='UNKNOWN', recovery_attempts=(),
|
||||
stderr=startup.stderr or '工程打开或释放未完成,尚无法确认 ICDB 状态。'))
|
||||
except Exception as error:
|
||||
return save(VerifyResult('FAIL', safe_to_continue=released,
|
||||
return save(VerifyResult('FAIL', safe_to_continue=not started,
|
||||
error_category='ICDB_INSPECTION_UNCONFIRMED', stderr=f'无法确认 ICDB 状态:{error}'))
|
||||
|
||||
|
||||
|
||||
@@ -31,6 +31,7 @@ class ManagementRequest:
|
||||
mapped_drive: str = ''
|
||||
mapped_remote_root: str = ''
|
||||
transaction_token: str = ''
|
||||
check_previous_release: bool = False
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -71,6 +72,7 @@ class ManagementResult:
|
||||
safe_to_continue: bool
|
||||
detail: str = ''
|
||||
evidence_path: Path | None = None
|
||||
release_proof: dict | None = None
|
||||
|
||||
|
||||
def validate_name(value):
|
||||
@@ -150,13 +152,22 @@ def unfinished_operations(root):
|
||||
for path in sorted(Path(root).glob('*/checkpoint.json')):
|
||||
try:
|
||||
record = json.loads(path.read_text(encoding='utf-8'))
|
||||
if record.get('stage') != 'complete' or record.get('safe_to_continue') is False:
|
||||
if (record.get('stage') != 'complete' or record.get('safe_to_continue') is False
|
||||
or record.get('status') == 'RECOVERY_REQUIRED'):
|
||||
results.append({**record, 'evidence_path': str(path)})
|
||||
except (OSError, ValueError):
|
||||
results.append({'status': 'CHECKPOINT_UNREADABLE', 'evidence_path': str(path)})
|
||||
return results
|
||||
|
||||
|
||||
def _may_have_mutated(record):
|
||||
prewrite = {'preflight', 'release_check', 'catalog_before', 'baseline', 'stage_source', 'prepare_identity'}
|
||||
history = record.get('history')
|
||||
return (record.get('stage') not in prewrite | {'complete'} or record.get('status') == 'RECOVERY_REQUIRED'
|
||||
or not isinstance(history, list) or not history
|
||||
or any(not isinstance(item, dict) or item.get('stage') not in prewrite for item in history))
|
||||
|
||||
|
||||
def run_management(request, *, adapter=None, verifier=None, idle_check=None, progress=None):
|
||||
from .verify_runner import VerifyRequest, run_verify
|
||||
from .backup_recovery import _idle_check
|
||||
@@ -174,6 +185,17 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
|
||||
owner_safe = True
|
||||
mutex = None
|
||||
acquired = False
|
||||
release_proof = None
|
||||
def invoke(callback, *args):
|
||||
nonlocal owner_safe
|
||||
owner_safe = False
|
||||
try:
|
||||
result = callback(*args)
|
||||
except Exception as error:
|
||||
owner_safe = getattr(error, 'safe_to_continue', False) is True
|
||||
raise
|
||||
owner_safe = result.safe_to_continue
|
||||
return result
|
||||
def checkpoint(next_stage, **details):
|
||||
nonlocal stage
|
||||
stage = next_stage
|
||||
@@ -185,9 +207,12 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
|
||||
progress({'stage': stage, 'block': request.name, 'operation': request.operation, **details})
|
||||
def finish(status, detail='', safe=True):
|
||||
result = ManagementResult(request.operation, request.library, request.name, request.partition,
|
||||
request.source, request.auto_verify, 'complete', status, safe, detail, report)
|
||||
request.source, request.auto_verify, 'complete', status, safe, detail, report, release_proof)
|
||||
if report:
|
||||
_write_json(report, {**asdict(result), 'history': history, 'backup_policy': 'manual'})
|
||||
try:
|
||||
_write_json(report, {**asdict(result), 'history': history, 'backup_policy': 'manual'})
|
||||
except OSError as error:
|
||||
result = replace(result, detail=f'{detail}\n操作记录写入失败:{error}'.strip())
|
||||
return result
|
||||
from .com_runtime import initialize_com, uninitialize_com
|
||||
initialized = initialize_com()
|
||||
@@ -207,9 +232,13 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
|
||||
capability = adapter.capabilities().get(request.operation, Capability(False, '未验证的原生接口'))
|
||||
if not capability.supported:
|
||||
return finish('UNSUPPORTED', capability.reason)
|
||||
unfinished_target = None
|
||||
for unfinished in unfinished_operations(evidence):
|
||||
if unfinished.get('library') and Path(unfinished['library']).resolve() == canonical_library:
|
||||
return finish('BLOCKED', f'存在未完成/需恢复任务,禁止自动重放:{unfinished["evidence_path"]}', False)
|
||||
if (unfinished.get('library') and Path(unfinished['library']).resolve() == canonical_library
|
||||
and _may_have_mutated(unfinished) and (not unfinished.get('name')
|
||||
or str(unfinished['name']).casefold() == request.name.casefold())):
|
||||
unfinished_target = unfinished
|
||||
break
|
||||
source = pcb = None
|
||||
if request.operation in ('add', 'update'):
|
||||
if request.source is None:
|
||||
@@ -219,16 +248,24 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
|
||||
or evidence.is_relative_to(source.parent)
|
||||
or source.parent.is_relative_to(evidence)):
|
||||
raise ValueError('来源工程、目标库与操作证据必须使用独立目录。')
|
||||
root = evidence/('management-' + uuid4().hex)
|
||||
root.mkdir(parents=True, exist_ok=False)
|
||||
report = root/'checkpoint.json'
|
||||
checkpoint('release_check')
|
||||
mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795')
|
||||
acquired = win32event.WaitForSingleObject(mutex, 0) in (win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED)
|
||||
if not acquired:
|
||||
return finish('BLOCKED', '已有 CBB 校验/管理/恢复任务运行。', False)
|
||||
return finish('BLOCKED', '已有 CBB 校验/管理/恢复任务运行;本次未启动。')
|
||||
from .library_lock import has_blocker, has_retained_library, release_retained_library
|
||||
if (has_blocker(library) or has_retained_library(library) or request.check_previous_release
|
||||
or unfinished_target and unfinished_target.get('safe_to_continue') is not True):
|
||||
release_proof = release_retained_library(library, root/'previous-release')
|
||||
if unfinished_target:
|
||||
return finish('BLOCKED', f'存在未完成/需恢复任务,禁止自动重放:{unfinished_target["evidence_path"]}')
|
||||
if hasattr(adapter, 'bind_library_mapping'):
|
||||
adapter.bind_library_mapping(request.mapped_drive, request.mapped_remote_root)
|
||||
with LibraryLock(library, safe_to_release=lambda: owner_safe):
|
||||
root = evidence/('management-' + uuid4().hex)
|
||||
root.mkdir(parents=True, exist_ok=False)
|
||||
report = root/'checkpoint.json'
|
||||
with LibraryLock(library, block_name=request.name, safe_to_release=lambda: owner_safe or (
|
||||
callable(getattr(adapter, 'release_confirmed', None)) and adapter.release_confirmed(library))):
|
||||
work = library.parent/'ReusableBlocksLP'/request.name/'Work'
|
||||
target_project, target_pcb = work/(request.name+'.prj'), work/'PCB/pcb.pcb'
|
||||
if request.operation != 'add':
|
||||
@@ -244,7 +281,7 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
|
||||
idle_check(library, source, pcb)
|
||||
checkpoint('catalog_before')
|
||||
owner_safe = False
|
||||
before = adapter.catalog(library, root/'before')
|
||||
before = invoke(adapter.catalog, library, root/'before')
|
||||
owner_safe = before.safe_to_continue
|
||||
if not owner_safe or Path(before.library).resolve() != canonical_library or before.flow != 1:
|
||||
return finish('BLOCKED', '原生目录身份/流程或所有者释放未确认。仅支持已验证 DxDesigner 流程。', owner_safe)
|
||||
@@ -285,32 +322,29 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
|
||||
if request.operation in ('remove', 'update'):
|
||||
checkpoint('native_remove')
|
||||
mutated = True; owner_safe = False
|
||||
native = adapter.remove(request, root/'remove')
|
||||
native = invoke(adapter.remove, request, root/'remove')
|
||||
owner_safe = native.safe_to_continue
|
||||
if not owner_safe or not native.success:
|
||||
return finish('RECOVERY_REQUIRED', native.detail, False)
|
||||
owner_safe = False
|
||||
return finish('RECOVERY_REQUIRED', native.detail, owner_safe)
|
||||
idle_check(library, target_project, target_pcb)
|
||||
owner_safe = False
|
||||
after = adapter.catalog(library, root/'after-remove')
|
||||
after = invoke(adapter.catalog, library, root/'after-remove')
|
||||
owner_safe = after.safe_to_continue
|
||||
if (not owner_safe or Path(after.library).resolve() != canonical_library or after.flow != 1
|
||||
or any(e.name == request.name and e.partition == request.partition for e in after.entries)):
|
||||
return finish('RECOVERY_REQUIRED', '原生移除后目录未确认目标缺失。', False)
|
||||
return finish('RECOVERY_REQUIRED', '原生移除后目录未确认目标缺失。', owner_safe)
|
||||
removed = True
|
||||
checkpoint('removed')
|
||||
if request.operation == 'remove':
|
||||
return finish('REMOVED', '已由原生操作移除,重新读取目录确认不存在;应用未创建备份。')
|
||||
checkpoint('native_add')
|
||||
mutated = True; owner_safe = False
|
||||
native = adapter.add(staged, root/'add')
|
||||
native = invoke(adapter.add, staged, root/'add')
|
||||
owner_safe = native.safe_to_continue
|
||||
if not owner_safe or not native.success:
|
||||
return finish('RECOVERY_REQUIRED' if removed or not owner_safe else 'UPLOAD_FAILED',
|
||||
native.detail, owner_safe and not removed)
|
||||
owner_safe = False
|
||||
native.detail, owner_safe)
|
||||
idle_check(library, target_project, target_pcb)
|
||||
after = adapter.catalog(library, root/'after-add')
|
||||
after = invoke(adapter.catalog, library, root/'after-add')
|
||||
owner_safe = after.safe_to_continue
|
||||
matches = [entry for entry in after.entries if entry.name == request.name
|
||||
and entry.partition == request.partition]
|
||||
@@ -319,7 +353,7 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
|
||||
len(matches) == 1 and matches[0].engineering_identity == identity)
|
||||
if (not owner_safe or Path(after.library).resolve() != canonical_library or after.flow != 1
|
||||
or len(matches) != 1 or not proof_matches):
|
||||
return finish('RECOVERY_REQUIRED', '原生新增后名称、分区或来源工程内容未确认一致。', False)
|
||||
return finish('RECOVERY_REQUIRED', '原生新增后名称、分区或来源工程内容未确认一致。', owner_safe)
|
||||
uploaded = True
|
||||
checkpoint('uploaded')
|
||||
if not request.auto_verify:
|
||||
@@ -336,12 +370,14 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
|
||||
verified.stderr or verified.library_flag_detail, owner_safe)
|
||||
except Exception as error:
|
||||
if uploaded:
|
||||
return finish('UPLOADED_VERIFY_FAILED', str(error), False)
|
||||
return finish('UPLOADED_VERIFY_FAILED', str(error), owner_safe)
|
||||
status = 'RECOVERY_REQUIRED' if mutated else ('UPLOAD_FAILED' if request.operation in ('add', 'update') else 'BLOCKED')
|
||||
# Bad input is never described as a native upload attempt.
|
||||
if root is None and isinstance(error, ValueError):
|
||||
status = 'BLOCKED'
|
||||
return finish(status, str(error), not mutated and owner_safe and not isinstance(error, LibraryBusy))
|
||||
if stage == 'release_check' and not mutated:
|
||||
status = 'BLOCKED'
|
||||
return finish(status, str(error), owner_safe)
|
||||
finally:
|
||||
if mutex is not None:
|
||||
if acquired:
|
||||
|
||||
@@ -236,12 +236,13 @@ def pcb_processes():
|
||||
|
||||
def is_reusable_circuit_pcb(exe, command, expected_pcb):
|
||||
"""Match the ReusableCircuit session for this CBB by argument, not install layout."""
|
||||
from .failed_session import _command_args
|
||||
exe = os.path.normcase(str(exe or ''))
|
||||
command = os.path.normcase(str(command or ''))
|
||||
args = _command_args(str(command or ''))
|
||||
expected = os.path.normcase(os.path.abspath(str(expected_pcb)))
|
||||
return (os.path.basename(exe) == 'expeditionpcb.exe'
|
||||
and '-reusablecircuit' in command
|
||||
and expected in command)
|
||||
and '-reusablecircuit' in {arg.casefold() for arg in args[1:]}
|
||||
and expected in {os.path.normcase(os.path.abspath(arg)) for arg in args[1:]})
|
||||
|
||||
|
||||
def select_reusable_circuit_pcb(candidates):
|
||||
@@ -636,7 +637,7 @@ def execute_job(job, emit):
|
||||
pcb_log_offset = snapshot_log(pcb_log)
|
||||
integration_log_dir = Path(job['pcb']).parent / 'LogFiles'
|
||||
integration_offsets = {}
|
||||
for name in ('ForwardAnnotation.txt', 'MsgBoxResponse.log', 'PartPkg.log'):
|
||||
for name in (() if job.get('diagnostic_only') else ('ForwardAnnotation.txt', 'MsgBoxResponse.log', 'PartPkg.log')):
|
||||
path = integration_log_dir / name
|
||||
try:
|
||||
baseline = path.read_bytes()
|
||||
@@ -663,6 +664,8 @@ def execute_job(job, emit):
|
||||
# Inspect every source before returning a generic server/packager
|
||||
# failure: either can be a consequence of a lost library session.
|
||||
startup = pcb_log_reports_missing_server(job['pcb'], offset=pcb_log_offset)
|
||||
if job.get('diagnostic_only'):
|
||||
return startup
|
||||
integration = pcb_log_reports_integration_error(job['pcb'], offsets=integration_offsets)
|
||||
if 'ICDB_REPAIR_REQUIRED' in startup:
|
||||
return startup
|
||||
@@ -692,6 +695,8 @@ def execute_job(job, emit):
|
||||
reference = match[2]
|
||||
if not reference or (config.parent/reference).resolve() != library:
|
||||
raise ValueError(f'DIAGNOSTIC_LIBRARY_MISMATCH: {config}: {reference}')
|
||||
from .diagnostic_open import snapshot_diagnostic_logs
|
||||
job['diagnostic_log_baseline'] = snapshot_diagnostic_logs(job)
|
||||
else:
|
||||
ensure_pcb_central_library(
|
||||
job['pcb'],
|
||||
@@ -708,6 +713,7 @@ def execute_job(job, emit):
|
||||
# The successful background runs use the normal ReusableCircuit
|
||||
# launcher. Keep the experimental Library Manager menu route opt-in
|
||||
# for diagnostics only; it is not the production trigger on EE7.9.
|
||||
pcb_started_ns = time.time_ns()
|
||||
if bool(job.get('native_lm_verify', False)):
|
||||
from .library_manager_verify import launch_library_verify
|
||||
emit(stage='lm_launch', library=job['lmc_file'], block=job['block_name'])
|
||||
@@ -749,46 +755,51 @@ def execute_job(job, emit):
|
||||
parent_pid=worker_parent_pid or lm_pid, command=worker_command,
|
||||
binding='commandline' if is_reusable_circuit_pcb(
|
||||
worker_executable, worker_command, job['pcb']) else 'launcher_child')
|
||||
try:
|
||||
from .mentor_paths import discover_sdd_home
|
||||
home = discover_sdd_home(job.get('mentor_bin'))
|
||||
wdir = os.environ.get('WDIR', '').split(';')[0].strip()
|
||||
if wdir or home:
|
||||
log_root = Path(os.path.expandvars(wdir)) if wdir else home/'standard'
|
||||
(root/'diagnostics/native-client-context.json').write_text(json.dumps({
|
||||
'native_pid': worker_pid, 'started_ns': pcb_started_ns,
|
||||
'client_log_root': str(log_root/'iCDB/Client/Logs'),
|
||||
'database': str(Path(job['project']).parent/'database')},
|
||||
ensure_ascii=False), encoding='utf-8')
|
||||
except (OSError, ValueError):
|
||||
pass
|
||||
break
|
||||
time.sleep(.2)
|
||||
if worker_pid is None:
|
||||
raise RuntimeError('ReusableCircuit common 启动后未观察到 wg PCB 子进程')
|
||||
app, doc, pi = wait_for_target_document(
|
||||
job,
|
||||
lambda: win32com.client.GetActiveObject('MGCPCB.Application'),
|
||||
process_alive=lambda: any(candidate_pid in {lm_pid, worker_pid, worker_parent_pid}
|
||||
for candidate_pid, _, _ in pcb_processes()),
|
||||
emit=emit,
|
||||
error_reader=native_error,
|
||||
)
|
||||
identity_verified = True
|
||||
if job.get('diagnostic_only'):
|
||||
# The diagnostic opens only to establish current native evidence.
|
||||
# Do not refresh integration, save/commit Cert, or edit PRJ paths.
|
||||
if detail := native_error():
|
||||
raise RuntimeError(detail)
|
||||
pi = doc = app = None
|
||||
gc.collect()
|
||||
from .failed_session import close_failed_document
|
||||
diagnostic_close_attempted = True
|
||||
closed = close_failed_document(job, emit=emit)
|
||||
if closed.get('status') != 'CLOSED':
|
||||
raise RuntimeError(f'DIAGNOSTIC_CLOSE_UNCONFIRMED: {closed}')
|
||||
release_deadline = time.monotonic() + 30
|
||||
while True:
|
||||
released = cleanup_verify_processes(lm_pid, worker_pid, worker_parent_pid,
|
||||
expected_pcb=job['pcb'], baseline_pids=pcb_before, emit=emit)
|
||||
if (released and released.get('safe_to_continue')
|
||||
and not unreleased_addresses(job['lmc_file'], job['project'], job['pcb'])):
|
||||
break
|
||||
if time.monotonic() >= release_deadline:
|
||||
raise RuntimeError('DIAGNOSTIC_CLOSE_UNCONFIRMED: 原生会话或数据库仍占用')
|
||||
time.sleep(.2)
|
||||
if detail := native_error():
|
||||
# Global PCB COM can wait on another design's modal window.
|
||||
# Opening checks use only the newly bound process and fresh logs.
|
||||
from .diagnostic_open import check_target_window
|
||||
def diagnostic_emit(**event):
|
||||
nonlocal diagnostic_close_attempted
|
||||
if event.get('stage') == 'diagnostic_wm_close':
|
||||
diagnostic_close_attempted = True
|
||||
emit(**event)
|
||||
checked = check_target_window(job, worker_pid, emit=diagnostic_emit,
|
||||
error_reader=native_error, launcher_process=launcher_process)
|
||||
released = cleanup_verify_processes(lm_pid, worker_pid, worker_parent_pid,
|
||||
expected_pcb=job['pcb'], baseline_pids=pcb_before, emit=emit)
|
||||
if (checked.get('status') != 'PASS' or not checked.get('native_processes_exited')
|
||||
or not released or not released.get('safe_to_continue')):
|
||||
raise RuntimeError(f'DIAGNOSTIC_CLOSE_UNCONFIRMED: {checked}; {released}')
|
||||
from .diagnostic_open import _read_bounded
|
||||
if detail := _read_bounded(native_error):
|
||||
raise RuntimeError(detail)
|
||||
completed = True
|
||||
emit(stage='diagnostic_complete', status='PASS')
|
||||
return {'status': 'PASS', 'stdout': 'ICDB 启动检查通过;未执行集成或保存,已关闭工程。'}
|
||||
return {'status': 'PASS', 'stdout': 'ICDB 启动检查通过;工程及启动器已退出。'}
|
||||
from .pcb_bridge import ProcessWatch
|
||||
with ProcessWatch((lm_pid, worker_pid, worker_parent_pid)) as watch:
|
||||
app, doc, pi = wait_for_target_document(
|
||||
job, lambda: win32com.client.GetActiveObject('MGCPCB.Application'),
|
||||
process_alive=watch.alive, emit=emit, error_reader=native_error)
|
||||
identity_verified = True
|
||||
# Do not acquire MGCPCBAutomationLicensing from this 64-bit Python
|
||||
# worker. EE7.9 registers that automation class for the 32-bit host;
|
||||
# the old, working path acquires the token inside the SysWOW64
|
||||
@@ -877,8 +888,8 @@ def execute_job(job, emit):
|
||||
if helper is not None and helper.poll() is None:
|
||||
emit(stage='save_helper_retained', helper_pid=helper.pid)
|
||||
elif diagnostic_close_attempted:
|
||||
# A timed-out close helper may still own an in-flight native Close.
|
||||
# Observe release below, but never start a second close helper.
|
||||
# The process-bound checker already sent its sole WM_CLOSE.
|
||||
# Preserve an unknown prompt; never fall back to global COM Close.
|
||||
pass
|
||||
elif not completed and identity_verified:
|
||||
try:
|
||||
@@ -994,11 +1005,16 @@ def worker_main(request_path):
|
||||
start_supervisor_watchdog(job['supervisor_pid'], cancel_path=job.get('cancel_signal'), stop_clients=True)
|
||||
start_gate = Path(job.get('start_gate', '')) if job.get('start_gate') else None
|
||||
if start_gate is not None:
|
||||
gate_deadline = time.monotonic() + 15
|
||||
from .defaults import WORKER_START_GATE_TIMEOUT_SECONDS
|
||||
gate_deadline = time.monotonic() + WORKER_START_GATE_TIMEOUT_SECONDS
|
||||
while not start_gate.is_file():
|
||||
if job.get('cancel_signal') and Path(job['cancel_signal']).exists():
|
||||
raise RuntimeError('VERIFY_CANCELLED: 启动已取消,未启动 PCB')
|
||||
if time.monotonic() >= gate_deadline:
|
||||
raise RuntimeError('DIALOG_AGENT_START_TIMEOUT: 弹窗代理未就绪,未启动 PCB')
|
||||
time.sleep(.05)
|
||||
if job.get('cancel_signal') and Path(job['cancel_signal']).exists():
|
||||
raise RuntimeError('VERIFY_CANCELLED: 启动已取消,未启动 PCB')
|
||||
outcome = execute_job(job, emit)
|
||||
except Exception as error:
|
||||
traceback.print_exc()
|
||||
@@ -1444,6 +1460,8 @@ def read_library_flag(library, name, *, timeout_seconds=90, log_path=None):
|
||||
import win32con
|
||||
import win32process
|
||||
import win32service
|
||||
from pywinauto import Desktop
|
||||
from pywinauto.controls.common_controls import TreeViewWrapper
|
||||
|
||||
executable = library_manager_path()
|
||||
if not executable.is_file():
|
||||
@@ -1452,8 +1470,6 @@ def read_library_flag(library, name, *, timeout_seconds=90, log_path=None):
|
||||
deadline = time.monotonic() + timeout_seconds
|
||||
desktop_name = 'CbbFlagRead_' + os.urandom(5).hex()
|
||||
desktop = win32service.CreateDesktop(desktop_name, 0, win32con.GENERIC_ALL, None)
|
||||
from pywinauto import Desktop
|
||||
from pywinauto.controls.common_controls import TreeViewWrapper
|
||||
|
||||
handle = None
|
||||
pid = None
|
||||
|
||||
@@ -265,14 +265,8 @@ def validate_export_output(kind, code, report, log):
|
||||
|
||||
|
||||
def _process_snapshot():
|
||||
import win32com.client
|
||||
service = win32com.client.GetObject('winmgmts:')
|
||||
try:
|
||||
return [{'pid': int(p.ProcessId), 'parent': int(p.ParentProcessId or 0),
|
||||
'name': str(p.Name), 'executable': str(p.ExecutablePath or '')}
|
||||
for p in service.ExecQuery('SELECT ProcessId, ParentProcessId, Name, ExecutablePath FROM Win32_Process')]
|
||||
finally:
|
||||
service = None
|
||||
from .owner_probe import query_process_snapshot
|
||||
return query_process_snapshot(timeout_seconds=10)
|
||||
|
||||
|
||||
def _database_released(project_root):
|
||||
@@ -295,9 +289,20 @@ 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):
|
||||
try:
|
||||
_write_json(root/'export-launch.json', {'started': False})
|
||||
except OSError as error:
|
||||
return {'success': False, 'safe_to_continue': True, 'native_started': False,
|
||||
'detail': str(error)}
|
||||
diagnostic_warnings = []
|
||||
try:
|
||||
before = _process_snapshot()
|
||||
except Exception as error:
|
||||
return {'success': False, 'safe_to_continue': True, 'native_started': False,
|
||||
'detail': str(error)}
|
||||
from .backup_recovery import _native_scope_match
|
||||
if any(p['name'].casefold() in _OWNER_NAMES and _native_scope_match(
|
||||
p.get('command', ''), roots=(project.parent,)) is True for p in before):
|
||||
return {'success': False, 'safe_to_continue': False, 'detail': 'An existing iCDB owner prevents isolated identity export.'}
|
||||
if not _database_released(project.parent):
|
||||
return {'success': False, 'safe_to_continue': False, 'detail': 'Analysis copy has unreleased native addresses or DB handles.'}
|
||||
@@ -318,14 +323,20 @@ def _run_exports(project, root, mentor_home, timeout_seconds):
|
||||
for kind, command, report, log in commands:
|
||||
process = None
|
||||
handles = {}
|
||||
identities = {}
|
||||
released = False
|
||||
record = {'command': command, 'kind': kind, 'success': False, 'safe_to_continue': False}
|
||||
launch_attempted = False
|
||||
record = {'command': command, 'kind': kind, 'success': False,
|
||||
'safe_to_continue': False, 'native_started': False}
|
||||
try:
|
||||
deadline = time.monotonic()+float(timeout_seconds)
|
||||
with (root/(kind+'-stdout.txt')).open('wb') as output:
|
||||
_write_json(root/'export-launch.json', {'started': True})
|
||||
launch_attempted = True
|
||||
record['native_started'] = None
|
||||
process = subprocess.Popen(command, stdout=output, stderr=subprocess.STDOUT,
|
||||
creationflags=subprocess.CREATE_NO_WINDOW)
|
||||
record['native_started'] = True
|
||||
record['pid'] = process.pid
|
||||
descendants = {process.pid}
|
||||
_write_json(root/(kind+'-process.json'), record)
|
||||
@@ -336,13 +347,19 @@ def _run_exports(project, root, mentor_home, timeout_seconds):
|
||||
previous = len(descendants)
|
||||
descendants.update(p['pid'] for p in snapshot if p['parent'] in descendants)
|
||||
changed = len(descendants) != previous
|
||||
owners = [p for p in snapshot if p['pid'] in descendants or p['name'].casefold() in _OWNER_NAMES]
|
||||
owners = [p for p in snapshot if p['pid'] in descendants or (
|
||||
p['name'].casefold() in _OWNER_NAMES and _native_scope_match(
|
||||
p.get('command', ''), roots=(project.parent,)) is True)]
|
||||
for owner in owners:
|
||||
if owner['pid'] not in handles:
|
||||
try: handles[owner['pid']] = win32api.OpenProcess(win32con.SYNCHRONIZE, False, owner['pid'])
|
||||
except pywintypes.error as error:
|
||||
if error.winerror != 87: raise
|
||||
record['observed_pids'] = sorted(descendants | handles.keys())
|
||||
identities.update({owner['pid']:
|
||||
{key: owner.get(key, '') for key in ('pid', 'created', 'executable')}
|
||||
for owner in owners})
|
||||
record['process_identities'] = list(identities.values())
|
||||
if (process.poll() is not None and not owners
|
||||
and all(win32event.WaitForSingleObject(h, 0) == win32con.WAIT_OBJECT_0 for h in handles.values())):
|
||||
released = _database_released(project.parent)
|
||||
@@ -355,15 +372,37 @@ def _run_exports(project, root, mentor_home, timeout_seconds):
|
||||
validate_export_output(kind, process.returncode, report, log)
|
||||
record.update(success=True, detail='Native export complete and owners released.')
|
||||
except Exception as error:
|
||||
creation_rejected = (isinstance(error, (FileNotFoundError, PermissionError))
|
||||
or getattr(error, 'winerror', None) in (2, 3, 5, 193, 206, 740))
|
||||
if process is None and (not launch_attempted or creation_rejected):
|
||||
# Only a known CreateProcess rejection proves that no native owner started.
|
||||
released = True
|
||||
record['native_started'] = False
|
||||
_write_json(root/'export-launch.json', {'started': False})
|
||||
record.update(detail=str(error), safe_to_continue=released)
|
||||
return record
|
||||
finally:
|
||||
if process is not None and not released:
|
||||
_retained_exports.append((process, handles))
|
||||
import json
|
||||
owner_path = root/'export-owner.json'
|
||||
try:
|
||||
owner = json.loads(owner_path.read_text('utf-8')) if owner_path.is_file() else {}
|
||||
except (ValueError, OSError):
|
||||
owner = {} # Preserve unknown ownership; never lose the live handles.
|
||||
_retained_exports.append((process, handles, {
|
||||
'library': owner.get('library'), 'project': str(project), 'analysis_root': str(root)}))
|
||||
else:
|
||||
for handle in handles.values(): handle.Close()
|
||||
_write_json(root/(kind+'-process.json'), record)
|
||||
return {'success': True, 'safe_to_continue': True, 'detail': 'All three native exports completed and released.'}
|
||||
try:
|
||||
_write_json(root/(kind+'-process.json'), record)
|
||||
except OSError as error:
|
||||
if not released:
|
||||
raise
|
||||
warning = 'Export diagnostic write failed: '+str(error)
|
||||
diagnostic_warnings.append(warning)
|
||||
record['detail'] = (record.get('detail', '')+'\n'+warning).strip()
|
||||
return {'success': True, 'safe_to_continue': True,
|
||||
'detail': '\n'.join(['All three native exports completed and released.', *diagnostic_warnings])}
|
||||
|
||||
|
||||
def capture_identity(source, evidence_root, *, expected_library, owner_library, mentor_home,
|
||||
@@ -374,18 +413,22 @@ def capture_identity(source, evidence_root, *, expected_library, owner_library,
|
||||
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()
|
||||
library = Path(owner_library)
|
||||
lease = LibraryLock(library)
|
||||
if owned_snapshot(lease.path) is None:
|
||||
raise ValueError('Native identity capture requires a current-thread transaction library lease.')
|
||||
if (root.resolve().is_relative_to(source.parent) or source.parent.is_relative_to(root.resolve())
|
||||
or root.resolve().is_relative_to(library.parent.resolve())):
|
||||
raise ValueError('Native identity evidence must be independent of source and library.')
|
||||
check_exporters(mentor_home)
|
||||
root.mkdir(parents=True, exist_ok=False)
|
||||
mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795')
|
||||
root = Path(evidence_root)
|
||||
try:
|
||||
root = root.absolute()
|
||||
source, pcb, top = source_project(source)
|
||||
library = Path(owner_library)
|
||||
lease = LibraryLock(library)
|
||||
if owned_snapshot(lease.path) is None:
|
||||
raise ValueError('Native identity capture requires a current-thread transaction library lease.')
|
||||
if (root.resolve().is_relative_to(source.parent) or source.parent.is_relative_to(root.resolve())
|
||||
or root.resolve().is_relative_to(library.parent.resolve())):
|
||||
raise ValueError('Native identity evidence must be independent of source and library.')
|
||||
check_exporters(mentor_home)
|
||||
root.mkdir(parents=True, exist_ok=False)
|
||||
mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795')
|
||||
except Exception as error:
|
||||
return IdentityOutcome(None, True, str(error), root)
|
||||
acquired = False
|
||||
owner_safe = True
|
||||
outcome = IdentityOutcome(None, True, 'Identity capture did not start.', root)
|
||||
@@ -403,10 +446,11 @@ def capture_identity(source, evidence_root, *, expected_library, owner_library,
|
||||
export_token = begin_export_analysis(library, root, clone)
|
||||
owner_safe = False
|
||||
native = _run_exports(clone, root, mentor_home, timeout_seconds)
|
||||
_write_json(root/'native-outcome.json', native)
|
||||
if native.get('safe_to_continue') is True:
|
||||
finish_export_analysis(library, export_token)
|
||||
finish_export_analysis(library, export_token,
|
||||
native_not_started=native.get('native_started') is False)
|
||||
owner_safe = True
|
||||
_write_json(root/'native-outcome.json', native)
|
||||
if not owner_safe or not native.get('success'):
|
||||
outcome = IdentityOutcome(None, owner_safe, native.get('detail', 'Native export failed.'), root)
|
||||
else:
|
||||
@@ -423,6 +467,10 @@ def capture_identity(source, evidence_root, *, expected_library, owner_library,
|
||||
finally:
|
||||
if acquired: win32event.ReleaseMutex(mutex)
|
||||
mutex.Close()
|
||||
_write_json(root/'identity.json', {'identity': outcome.identity, 'safe_to_continue': outcome.safe_to_continue,
|
||||
'detail': outcome.detail, 'policy': POLICY})
|
||||
try:
|
||||
_write_json(root/'identity.json', {'identity': outcome.identity, 'safe_to_continue': outcome.safe_to_continue,
|
||||
'detail': outcome.detail, 'policy': POLICY})
|
||||
except OSError as error:
|
||||
outcome = IdentityOutcome(outcome.identity, outcome.safe_to_continue,
|
||||
outcome.detail+'\nIdentity summary write failed: '+str(error), root)
|
||||
return outcome
|
||||
@@ -7,11 +7,16 @@ from uuid import uuid4
|
||||
from .management import _write_json
|
||||
|
||||
|
||||
def assert_retained_exports_idle():
|
||||
def assert_retained_exports_idle(library=None):
|
||||
import win32con, win32event
|
||||
from .native_engineering_identity import _retained_exports
|
||||
from .library_lock import LibraryBusy
|
||||
for process, handles in _retained_exports:
|
||||
for entry in _retained_exports:
|
||||
process, handles = entry[:2]
|
||||
scope = entry[2] if len(entry) > 2 else {}
|
||||
if (library is not None and scope.get('library')
|
||||
and Path(scope['library']).resolve() != Path(library).resolve()):
|
||||
continue
|
||||
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.')
|
||||
@@ -40,26 +45,33 @@ def begin_export_analysis(library, root, project):
|
||||
|
||||
|
||||
@contextmanager
|
||||
def prove_export_copies_released(library):
|
||||
def prove_export_copies_released(library, *, allow_unknown_checkpoint=False, unstarted_token=''):
|
||||
"""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()
|
||||
assert_retained_exports_idle(library)
|
||||
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 not allow_unknown_checkpoint:
|
||||
raise LibraryBusy('Invalid library checkpoint cannot release export ownership.')
|
||||
# Only the explicit release path supplies full-library/native proof and
|
||||
# archives the unchanged metadata while its coordination handle is held.
|
||||
assert_retained_exports_idle()
|
||||
if any(p['name'].casefold() in _OWNER_NAMES for p in _process_snapshot()):
|
||||
raise LibraryBusy('Unknown export checkpoint still has a possible native identity owner.')
|
||||
yield []
|
||||
return
|
||||
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}')
|
||||
snapshot = None
|
||||
copies = []
|
||||
with ExitStack() as stack:
|
||||
for record in records:
|
||||
@@ -78,15 +90,43 @@ def prove_export_copies_released(library):
|
||||
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}:
|
||||
launch_path = root/'export-launch.json'
|
||||
launch = json.loads(launch_path.read_text('utf-8')) if launch_path.exists() else None
|
||||
unstarted_current_lease = False
|
||||
if unstarted_token and record['token'] == unstarted_token:
|
||||
# In-memory no-start proof may clear its own guard even
|
||||
# when creating the first launch record failed.
|
||||
from .management_transaction import current_lease
|
||||
current = current_lease(library)
|
||||
unstarted_current_lease = (record['lease_id'] == current['lease_id']
|
||||
and record['supervisor_pid'] == current['supervisor_pid'])
|
||||
if launch != {'started': False} and not (launch is None and unstarted_current_lease):
|
||||
raise ValueError('Export launch has no confirmed process record.')
|
||||
else:
|
||||
if snapshot is None:
|
||||
snapshot = _process_snapshot()
|
||||
from .backup_recovery import _native_scope_match
|
||||
if any(p['name'].casefold() in _OWNER_NAMES and _native_scope_match(
|
||||
p.get('command', ''), roots=(project.parent,)) is True for p in snapshot):
|
||||
raise LibraryBusy('A native identity owner is bound to this analysis copy.')
|
||||
for path in processes:
|
||||
process = json.loads(path.read_text(encoding='utf-8'))
|
||||
if ('pid' not in process and process.get('safe_to_continue') is True
|
||||
and process.get('native_started') is False
|
||||
and json.loads((root/'export-launch.json').read_text('utf-8')) == {'started': False}):
|
||||
continue # Failed CreateProcess: no native ownership was acquired.
|
||||
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):
|
||||
identities = {p['pid']: p for p in process.get('process_identities', [])}
|
||||
def original_alive(pid):
|
||||
recorded = identities.get(pid, {})
|
||||
current = next((p for p in snapshot if p['pid'] == pid), None)
|
||||
if recorded.get('created') and current and current.get('created'):
|
||||
return (recorded['created'] == current['created']
|
||||
and recorded.get('executable') == current.get('executable'))
|
||||
return any(p['pid'] == pid for p in snapshot) or _supervisor_alive(pid)
|
||||
if any(original_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):
|
||||
@@ -105,9 +145,10 @@ def prove_export_copies_released(library):
|
||||
yield copies
|
||||
|
||||
|
||||
def finish_export_analysis(library, token):
|
||||
def finish_export_analysis(library, token, *, native_not_started=False):
|
||||
from .library_lock import _guard, blocker_path, checkpoint_record, LibraryBusy
|
||||
with _guard, prove_export_copies_released(library):
|
||||
with _guard, prove_export_copies_released(library,
|
||||
unstarted_token=token if native_not_started else ''):
|
||||
marker = blocker_path(library)
|
||||
checkpoint = checkpoint_record(marker)
|
||||
records = checkpoint.get('export_analysis', []) if checkpoint else []
|
||||
|
||||
@@ -21,6 +21,12 @@ from .scoped_manifest import hash_file
|
||||
from .network_path import absolute_preserving_drive
|
||||
|
||||
_retained_workers = []
|
||||
|
||||
|
||||
class NativeOperationError(RuntimeError):
|
||||
def __init__(self, detail, *, safe_to_continue):
|
||||
super().__init__(detail)
|
||||
self.safe_to_continue = safe_to_continue
|
||||
# Coordinator-owned Create/Add/conflict/update/remove/backup-reimport evidence:
|
||||
# diagnostics/issue2-native-crud-20261103/engine-e2e/cycle-result.json
|
||||
_PRODUCTION_ADD_VALIDATED = True
|
||||
@@ -62,6 +68,28 @@ class NativeManagementAdapter:
|
||||
self.timeout_seconds = timeout_seconds
|
||||
self.mapped_drive = ''
|
||||
self.mapped_remote_root = ''
|
||||
self._pending_workers = {}
|
||||
|
||||
def release_confirmed(self, library):
|
||||
"""Reap only this adapter's timed-out worker after its own release result."""
|
||||
key = str(Path(library).resolve()).casefold()
|
||||
pending = self._pending_workers.get(key)
|
||||
if pending is None:
|
||||
return False
|
||||
worker, evidence = pending
|
||||
if worker.poll() is None:
|
||||
return False
|
||||
try:
|
||||
result = json.loads((evidence/'result.json').read_text(encoding='utf-8'))
|
||||
if result.get('safe_to_continue') is not True:
|
||||
return False
|
||||
except (OSError, ValueError, TypeError, AttributeError):
|
||||
return False
|
||||
worker.close()
|
||||
if worker in _retained_workers:
|
||||
_retained_workers.remove(worker)
|
||||
del self._pending_workers[key]
|
||||
return True
|
||||
|
||||
def bind_library_mapping(self, drive, remote_root):
|
||||
self.mapped_drive = drive or ''
|
||||
@@ -105,14 +133,18 @@ class NativeManagementAdapter:
|
||||
}
|
||||
|
||||
def _worker(self, job, evidence):
|
||||
evidence = Path(evidence)
|
||||
evidence.mkdir(parents=True, exist_ok=False)
|
||||
desktop = 'CbbManagement_' + uuid4().hex[:12]
|
||||
timeout = float(job.get('timeout_seconds', self.timeout_seconds))
|
||||
job = {**job, 'desktop': desktop, 'mentor_home': str(self.home or ''),
|
||||
'mapped_drive': job.get('mapped_drive', self.mapped_drive),
|
||||
'mapped_remote_root': job.get('mapped_remote_root', self.mapped_remote_root),
|
||||
'timeout_seconds': timeout, 'supervisor_pid': os.getpid()}
|
||||
try:
|
||||
evidence = Path(evidence)
|
||||
evidence.mkdir(parents=True, exist_ok=False)
|
||||
desktop = 'CbbManagement_' + uuid4().hex[:12]
|
||||
timeout = float(job.get('timeout_seconds', self.timeout_seconds))
|
||||
job = {**job, 'desktop': desktop, 'mentor_home': str(self.home or ''),
|
||||
'mapped_drive': job.get('mapped_drive', self.mapped_drive),
|
||||
'mapped_remote_root': job.get('mapped_remote_root', self.mapped_remote_root),
|
||||
'timeout_seconds': timeout, 'supervisor_pid': os.getpid()}
|
||||
except Exception as error:
|
||||
error.safe_to_continue = True
|
||||
raise
|
||||
if job['operation'] == 'add':
|
||||
import win32con, win32event
|
||||
mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795')
|
||||
@@ -158,6 +190,23 @@ class NativeManagementAdapter:
|
||||
return self._launch_worker(job, evidence)
|
||||
|
||||
def _launch_worker(self, job, evidence):
|
||||
state = {'attempted': False, 'worker': None, 'released': False}
|
||||
try:
|
||||
return self._launch_worker_observed(job, evidence, state)
|
||||
except Exception as error:
|
||||
proof = getattr(error, 'worker_launch_release', None)
|
||||
no_launch = (isinstance(proof, dict) and proof.get('safe_to_continue') is True
|
||||
and proof.get('process_created') is False and proof.get('worker_exited') is True
|
||||
and proof.get('remaining_pids') == [])
|
||||
error.safe_to_continue = (not state['attempted'] or state['released']
|
||||
or (state['worker'] is None and no_launch))
|
||||
if state['worker'] is not None and not error.safe_to_continue:
|
||||
if state['worker'] not in _retained_workers:
|
||||
_retained_workers.append(state['worker'])
|
||||
self._pending_workers[str(Path(job['library']).resolve()).casefold()] = (state['worker'], evidence)
|
||||
raise
|
||||
|
||||
def _launch_worker_observed(self, job, evidence, state):
|
||||
from .desktop_worker import DesktopWorker
|
||||
request_path = evidence/'request.json'
|
||||
desktop, timeout = job['desktop'], job['timeout_seconds']
|
||||
@@ -168,13 +217,17 @@ class NativeManagementAdapter:
|
||||
_write_json(request_path, job)
|
||||
command = ([sys.executable] if getattr(sys, 'frozen', False)
|
||||
else [sys.executable, '-m', 'cbb_refresh_verify'])
|
||||
state['attempted'] = True
|
||||
worker = (self.worker_factory or DesktopWorker)(command + ['--management-worker', str(request_path)], desktop)
|
||||
state['worker'] = worker
|
||||
worker.cbb_library = str(Path(job['library']).resolve())
|
||||
while worker.poll() is None and time.monotonic() < deadline:
|
||||
time.sleep(.1)
|
||||
if worker.poll() is None:
|
||||
# DesktopWorker.close() requests a kill without a cancellation file.
|
||||
# Keep this exact worker alive until its native call returns normally.
|
||||
_retained_workers.append(worker)
|
||||
self._pending_workers[str(Path(job['library']).resolve()).casefold()] = (worker, evidence)
|
||||
if add_job:
|
||||
(evidence/'cancel-native-add.signal').touch()
|
||||
return {'success': False, 'safe_to_continue': False,
|
||||
@@ -183,6 +236,7 @@ class NativeManagementAdapter:
|
||||
result = json.loads((evidence/'result.json').read_text(encoding='utf-8'))
|
||||
if not isinstance(result.get('safe_to_continue'), bool):
|
||||
raise ValueError('原生释放记录缺失')
|
||||
state['released'] = result['safe_to_continue']
|
||||
return result
|
||||
except (OSError, ValueError) as error:
|
||||
return {'success': False, 'safe_to_continue': False, 'detail': str(error)}
|
||||
@@ -192,7 +246,8 @@ class NativeManagementAdapter:
|
||||
def catalog(self, library, evidence):
|
||||
result = self._worker({'operation': 'catalog', 'library': str(absolute_preserving_drive(library))}, evidence)
|
||||
if not result.get('success') or not result.get('safe_to_continue'):
|
||||
raise RuntimeError(result.get('detail', '原生目录复读未确认,禁止文件夹回退。'))
|
||||
raise NativeOperationError(result.get('detail', '原生目录复读未确认,禁止文件夹回退。'),
|
||||
safe_to_continue=result.get('safe_to_continue') is True)
|
||||
return Catalog(Path(result['library']), int(result['flow']),
|
||||
tuple(CatalogEntry(**entry) for entry in result['entries']), result['safe_to_continue'])
|
||||
|
||||
@@ -228,48 +283,65 @@ class NativeManagementAdapter:
|
||||
from .management_transaction import current_lease, prepare_transaction
|
||||
from .management import source_project
|
||||
from .backup_recovery import _align_library
|
||||
if not self.capabilities()['add'].supported:
|
||||
raise ValueError(self.capabilities()['add'].reason)
|
||||
try:
|
||||
if not self.capabilities()['add'].supported:
|
||||
raise ValueError(self.capabilities()['add'].reason)
|
||||
validate_native_copy_paths(request.source, request.library, request.name)
|
||||
except ValueError as error:
|
||||
current_lease(request.library)
|
||||
original_assets = asset_identity(original_source, project_library(original_source))
|
||||
staged, pcb, _ = source_project(request.source, request.top_level_block)
|
||||
if staged.parent != Path(root).resolve()/'source':
|
||||
raise ValueError('Only the engine staged source can be aligned for native Add.')
|
||||
_align_library(staged, pcb, request.library)
|
||||
if asset_identity(staged, request.library) != original_assets:
|
||||
raise ValueError('Staged engineering assets differ from the original source.')
|
||||
except Exception as error:
|
||||
return request, IdentityOutcome(None, True, str(error), Path(root))
|
||||
current_lease(request.library)
|
||||
original_assets = asset_identity(original_source, project_library(original_source))
|
||||
staged, pcb, _ = source_project(request.source, request.top_level_block)
|
||||
if staged.parent != Path(root).resolve()/'source':
|
||||
raise ValueError('Only the engine staged source can be aligned for native Add.')
|
||||
_align_library(staged, pcb, request.library)
|
||||
if asset_identity(staged, request.library) != original_assets:
|
||||
raise ValueError('Staged engineering assets differ from the original source.')
|
||||
proof = capture_identity(staged, Path(root)/'source-identity', expected_library=request.library,
|
||||
owner_library=request.library, mentor_home=self.home, timeout_seconds=request.timeout_seconds)
|
||||
if proof.identity is None or not proof.safe_to_continue:
|
||||
return request, proof
|
||||
token = prepare_transaction(request, root, proof.identity, mentor_home=self.home,
|
||||
fixture=getattr(self, '_fixture_authority', None))
|
||||
try:
|
||||
token = prepare_transaction(request, root, proof.identity, mentor_home=self.home,
|
||||
fixture=getattr(self, '_fixture_authority', None))
|
||||
except Exception as error:
|
||||
return request, IdentityOutcome(None, proof.safe_to_continue, str(error), Path(root))
|
||||
return replace(request, transaction_token=token), proof
|
||||
|
||||
def _add_transaction(self, request, evidence):
|
||||
from contextlib import contextmanager
|
||||
from .management_transaction import validate_transaction
|
||||
from .library_lock import LibraryLock
|
||||
from .native_engineering_identity import capture_identity, project_library
|
||||
from .management import source_project
|
||||
from .backup_recovery import _align_library, _idle_check
|
||||
job = {'operation': 'add', 'authority_kind': 'management', 'transaction_nonce': request.transaction_token,
|
||||
'library': str(absolute_preserving_drive(request.library)), 'source': str(request.source),
|
||||
'name': request.name, 'partition': request.partition, 'top_level_block': request.top_level_block,
|
||||
'source_identity': engineering_identity(request.source), 'supervisor_pid': os.getpid(),
|
||||
'mentor_home': str(self.home), 'timeout_seconds': request.timeout_seconds,
|
||||
'mapped_drive': request.mapped_drive, 'mapped_remote_root': request.mapped_remote_root}
|
||||
prepared = validate_transaction(job, evidence.parent)
|
||||
owner_safe = False
|
||||
with LibraryLock(request.library, safe_to_release=lambda: owner_safe):
|
||||
try:
|
||||
job = {'operation': 'add', 'authority_kind': 'management', 'transaction_nonce': request.transaction_token,
|
||||
'library': str(absolute_preserving_drive(request.library)), 'source': str(request.source),
|
||||
'name': request.name, 'partition': request.partition, 'top_level_block': request.top_level_block,
|
||||
'source_identity': engineering_identity(request.source), 'supervisor_pid': os.getpid(),
|
||||
'mentor_home': str(self.home), 'timeout_seconds': request.timeout_seconds,
|
||||
'mapped_drive': request.mapped_drive, 'mapped_remote_root': request.mapped_remote_root}
|
||||
prepared = validate_transaction(job, evidence.parent)
|
||||
except Exception as error:
|
||||
error.safe_to_continue = True
|
||||
raise
|
||||
owner_safe = True
|
||||
@contextmanager
|
||||
def preserve_release():
|
||||
nonlocal owner_safe
|
||||
try:
|
||||
yield
|
||||
except Exception as error:
|
||||
owner_safe = getattr(error, 'safe_to_continue', owner_safe) is True
|
||||
error.safe_to_continue = owner_safe
|
||||
raise
|
||||
with LibraryLock(request.library, safe_to_release=lambda: owner_safe), preserve_release():
|
||||
owner_safe = False
|
||||
result = self._worker(job, evidence)
|
||||
owner_safe = result.get('safe_to_continue') is True
|
||||
if not owner_safe or not result.get('success'):
|
||||
return NativeOutcome(False, owner_safe, result.get('detail', 'Native Add failed.'), evidence_path=evidence)
|
||||
owner_safe = False
|
||||
# The native editor may leave PCB/pcb.prj relative to the staged
|
||||
# location. Correct only documented library-reference tokens after
|
||||
# its owner has exited, then reopen the native catalog independently.
|
||||
@@ -277,12 +349,10 @@ class NativeManagementAdapter:
|
||||
work = Path(request.library).parent/'ReusableBlocksLP'/request.name/'Work'
|
||||
projects = list(work.glob('*.prj'))
|
||||
if len(projects) != 1:
|
||||
owner_safe = False
|
||||
return NativeOutcome(True, False, 'Registered engineering project is not unique.',
|
||||
return NativeOutcome(True, owner_safe, 'Registered engineering project is not unique.',
|
||||
identity_matches=False, evidence_path=evidence)
|
||||
target, pcb, _ = source_project(projects[0], request.top_level_block)
|
||||
_idle_check(request.library, target, pcb)
|
||||
owner_safe = False
|
||||
from .maintenance_entry import maintenance_project_files
|
||||
project_files = maintenance_project_files(target, pcb)
|
||||
before_refs = {str(p): hash_file(p) for p in project_files}
|
||||
@@ -291,13 +361,13 @@ class NativeManagementAdapter:
|
||||
raise ValueError('Registered project references do not resolve to the exact target library.')
|
||||
_write_json(evidence/'reference-alignment.json', {'before': before_refs,
|
||||
'after': {str(p): hash_file(p) for p in project_files}, 'library': job['library']})
|
||||
owner_safe = False
|
||||
catalog = self.catalog(request.library, evidence/'reopen-aligned')
|
||||
owner_safe = catalog.safe_to_continue
|
||||
entries = [entry for entry in catalog.entries if entry.name == request.name and entry.partition == request.partition]
|
||||
if (not owner_safe or Path(catalog.library).resolve() != Path(request.library).resolve()
|
||||
or catalog.flow != 1 or len(entries) != 1):
|
||||
owner_safe = False
|
||||
return NativeOutcome(True, False, 'Aligned target did not reopen with the exact catalog identity.',
|
||||
return NativeOutcome(True, owner_safe, 'Aligned target did not reopen with the exact catalog identity.',
|
||||
identity_matches=False, evidence_path=evidence)
|
||||
owner_safe = False
|
||||
proof = capture_identity(target, evidence/'registered-identity', expected_library=request.library,
|
||||
@@ -906,17 +976,21 @@ def _catalog_native(job, root):
|
||||
def _catalog_com(job, root):
|
||||
import pythoncom, win32com.client, win32con, win32gui, win32process
|
||||
from .mentor_adapter import _process_details
|
||||
if job['operation'] == 'add':
|
||||
if job.get('authority_kind') == 'management':
|
||||
from .management_transaction import validate_transaction
|
||||
validate_transaction(job, root.parent)
|
||||
else:
|
||||
validate_owned_fixture_add(job, root)
|
||||
desktop, name = _current_desktop()
|
||||
if name != job['desktop'] or not name.startswith('CbbManagement_'):
|
||||
raise RuntimeError('拒绝在非本次私有桌面读取原生目录。')
|
||||
if _process_details('LibraryManager.exe'):
|
||||
raise RuntimeError('已有 Library Manager 运行,请关闭后重试。')
|
||||
try:
|
||||
if job['operation'] == 'add':
|
||||
if job.get('authority_kind') == 'management':
|
||||
from .management_transaction import validate_transaction
|
||||
validate_transaction(job, root.parent)
|
||||
else:
|
||||
validate_owned_fixture_add(job, root)
|
||||
desktop, name = _current_desktop()
|
||||
if name != job['desktop'] or not name.startswith('CbbManagement_'):
|
||||
raise RuntimeError('拒绝在非本次私有桌面读取原生目录。')
|
||||
if _process_details('LibraryManager.exe'):
|
||||
raise RuntimeError('已有 Library Manager 运行,请关闭后重试。')
|
||||
except Exception as error:
|
||||
error.safe_to_continue = True
|
||||
raise
|
||||
stop = threading.Event()
|
||||
refused = []
|
||||
observed = []
|
||||
@@ -1059,7 +1133,7 @@ def management_worker_main(request_path):
|
||||
request_path = Path(request_path)
|
||||
root = request_path.parent
|
||||
job = json.loads(request_path.read_text(encoding='utf-8'))
|
||||
result = {'success': False, 'safe_to_continue': False}
|
||||
result = {'success': False, 'safe_to_continue': True}
|
||||
try:
|
||||
_, desktop = _current_desktop()
|
||||
if desktop != job['desktop'] or not desktop.startswith('CbbManagement_'):
|
||||
@@ -1077,6 +1151,7 @@ def management_worker_main(request_path):
|
||||
raise ValueError('Native Add requires Logical-Physical.')
|
||||
if engineering_identity(job['source']) != job.get('source_identity'):
|
||||
raise ValueError('Staged source engineering identity changed before native Add.')
|
||||
result['safe_to_continue'] = False
|
||||
result = _catalog_native(job, root)
|
||||
elif job['operation'] == 'remove':
|
||||
adapter = NativeManagementAdapter(mentor_home=job['mentor_home'])
|
||||
@@ -1090,8 +1165,13 @@ def management_worker_main(request_path):
|
||||
command = [str(adapter.home/'lm/win32/bin/CleanWGLib.exe'), str(job['library']), 'F4', str(input_path)]
|
||||
_write_json(root/'command.json', command)
|
||||
with (root/'native-output.txt').open('wb') as output:
|
||||
process = subprocess.Popen(command, stdout=output, stderr=subprocess.STDOUT,
|
||||
creationflags=subprocess.CREATE_NO_WINDOW)
|
||||
result['safe_to_continue'] = False
|
||||
try:
|
||||
process = subprocess.Popen(command, stdout=output, stderr=subprocess.STDOUT,
|
||||
creationflags=subprocess.CREATE_NO_WINDOW)
|
||||
except (FileNotFoundError, PermissionError):
|
||||
result['safe_to_continue'] = True
|
||||
raise
|
||||
_write_json(root/'native-process.json', {'pid': process.pid, 'command': command})
|
||||
# Never terminate this native database owner on timeout.
|
||||
try:
|
||||
@@ -1099,12 +1179,15 @@ def management_worker_main(request_path):
|
||||
except subprocess.TimeoutExpired:
|
||||
result.update(detail=f'TIMEOUT: CleanWGLib PID {process.pid} 尚未释放')
|
||||
else:
|
||||
result.update(safe_to_continue=True, exit_code=code)
|
||||
text = (root/'native-output.txt').read_bytes().decode('mbcs', errors='replace')
|
||||
result.update(success=removal_output_ok(code, text, job['name'], job['partition']),
|
||||
safe_to_continue=True, detail=text, exit_code=code)
|
||||
detail=text)
|
||||
else:
|
||||
raise ValueError('未验证的原生管理操作')
|
||||
except Exception as error:
|
||||
if getattr(error, 'safe_to_continue', None) is True:
|
||||
result['safe_to_continue'] = True
|
||||
result['detail'] = str(error)
|
||||
result['exception'] = _exception_details(error)
|
||||
finally:
|
||||
|
||||
@@ -9,6 +9,20 @@ import ntpath
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Protocol
|
||||
from functools import wraps
|
||||
from threading import RLock
|
||||
from weakref import WeakValueDictionary
|
||||
|
||||
_retained_path_leases = {}
|
||||
_live_path_leases = WeakValueDictionary()
|
||||
_path_lease_guard = RLock()
|
||||
|
||||
|
||||
def _lease_locked(method):
|
||||
@wraps(method)
|
||||
def locked(*args, **kwargs):
|
||||
with _path_lease_guard: return method(*args, **kwargs)
|
||||
return locked
|
||||
|
||||
|
||||
class NetworkPathError(RuntimeError):
|
||||
@@ -45,23 +59,35 @@ class WindowsWNetBackend:
|
||||
def __init__(self) -> None:
|
||||
self._mpr = ctypes.WinDLL("mpr", use_last_error=True)
|
||||
self._kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
|
||||
self._unavailable_drives = set()
|
||||
|
||||
def mapping(self, drive: str) -> str | None:
|
||||
size = wintypes.DWORD(32768)
|
||||
buffer = ctypes.create_unicode_buffer(size.value)
|
||||
error = self._mpr.WNetGetConnectionW(drive, buffer, ctypes.byref(size))
|
||||
if error == 0:
|
||||
return buffer.value
|
||||
if error == self.ERROR_NOT_CONNECTED:
|
||||
return None
|
||||
raise OSError(error, f"WNetGetConnectionW({drive})")
|
||||
|
||||
def mappings(self) -> dict[str, str]:
|
||||
result: dict[str, str] = {}
|
||||
self._unavailable_drives = set()
|
||||
for code in range(ord("D"), ord("Z") + 1):
|
||||
drive = f"{chr(code)}:"
|
||||
size = wintypes.DWORD(32768)
|
||||
buffer = ctypes.create_unicode_buffer(size.value)
|
||||
error = self._mpr.WNetGetConnectionW(drive, buffer, ctypes.byref(size))
|
||||
if error == 0:
|
||||
result[drive] = buffer.value
|
||||
elif error != self.ERROR_NOT_CONNECTED:
|
||||
raise OSError(error, f"WNetGetConnectionW({drive})")
|
||||
try:
|
||||
remote = self.mapping(drive)
|
||||
except OSError:
|
||||
self._unavailable_drives.add(drive)
|
||||
continue
|
||||
if remote:
|
||||
result[drive] = remote
|
||||
return result
|
||||
|
||||
def used_drives(self) -> set[str]:
|
||||
mask = int(self._kernel32.GetLogicalDrives())
|
||||
return {
|
||||
return getattr(self, '_unavailable_drives', set()) | {
|
||||
f"{chr(ord('A') + index)}:"
|
||||
for index in range(26)
|
||||
if mask & (1 << index)
|
||||
@@ -88,6 +114,14 @@ def _same_remote(left: str, right: str) -> bool:
|
||||
return ntpath.normcase(ntpath.normpath(left)) == ntpath.normcase(ntpath.normpath(right))
|
||||
|
||||
|
||||
def _mapping(backend, drive):
|
||||
direct = getattr(backend, 'mapping', None)
|
||||
if callable(direct):
|
||||
return direct(drive)
|
||||
return next((value for key, value in backend.mappings().items()
|
||||
if str(key).upper().rstrip('\\/') == drive.upper()), None)
|
||||
|
||||
|
||||
def ensure_mapped_drive_visible(drive: str, remote_root: str, *,
|
||||
backend: WNetBackend | None = None) -> dict[str, object]:
|
||||
"""Ensure a worker process can see the mapped drive used by Mentor.
|
||||
@@ -108,13 +142,11 @@ def ensure_mapped_drive_visible(drive: str, remote_root: str, *,
|
||||
normalized_drive = raw_drive.upper()
|
||||
backend = backend or WindowsWNetBackend()
|
||||
try:
|
||||
mappings = backend.mappings()
|
||||
current = _mapping(backend, normalized_drive)
|
||||
except OSError as error:
|
||||
raise NetworkPathError(
|
||||
f"NETWORK_UNAVAILABLE: 无法读取网络盘映射 {normalized_drive}: {error}"
|
||||
) from error
|
||||
current = next((value for key, value in mappings.items()
|
||||
if str(key).upper().rstrip('\\/') == normalized_drive), None)
|
||||
if current:
|
||||
if _same_remote(current, raw_remote):
|
||||
return {'drive': normalized_drive, 'remote_root': current, 'created': False}
|
||||
@@ -180,7 +212,11 @@ class LibraryPathLease:
|
||||
_closed: bool = False
|
||||
_retained_for_recovery: bool = False
|
||||
|
||||
def __post_init__(self):
|
||||
with _path_lease_guard: _live_path_leases[id(self)] = self
|
||||
|
||||
@classmethod
|
||||
@_lease_locked
|
||||
def acquire(cls, path, *, backend: WNetBackend | None = None) -> "LibraryPathLease":
|
||||
raw = _normalize_input_path(path)
|
||||
if not raw.startswith("\\\\"):
|
||||
@@ -189,8 +225,7 @@ class LibraryPathLease:
|
||||
if drive:
|
||||
try:
|
||||
backend = backend or WindowsWNetBackend()
|
||||
remote = next((value for key, value in backend.mappings().items()
|
||||
if str(key).upper().rstrip('\\/') == drive.upper()), '')
|
||||
remote = _mapping(backend, drive.upper()) or ''
|
||||
except (OSError, AttributeError):
|
||||
remote = ''
|
||||
return cls(local, local, drive.upper(), remote, False, backend)
|
||||
@@ -225,10 +260,31 @@ class LibraryPathLease:
|
||||
f"NETWORK_UNAVAILABLE: 无法挂载中心库 {remote_root}: {error}"
|
||||
) from error
|
||||
|
||||
@_lease_locked
|
||||
def retain_for_recovery(self) -> None:
|
||||
"""Keep the Mentor drive available to a retained native session."""
|
||||
self._retained_for_recovery = True
|
||||
_retained_path_leases[id(self)] = self
|
||||
|
||||
@_lease_locked
|
||||
def release_after_recovery(self, proof) -> bool:
|
||||
"""Restore normal mapping lifetime after this library's release proof."""
|
||||
if not isinstance(proof, dict) or proof.get('status') != 'RELEASE_CONFIRMED':
|
||||
return False
|
||||
candidates = [str(path) for path in (self.display_path, self.mentor_path)
|
||||
if str(path).casefold().endswith('.lmc')]
|
||||
drive, tail = ntpath.splitdrive(str(self.mentor_path))
|
||||
if (self.remote_root and drive.upper() == self.drive.upper()
|
||||
and str(self.mentor_path).casefold().endswith('.lmc')):
|
||||
candidates.append(self.remote_root + tail)
|
||||
library = str(proof.get('library') or '')
|
||||
if not any(_same_remote(library, candidate) for candidate in candidates):
|
||||
return False
|
||||
self._retained_for_recovery = False
|
||||
_retained_path_leases.pop(id(self), None)
|
||||
return True
|
||||
|
||||
@_lease_locked
|
||||
def transfer_ownership(self, other) -> None:
|
||||
"""Keep a shared mapping alive for the currently loaded library."""
|
||||
if (isinstance(other, LibraryPathLease) and not other._closed
|
||||
@@ -237,16 +293,28 @@ class LibraryPathLease:
|
||||
other.created, other._backend = True, self._backend
|
||||
self.created = False
|
||||
|
||||
@_lease_locked
|
||||
def close(self) -> None:
|
||||
if self._closed:
|
||||
return
|
||||
self._closed = True
|
||||
if self._retained_for_recovery or not self.created or self._backend is None or not self.drive:
|
||||
if self._retained_for_recovery:
|
||||
return
|
||||
if not self.created or self._backend is None or not self.drive:
|
||||
self._closed = True
|
||||
return
|
||||
for live in tuple(_live_path_leases.values()):
|
||||
same_backend = (live._backend is self._backend or
|
||||
isinstance(self._backend, WindowsWNetBackend) and isinstance(live._backend, WindowsWNetBackend))
|
||||
if live is not self and not live._closed and same_backend:
|
||||
self.transfer_ownership(live)
|
||||
if not self.created:
|
||||
self._closed = True
|
||||
return
|
||||
try:
|
||||
current = self._backend.mappings().get(self.drive)
|
||||
current = _mapping(self._backend, self.drive)
|
||||
if current and _same_remote(current, self.remote_root):
|
||||
self._backend.cancel_mapping(self.drive)
|
||||
self._closed = True
|
||||
except OSError as error:
|
||||
raise NetworkPathError(
|
||||
f"NETWORK_UNAVAILABLE: 释放临时盘符 {self.drive} 失败: {error}"
|
||||
@@ -257,3 +325,20 @@ class LibraryPathLease:
|
||||
|
||||
def __exit__(self, exc_type, exc_value, traceback) -> None:
|
||||
self.close()
|
||||
|
||||
|
||||
def release_retained_path_leases(proof, *, current_lease=None) -> int:
|
||||
"""Recover matching leases even after the UI dropped its old reference."""
|
||||
released = 0
|
||||
for lease in tuple(_retained_path_leases.values()):
|
||||
if not lease.release_after_recovery(proof):
|
||||
continue
|
||||
if lease is not current_lease:
|
||||
lease.transfer_ownership(current_lease)
|
||||
try:
|
||||
lease.close()
|
||||
except NetworkPathError:
|
||||
_retained_path_leases[id(lease)] = lease
|
||||
raise
|
||||
released += 1
|
||||
return released
|
||||
@@ -0,0 +1,44 @@
|
||||
"""Cooperative FIFO admission for this application's native operations."""
|
||||
from threading import Condition
|
||||
|
||||
|
||||
class QueueCancelled(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
class NativeQueue:
|
||||
def __init__(self):
|
||||
self.condition = Condition()
|
||||
self.pending = []
|
||||
self.active = False
|
||||
|
||||
def wake(self):
|
||||
with self.condition: self.condition.notify_all()
|
||||
|
||||
def run(self, action, *, stop=None, waiting=None, ready=lambda: True):
|
||||
ticket = object()
|
||||
acquired, notified = False, False
|
||||
with self.condition: self.pending.append((ticket, ready))
|
||||
try:
|
||||
while not acquired:
|
||||
with self.condition:
|
||||
if stop is not None and stop.is_set():
|
||||
raise QueueCancelled('已取消排队,未启动原生操作。')
|
||||
first = next((token for token, available in self.pending if available()), None)
|
||||
if not self.active and first is ticket:
|
||||
self.pending = [entry for entry in self.pending if entry[0] is not ticket]
|
||||
self.active = acquired = True
|
||||
else:
|
||||
self.condition.wait(.1)
|
||||
if not acquired and not notified and waiting is not None:
|
||||
notified = True
|
||||
try: waiting()
|
||||
except Exception: pass
|
||||
if stop is not None and stop.is_set():
|
||||
raise QueueCancelled('已取消排队,未启动原生操作。')
|
||||
return action()
|
||||
finally:
|
||||
with self.condition:
|
||||
self.pending = [entry for entry in self.pending if entry[0] is not ticket]
|
||||
if acquired: self.active = False
|
||||
self.condition.notify_all()
|
||||
@@ -11,9 +11,20 @@ def query_owners(names, *, timeout_seconds=10):
|
||||
names = tuple(names)
|
||||
if not names or any(not re.fullmatch(r'[\w.-]+\.exe', name, re.I) for name in names):
|
||||
raise ValueError('OWNER_QUERY_INVALID')
|
||||
return _query_processes(names, timeout_seconds=timeout_seconds)
|
||||
|
||||
|
||||
def query_process_snapshot(*, timeout_seconds=10):
|
||||
"""Bound a complete process tree; retain unknown executable descendants."""
|
||||
return _query_processes(None, timeout_seconds=timeout_seconds)
|
||||
|
||||
|
||||
def _query_processes(names, *, timeout_seconds):
|
||||
full_snapshot = names is None
|
||||
request = {'snapshot_version': 1} if full_snapshot else {'names': names}
|
||||
with tempfile.TemporaryDirectory(prefix='cbb-owner-probe-') as directory:
|
||||
job = Path(directory)/'request.json'
|
||||
job.write_text(json.dumps({'names': names}), encoding='utf-8')
|
||||
job.write_text(json.dumps(request), encoding='utf-8')
|
||||
command = ([sys.executable] if getattr(sys, 'frozen', False) else
|
||||
[sys.executable, '-m', 'cbb_refresh_verify']) + ['--owner-probe', str(job)]
|
||||
try:
|
||||
@@ -27,13 +38,20 @@ def query_owners(names, *, timeout_seconds=10):
|
||||
try:
|
||||
record = json.loads(job.with_name('result.json').read_text('utf-8'))
|
||||
rows = record['owners']
|
||||
if result.returncode != 0 or record['names'] != list(names) or not isinstance(rows, list):
|
||||
identity_matches = (type(record.get('snapshot_version')) is int and record['snapshot_version'] == 1
|
||||
if full_snapshot else record.get('names') == list(names))
|
||||
if result.returncode != 0 or not identity_matches or not isinstance(rows, list):
|
||||
raise ValueError('invalid result')
|
||||
seen = set()
|
||||
for row in rows:
|
||||
if (type(row['pid']) is not int or row['pid'] <= 0 or row['name'].casefold() not in {n.casefold() for n in names}
|
||||
if (type(row['pid']) is not int or row['pid'] < (0 if full_snapshot else 1)
|
||||
or row['pid'] in seen or not isinstance(row['name'], str) or not row['name']
|
||||
or not full_snapshot and row['name'].casefold() not in {n.casefold() for n in names}
|
||||
or full_snapshot and not isinstance(row['created'], str)
|
||||
or not isinstance(row['command'], str) or not isinstance(row['executable'], str)
|
||||
or type(row['parent']) is not int or row['parent'] < 0):
|
||||
raise ValueError('invalid owner')
|
||||
seen.add(row['pid'])
|
||||
return rows
|
||||
except (OSError, ValueError, KeyError, TypeError, AttributeError) as error:
|
||||
raise RuntimeError('OWNER_QUERY_UNCONFIRMED: 进程查询未返回有效证据') from error
|
||||
@@ -43,19 +61,28 @@ def owner_probe_main(job):
|
||||
import pythoncom
|
||||
import win32com.client
|
||||
job = Path(job)
|
||||
names = json.loads(job.read_text('utf-8'))['names']
|
||||
if not names or any(not re.fullmatch(r'[\w.-]+\.exe', name, re.I) for name in names):
|
||||
return 1
|
||||
request = json.loads(job.read_text('utf-8'))
|
||||
full_snapshot = request == {'snapshot_version': 1} and type(request.get('snapshot_version')) is int
|
||||
names = request.get('names')
|
||||
if not full_snapshot:
|
||||
if (not isinstance(names, list) or not names
|
||||
or any(not isinstance(name, str) or not re.fullmatch(r'[\w.-]+\.exe', name, re.I) for name in names)):
|
||||
return 1
|
||||
pythoncom.CoInitialize()
|
||||
try:
|
||||
service = win32com.client.GetObject('winmgmts:')
|
||||
query = 'SELECT ProcessId,Name,CommandLine,ExecutablePath,ParentProcessId FROM Win32_Process WHERE ' + ' OR '.join(
|
||||
f"Name='{name}'" for name in names)
|
||||
query = ('SELECT ProcessId,Name,CommandLine,ExecutablePath,ParentProcessId' +
|
||||
(',CreationDate' if full_snapshot else '') + ' FROM Win32_Process')
|
||||
if not full_snapshot:
|
||||
query += ' WHERE ' + ' OR '.join(f"Name='{name}'" for name in names)
|
||||
rows = [{'pid': int(item.ProcessId), 'name': str(item.Name),
|
||||
'command': str(item.CommandLine or ''), 'executable': str(item.ExecutablePath or ''),
|
||||
'parent': int(item.ParentProcessId or 0)} for item in service.ExecQuery(query)]
|
||||
'parent': int(item.ParentProcessId or 0),
|
||||
**({'created': str(item.CreationDate or '')} if full_snapshot else {})}
|
||||
for item in service.ExecQuery(query)]
|
||||
service = None
|
||||
job.with_name('result.json').write_text(json.dumps({'names': names, 'owners': rows}), encoding='utf-8')
|
||||
response = {'snapshot_version': 1} if full_snapshot else {'names': names}
|
||||
job.with_name('result.json').write_text(json.dumps({**response, 'owners': rows}), encoding='utf-8')
|
||||
return 0
|
||||
finally:
|
||||
pythoncom.CoUninitialize()
|
||||
@@ -91,6 +91,35 @@ def require_document_identity(document, job):
|
||||
return integration
|
||||
|
||||
|
||||
class ProcessWatch:
|
||||
"""Hold this task's native handles; repeated COM attach polls never run WMI."""
|
||||
def __init__(self, pids):
|
||||
self.pids = set(int(pid) for pid in pids if pid)
|
||||
self.handles = None
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def alive(self):
|
||||
import pywintypes, win32api, win32con, win32event
|
||||
if self.handles is None:
|
||||
self.handles = []
|
||||
try:
|
||||
for pid in self.pids:
|
||||
try:
|
||||
self.handles.append(win32api.OpenProcess(win32con.SYNCHRONIZE, False, pid))
|
||||
except pywintypes.error as error:
|
||||
if error.winerror != 87: raise
|
||||
except Exception:
|
||||
self.__exit__(None, None, None)
|
||||
raise
|
||||
return any(win32event.WaitForSingleObject(h, 0) != win32con.WAIT_OBJECT_0 for h in self.handles)
|
||||
|
||||
def __exit__(self, *_):
|
||||
for handle in self.handles or (): handle.Close()
|
||||
self.handles = []
|
||||
|
||||
|
||||
def wait_for_target_document(job, app_provider, *, process_alive, emit=lambda **event: None,
|
||||
error_reader=None, sleep=time.sleep):
|
||||
"""Wait for the exact launched document; the parent process owns timeout."""
|
||||
|
||||
@@ -0,0 +1,379 @@
|
||||
"""Preview and cooperatively close the exact native sessions a user confirms."""
|
||||
from contextlib import contextmanager
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import time
|
||||
from uuid import uuid4
|
||||
|
||||
from .owner_probe import query_process_snapshot
|
||||
from .native_engineering_identity import _OWNER_NAMES
|
||||
|
||||
_NAMES = {'expeditionpcb.exe', 'librarymanager.exe', 'icdbprojectbackup.exe',
|
||||
'viewdraw.exe', 'icdbnetserver.exe', 'icdbserver.exe',
|
||||
'reuseblockimporter.exe', 'cleanwglib.exe', 'cscript.exe', 'wscript.exe'} | _OWNER_NAMES
|
||||
_WORKER_NAMES = {'python.exe', 'pythonw.exe', 'cbbrefreshverify.exe'}
|
||||
_WORKER_FLAGS = ('--verify-worker', '--repair-worker', '--management-worker', '--native-backup-worker')
|
||||
|
||||
|
||||
@contextmanager
|
||||
def _process_handle(pid, *, terminate=False):
|
||||
import win32api, win32con
|
||||
handle = win32api.OpenProcess(win32con.SYNCHRONIZE | 0x1000 | (1 if terminate else 0), False, int(pid))
|
||||
try:
|
||||
yield handle
|
||||
finally:
|
||||
handle.Close()
|
||||
|
||||
|
||||
def _handle_identity(handle):
|
||||
import ctypes
|
||||
from ctypes import wintypes
|
||||
import win32process
|
||||
kernel = ctypes.WinDLL('kernel32', use_last_error=True)
|
||||
kernel.QueryFullProcessImageNameW.argtypes = [wintypes.HANDLE, wintypes.DWORD,
|
||||
wintypes.LPWSTR, ctypes.POINTER(wintypes.DWORD)]
|
||||
kernel.QueryFullProcessImageNameW.restype = wintypes.BOOL
|
||||
buffer = ctypes.create_unicode_buffer(32768)
|
||||
length = wintypes.DWORD(len(buffer))
|
||||
if not kernel.QueryFullProcessImageNameW(int(handle), 0, buffer, ctypes.byref(length)):
|
||||
raise ctypes.WinError(ctypes.get_last_error())
|
||||
return {'created_handle': win32process.GetProcessTimes(handle)['CreationTime'].isoformat(),
|
||||
'image': buffer.value}
|
||||
|
||||
|
||||
def _process_identity(row):
|
||||
with _process_handle(row['pid']) as handle:
|
||||
return _handle_identity(handle)
|
||||
|
||||
|
||||
def _process_windows(pids):
|
||||
if not pids: return {}
|
||||
import win32api, win32con, win32gui, win32process, win32service
|
||||
from .native_repair_ui import _native_output
|
||||
result = {pid: [] for pid in pids}
|
||||
observed = set()
|
||||
def capture(hwnd, _=None):
|
||||
pid = win32process.GetWindowThreadProcessId(hwnd)[1]
|
||||
if pid not in result or hwnd in observed or not win32gui.IsWindowVisible(hwnd):
|
||||
return
|
||||
observed.add(hwnd)
|
||||
children, documents = [], []
|
||||
def child(handle, _):
|
||||
kind = win32gui.GetClassName(handle)
|
||||
if kind == 'MDIClient' and win32gui.GetWindow(handle, win32con.GW_CHILD):
|
||||
documents.append(handle)
|
||||
if win32gui.IsWindowVisible(handle):
|
||||
children.append({'hwnd': int(handle), 'class': kind,
|
||||
'id': win32gui.GetDlgCtrlID(handle) & 0xffff,
|
||||
'text': win32gui.GetWindowText(handle), 'enabled': bool(win32gui.IsWindowEnabled(handle))})
|
||||
win32api.SetLastError(0)
|
||||
win32gui.EnumChildWindows(hwnd, child, None)
|
||||
window = {'hwnd': int(hwnd), 'title': win32gui.GetWindowText(hwnd),
|
||||
'class': win32gui.GetClassName(hwnd), 'enabled': bool(win32gui.IsWindowEnabled(hwnd)),
|
||||
'children': children, 'documents': documents, 'rect': list(win32gui.GetWindowRect(hwnd))}
|
||||
if any(c['class'].casefold().startswith('richedit') for c in children):
|
||||
window['output'] = _native_output([window])
|
||||
result[pid].append(window)
|
||||
win32api.SetLastError(0)
|
||||
def incomplete():
|
||||
for pid in result:
|
||||
result[pid].append({'hwnd': 0, 'title': '窗口状态读取不完整', 'class': 'UNCONFIRMED',
|
||||
'enabled': False, 'children': []})
|
||||
try:
|
||||
win32gui.EnumWindows(capture, None)
|
||||
except Exception:
|
||||
incomplete()
|
||||
try:
|
||||
desktops = win32service.GetProcessWindowStation().EnumDesktops()
|
||||
except Exception:
|
||||
incomplete()
|
||||
return result
|
||||
for name in desktops:
|
||||
if name != 'Default' and not name.startswith(('CbbVerify_', 'CbbRepair_', 'CbbManagement_', 'CbbStatusRead_', 'CbbFlagRead_')):
|
||||
continue
|
||||
desktop = None
|
||||
try:
|
||||
desktop = win32service.OpenDesktop(name, 0, False, win32con.DESKTOP_READOBJECTS)
|
||||
for hwnd in desktop.EnumDesktopWindows(): capture(int(hwnd))
|
||||
except Exception:
|
||||
incomplete()
|
||||
finally:
|
||||
if desktop is not None: desktop.CloseDesktop()
|
||||
return result
|
||||
|
||||
|
||||
def _project_name(row, library):
|
||||
from .failed_session import _command_args
|
||||
for arg in _command_args(row['command'])[1:]:
|
||||
try:
|
||||
relative = Path(arg.split('=', 1)[-1]).relative_to(library.parent/'ReusableBlocksLP')
|
||||
if len(relative.parts) >= 2 and relative.parts[1].casefold() == 'work':
|
||||
return relative.parts[0]
|
||||
except ValueError:
|
||||
continue
|
||||
return '当前库关联会话'
|
||||
|
||||
|
||||
def close_target(name, windows):
|
||||
"""No save/restore approval and no close against an unknown modal/window."""
|
||||
main = [w for w in windows if w['class'].startswith('Afx:') and (
|
||||
name.casefold() == 'icdbprojectbackup.exe' and w['title'].startswith('iCDB Project Backup')
|
||||
or name.casefold() == 'librarymanager.exe' and w['title'].startswith('Library Manager')
|
||||
or name.casefold() == 'expeditionpcb.exe' and 'Expedition PCB' in w['title'])]
|
||||
if len(main) != 1:
|
||||
return None, '未确认空闲主窗口;有工程时请先在原生窗口保存并关闭'
|
||||
window = main[0]
|
||||
for other in windows:
|
||||
if other is window: continue
|
||||
benign = (not other['title'] and other['class'] in
|
||||
('UAC_InputIndicatorOverlayWnd', 'UAC Input Indicator'))
|
||||
benign = benign or (other['class'] == 'Internet Explorer_Hidden' and not other['title']
|
||||
and not other.get('children') and other.get('rect', [1, 1, 2, 2])[0:2] == other.get('rect', [1, 1, 2, 2])[2:4])
|
||||
if not benign: return None, '存在原生弹窗,请先处理该窗口后重新检查'
|
||||
if not window['enabled']:
|
||||
return None, '原生程序正在工作,请稍后重新检查'
|
||||
if any(c['class'].casefold() == 'msctls_progress32' for c in window['children']):
|
||||
return None, '原生操作尚未结束'
|
||||
if name.casefold() == 'icdbprojectbackup.exe':
|
||||
output = window.get('output')
|
||||
if not isinstance(output, str): return None, '原生输出尚无法确认,请重新检查'
|
||||
active = list(re.finditer(r'(?i)repairing|restoring|backing up|creating (?:a )?backup', output))
|
||||
last_load = output.rfind('Backup information loaded correctly.')
|
||||
failure = output.rfind('Repair project error [')
|
||||
if active and max(last_load, failure) < active[-1].start():
|
||||
return None, '备份、恢复或修复需要在原生窗口确认结束后再释放'
|
||||
return window, ('将正常关闭工程;未保存时等待确认' if window.get('documents') else '可正常关闭')
|
||||
|
||||
|
||||
def _save_question(windows):
|
||||
for window in windows:
|
||||
text = '\n'.join(c['text'] for c in window['children'] if c['class'] == 'Static')
|
||||
buttons = {c['id']: c for c in window['children'] if c['class'] == 'Button' and c['enabled']}
|
||||
if (window['class'] == '#32770' and 'Expedition' in window['title']
|
||||
and re.search(r'\bsave\b', text, re.I) and re.search(r'changes|modified', text, re.I)
|
||||
and set(buttons) == {6, 7, 2}):
|
||||
return {'hwnd': window['hwnd'], 'text': text, 'buttons': buttons}
|
||||
return None
|
||||
|
||||
|
||||
def inspect_residual_sessions(library, *, block_names=()):
|
||||
from .library_lock import _owner_matches_scope, blocker_path, checkpoint_record, has_retained_library
|
||||
library = Path(library).resolve()
|
||||
if library.suffix.casefold() != '.lmc' or not library.is_file():
|
||||
raise ValueError('请选择有效的中心库 .lmc 文件')
|
||||
blocks = tuple(dict.fromkeys(str(name) for name in block_names))
|
||||
if any(not name or name in ('.', '..') or any(c in name for c in '\\/:*?"<>|') for name in blocks):
|
||||
raise ValueError('残留检查的工程名称无效')
|
||||
roots = tuple(library.parent/'ReusableBlocksLP'/b/'Work' for b in blocks) + (library.parent/'SymbolLibs',)
|
||||
if not blocks: roots = (library.parent,)
|
||||
candidates = []
|
||||
for row in query_process_snapshot():
|
||||
if row['pid'] == os.getpid(): continue
|
||||
native = row['name'].casefold() in _NAMES
|
||||
worker = (row['name'].casefold() in _WORKER_NAMES
|
||||
and any(flag in row['command'].casefold() for flag in _WORKER_FLAGS))
|
||||
if not (native or worker): continue
|
||||
scope = _owner_matches_scope(row, library, roots)
|
||||
if scope is not False:
|
||||
candidates.append({**row, 'scope_confirmed': scope is True})
|
||||
windows = _process_windows({r['pid'] for r in candidates})
|
||||
sessions = []
|
||||
for row in candidates:
|
||||
item = dict(row)
|
||||
try:
|
||||
item.update(_process_identity(row))
|
||||
target, detail = close_target(row['name'], windows.get(row['pid'], [])) if row['scope_confirmed'] else (
|
||||
None, '归属未确认,请在原生窗口确认工程并关闭后重新检查')
|
||||
item.update(can_close=target is not None, detail=detail)
|
||||
except Exception as error:
|
||||
item.update(can_close=False, detail=f'进程已变化或暂时无法确认:{error}')
|
||||
item['project'] = _project_name(row, library) if row['scope_confirmed'] else '归属未确认'
|
||||
item['prompt'] = _save_question(windows.get(row['pid'], [])) if row['scope_confirmed'] else None
|
||||
sessions.append(item)
|
||||
previous = []
|
||||
marker = blocker_path(library)
|
||||
for path in (marker, marker.with_suffix('.pending')):
|
||||
if path.exists():
|
||||
record = checkpoint_record(path)
|
||||
previous.append({'path': str(path), 'recognized': record is not None,
|
||||
'status': record.get('status', 'UNRECOGNIZED') if record else 'UNRECOGNIZED',
|
||||
'time': record.get('time', '') if record else '',
|
||||
'pid': record.get('pid') if record else None})
|
||||
if has_retained_library(library):
|
||||
previous.append({'path': str(library), 'status': 'RETAINED_IN_MEMORY', 'time': '',
|
||||
'pid': os.getpid(), 'kind': 'in_memory'})
|
||||
return {'library': str(library), 'block_names': list(blocks), 'sessions': sessions,
|
||||
'previous_records': previous}
|
||||
|
||||
|
||||
def _request_close(row, *, stop=None):
|
||||
import win32con, win32event, win32gui, win32process
|
||||
with _process_handle(row['pid']) as handle:
|
||||
if win32event.WaitForSingleObject(handle, 0) == win32con.WAIT_OBJECT_0:
|
||||
return {'release_status': 'RELEASED', 'detail': '已退出'}
|
||||
identity = _handle_identity(handle)
|
||||
if identity != {key: row.get(key) for key in ('created_handle', 'image')}:
|
||||
return {'release_status': 'IDENTITY_CHANGED', 'detail': '进程身份已变化,未关闭'}
|
||||
windows = _process_windows({row['pid']}).get(row['pid'], [])
|
||||
if row['name'].casefold() == 'expeditionpcb.exe':
|
||||
from .failed_session import _startup_snapshot, _cancel_target
|
||||
for window in windows:
|
||||
if window['class'] != '#32770': continue
|
||||
target = _cancel_target(_startup_snapshot(window['hwnd'], row['pid']))
|
||||
if target:
|
||||
win32gui.PostMessage(target[1].handle, win32con.BM_CLICK, 0, 0)
|
||||
deadline = time.monotonic()+3
|
||||
while time.monotonic() < deadline:
|
||||
if win32event.WaitForSingleObject(handle, 100) == win32con.WAIT_OBJECT_0:
|
||||
return {'release_status': 'RELEASED', 'detail': '已取消启动并退出'}
|
||||
if stop is not None and stop.is_set():
|
||||
return {'release_status': 'CANCELLED', 'detail': '已停止释放'}
|
||||
windows = _process_windows({row['pid']}).get(row['pid'], [])
|
||||
if close_target(row['name'], windows)[0] is not None: break
|
||||
break
|
||||
target, detail = close_target(row['name'], windows)
|
||||
if target is None: return {'release_status': 'WAITING', 'detail': detail}
|
||||
if stop is not None and stop.is_set():
|
||||
return {'release_status': 'CANCELLED', 'detail': '已停止释放'}
|
||||
if win32process.GetWindowThreadProcessId(target['hwnd'])[1] != row['pid']:
|
||||
return {'release_status': 'IDENTITY_CHANGED', 'detail': '窗口归属已变化,未关闭'}
|
||||
win32gui.PostMessage(target['hwnd'], win32con.WM_CLOSE, 0, 0)
|
||||
deadline = time.monotonic()+3
|
||||
while time.monotonic() < deadline:
|
||||
if win32event.WaitForSingleObject(handle, 100) == win32con.WAIT_OBJECT_0:
|
||||
return {'release_status': 'RELEASED', 'detail': '已正常退出'}
|
||||
if stop is not None and stop.is_set(): break
|
||||
return {'release_status': 'WAITING', 'detail': '已请求正常关闭;请处理原生窗口,完成后重新检查'}
|
||||
|
||||
|
||||
def _force_close(row, *, stop=None):
|
||||
"""Separate UI consent permits ending only this exact, scoped process handle."""
|
||||
import win32api, win32con, win32event
|
||||
if stop is not None and stop.is_set():
|
||||
return {'release_status': 'CANCELLED', 'detail': '已停止释放'}
|
||||
with _process_handle(row['pid'], terminate=True) as handle:
|
||||
if win32event.WaitForSingleObject(handle, 0) == win32con.WAIT_OBJECT_0:
|
||||
return {'release_status': 'RELEASED', 'detail': '已退出'}
|
||||
if _handle_identity(handle) != {k: row.get(k) for k in ('created_handle', 'image')}:
|
||||
return {'release_status': 'IDENTITY_CHANGED', 'detail': '进程身份已变化,未结束'}
|
||||
win32api.TerminateProcess(handle, 1)
|
||||
exited = win32event.WaitForSingleObject(handle, 3000) == win32con.WAIT_OBJECT_0
|
||||
return {'release_status': 'RELEASED' if exited else 'WAITING',
|
||||
'detail': '已强制结束,工程需重新检查' if exited else '已请求结束,等待退出'}
|
||||
|
||||
|
||||
def _finish_library_release(library, evidence):
|
||||
from .library_lock import release_retained_library
|
||||
return release_retained_library(library, evidence)
|
||||
|
||||
|
||||
def _release_residual_sessions(plan, evidence_dir, *, stop=None, force=False):
|
||||
library = Path(plan['library']).resolve()
|
||||
root = Path(evidence_dir).resolve()/('sessions-'+uuid4().hex[:12])
|
||||
if root.is_relative_to(library.parent) or library.parent.is_relative_to(root):
|
||||
raise ValueError('释放记录需位于中心库之外')
|
||||
root.mkdir(parents=True)
|
||||
result = {'status': 'PARTIAL', 'library': str(library), 'sessions': [], 'force': force,
|
||||
'evidence_path': str(root/'result.json'), 'previous_records': plan.get('previous_records', [])}
|
||||
fresh = {r['pid']: r for r in query_process_snapshot()}
|
||||
# Close native children first, so their supervisors can finish and drop leases.
|
||||
ordered = sorted(plan['sessions'], key=lambda r: r['name'].casefold() in _WORKER_NAMES)
|
||||
for original in ordered:
|
||||
current = fresh.get(original['pid'])
|
||||
outcome = {'release_status': 'RELEASED', 'detail': '已退出'}
|
||||
if stop is not None and stop.is_set():
|
||||
outcome = {'release_status': 'CANCELLED', 'detail': '已停止释放'}
|
||||
elif current is not None:
|
||||
from .library_lock import _owner_matches_scope
|
||||
scoped = _owner_matches_scope(current, library, (library.parent,)) is True
|
||||
if original.get('scope_confirmed') is not True or not scoped or original['pid'] == os.getpid():
|
||||
outcome = {'release_status': 'WAITING', 'detail': '未在确认名单中证明属于当前库,未关闭;请重新检查'}
|
||||
elif any(current.get(key) != original.get(key) for key in ('created', 'executable', 'command', 'name')):
|
||||
outcome = {'release_status': 'IDENTITY_CHANGED', 'detail': '确认后进程身份已变化,未关闭'}
|
||||
else:
|
||||
try: outcome = (_force_close if force else _request_close)(original, stop=stop)
|
||||
except Exception as error:
|
||||
outcome = {'release_status': 'WAITING', 'detail': str(error)}
|
||||
result['sessions'].append({**original, **outcome})
|
||||
by_pid = {r['pid']: r for r in result['sessions']}
|
||||
result['sessions'] = [by_pid[r['pid']] for r in plan['sessions']]
|
||||
# Launchers may exit only after the GUI child processed its close request.
|
||||
after = {r['pid']: r for r in query_process_snapshot()}
|
||||
remaining_windows = _process_windows({r['pid'] for r in result['sessions']
|
||||
if r['release_status'] == 'WAITING' and r['pid'] in after})
|
||||
for row in result['sessions']:
|
||||
if row['release_status'] == 'WAITING' and row['pid'] not in after:
|
||||
row.update(release_status='RELEASED', detail='已退出')
|
||||
elif row['release_status'] == 'WAITING':
|
||||
row['prompt'] = _save_question(remaining_windows.get(row['pid'], []))
|
||||
if all(row['release_status'] == 'RELEASED' for row in result['sessions']) and not (stop and stop.is_set()):
|
||||
try:
|
||||
result['proof'] = _finish_library_release(library, root/'library-proof')
|
||||
proof = result['proof']
|
||||
if (proof.get('status') != 'RELEASE_CONFIRMED'
|
||||
or Path(proof.get('library', '')).resolve() != library):
|
||||
raise ValueError('释放证明与当前库不一致')
|
||||
result['status'] = 'RELEASE_CONFIRMED'
|
||||
except Exception as error:
|
||||
result['detail'] = str(error)
|
||||
try:
|
||||
(root/'result.json').write_text(json.dumps(result, ensure_ascii=False, indent=2), 'utf-8')
|
||||
except OSError as error:
|
||||
result['evidence_error'] = str(error)
|
||||
return result
|
||||
|
||||
|
||||
def release_residual_sessions(plan, evidence_dir, *, stop=None, force=False):
|
||||
import win32con, win32event
|
||||
mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795')
|
||||
acquired = False
|
||||
try:
|
||||
deadline = time.monotonic()+15
|
||||
while time.monotonic() < deadline and not (stop and stop.is_set()):
|
||||
acquired = win32event.WaitForSingleObject(mutex, 0) in (win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED)
|
||||
if acquired: break
|
||||
time.sleep(.2)
|
||||
if not acquired:
|
||||
return {'status': 'PARTIAL', 'library': plan['library'], 'sessions': [
|
||||
{**r, 'release_status': 'WAITING', 'detail': '其它批次尚在执行;请停止该批次后重试'}
|
||||
for r in plan['sessions']], 'detail': '未取得执行通道,未关闭任何进程。'}
|
||||
return _release_residual_sessions(plan, evidence_dir, stop=stop, force=force)
|
||||
finally:
|
||||
if acquired: win32event.ReleaseMutex(mutex)
|
||||
mutex.Close()
|
||||
|
||||
|
||||
def answer_save_question(row, choice):
|
||||
"""Only the exact displayed save question receives an explicit user answer."""
|
||||
import win32con, win32event, win32gui
|
||||
if choice not in (6, 7, 2): raise ValueError('无效的保存选择')
|
||||
mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795')
|
||||
acquired = win32event.WaitForSingleObject(mutex, 0) in (win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED)
|
||||
if not acquired:
|
||||
mutex.Close()
|
||||
raise ValueError('其它批次正在执行,请稍后处理保存提示')
|
||||
try:
|
||||
_answer_save_question(row, choice)
|
||||
finally:
|
||||
win32event.ReleaseMutex(mutex)
|
||||
mutex.Close()
|
||||
|
||||
|
||||
def _answer_save_question(row, choice):
|
||||
import win32con, win32gui
|
||||
fresh = next((r for r in query_process_snapshot() if r['pid'] == row['pid']), None)
|
||||
if fresh is None or any(fresh.get(k) != row.get(k) for k in ('created', 'command', 'executable')):
|
||||
raise ValueError('进程已变化,请重新检查')
|
||||
with _process_handle(row['pid']) as handle:
|
||||
if _handle_identity(handle) != {k: row.get(k) for k in ('created_handle', 'image')}:
|
||||
raise ValueError('进程已变化,请重新检查')
|
||||
prompt = _save_question(_process_windows({row['pid']}).get(row['pid'], []))
|
||||
if not prompt or prompt != row.get('prompt'):
|
||||
raise ValueError('原生提示已变化,请重新检查')
|
||||
button = prompt['buttons'][choice]
|
||||
import win32process
|
||||
if win32process.GetWindowThreadProcessId(button['hwnd'])[1] != row['pid']:
|
||||
raise ValueError('保存按钮归属已变化')
|
||||
win32gui.PostMessage(button['hwnd'], win32con.BM_CLICK, 0, 0)
|
||||
@@ -58,6 +58,11 @@ class RunTimings:
|
||||
elif stage == 'identity_verified':
|
||||
self.end('pcb_startup', now)
|
||||
self.begin('integration', now)
|
||||
elif stage == 'diagnostic_native_loaded_candidate':
|
||||
self.end('pcb_startup', now)
|
||||
self.begin('diagnostic_close', now)
|
||||
elif stage == 'diagnostic_complete':
|
||||
self.end('diagnostic_close', now)
|
||||
elif stage == 'integration_action':
|
||||
key = ACTION_KEYS.get(event.get('action'))
|
||||
if key:
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
"""Small, asynchronous entry point for recovery from a healthy CBB project."""
|
||||
from pathlib import Path
|
||||
from threading import Event
|
||||
|
||||
from PySide6.QtCore import QObject, QThreadPool, Signal
|
||||
from PySide6.QtWidgets import (QComboBox, QDialog, QFileDialog, QFormLayout,
|
||||
@@ -23,6 +24,8 @@ class BackupRecoveryDialog(QDialog):
|
||||
self.resize(620, 230)
|
||||
self.request_factory = request_factory
|
||||
self.recoverer = recoverer
|
||||
self.native_queue = None
|
||||
self.stop = Event()
|
||||
self.busy = False
|
||||
self.pool = QThreadPool(self)
|
||||
self.pool.setMaxThreadCount(1)
|
||||
@@ -38,6 +41,9 @@ class BackupRecoveryDialog(QDialog):
|
||||
self.restore_button.clicked.connect(self._restore)
|
||||
self.close_button = QPushButton('关闭')
|
||||
self.close_button.clicked.connect(self.reject)
|
||||
self.cancel_queue_button = QPushButton('取消排队')
|
||||
self.cancel_queue_button.setEnabled(False)
|
||||
self.cancel_queue_button.clicked.connect(self.stop.set)
|
||||
self.status_label = QLabel(MANUAL_BACKUP_NOTICE + ' 所选备份先在隔离库中验证;安装时旧 Work 仅改名保留。')
|
||||
self.status_label.setWordWrap(True)
|
||||
layout = QFormLayout(self)
|
||||
@@ -50,6 +56,7 @@ class BackupRecoveryDialog(QDialog):
|
||||
buttons = QHBoxLayout()
|
||||
buttons.addStretch()
|
||||
buttons.addWidget(self.restore_button)
|
||||
buttons.addWidget(self.cancel_queue_button)
|
||||
buttons.addWidget(self.close_button)
|
||||
layout.addRow(buttons)
|
||||
|
||||
@@ -84,11 +91,24 @@ class BackupRecoveryDialog(QDialog):
|
||||
QMessageBox.Yes | QMessageBox.No, QMessageBox.No) != QMessageBox.Yes:
|
||||
return
|
||||
self.busy = True
|
||||
self.stop.clear()
|
||||
self._set_enabled(False)
|
||||
self.status_label.setText('正在准备恢复…')
|
||||
self.started.emit(name)
|
||||
self.worker = ServiceWorker(lambda: recoverer(
|
||||
request, source, progress=self.signals.progress.emit))
|
||||
def execute():
|
||||
action = lambda: recoverer(request, source, progress=self.signals.progress.emit)
|
||||
if self.native_queue is None: return action()
|
||||
from ..operation_queue import QueueCancelled
|
||||
def restore():
|
||||
self.signals.progress.emit({'stage': 'queue_acquired'})
|
||||
return action()
|
||||
try:
|
||||
return self.native_queue.run(restore, stop=self.stop, waiting=lambda: self.signals.progress.emit(
|
||||
{'stage': 'waiting_native_slot', 'detail': '已排队,等待当前检查结束'}))
|
||||
except QueueCancelled as error:
|
||||
from ..verify_runner import VerifyResult
|
||||
return VerifyResult('CANCELLED', stderr=str(error))
|
||||
self.worker = ServiceWorker(execute)
|
||||
self.worker.signals.succeeded.connect(lambda result: self._result(name, result))
|
||||
self.worker.signals.failed.connect(lambda error: self._failed(name, error))
|
||||
self.worker.signals.finished.connect(self._finished)
|
||||
@@ -101,6 +121,8 @@ class BackupRecoveryDialog(QDialog):
|
||||
|
||||
def _progress(self, event):
|
||||
if isinstance(event, dict):
|
||||
if event.get('stage') in ('waiting_native_slot', 'queue_acquired'):
|
||||
self.cancel_queue_button.setEnabled(event['stage'] == 'waiting_native_slot')
|
||||
message = event.get('message') or event.get('detail')
|
||||
if message:
|
||||
self.status_label.setText(str(message))
|
||||
@@ -121,6 +143,7 @@ class BackupRecoveryDialog(QDialog):
|
||||
|
||||
def _finished(self):
|
||||
self.busy = False
|
||||
self.cancel_queue_button.setEnabled(False)
|
||||
self._set_enabled(True)
|
||||
|
||||
def reject(self):
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
"""A check batch owns its snapshot and yields the native queue after each CBB."""
|
||||
from threading import Event
|
||||
from PySide6.QtCore import QObject, QThreadPool, Signal
|
||||
from .workers import ServiceWorker
|
||||
from ..operation_queue import QueueCancelled
|
||||
from ..verify_runner import VerifyResult, run_verify, write_batch_report
|
||||
from ..icdb_maintenance import write_maintenance_report
|
||||
|
||||
|
||||
class IcdbCheckTask(QObject):
|
||||
event = Signal(object)
|
||||
item_done = Signal(str, object)
|
||||
finished = Signal(object)
|
||||
|
||||
def __init__(self, requests, queue, report_root, *, verifier=None, path_lease=None, parent=None):
|
||||
super().__init__(parent)
|
||||
self.requests = tuple(requests)
|
||||
self.queue, self.report_root = queue, report_root
|
||||
self.path_lease = path_lease
|
||||
self.verifier = verifier or (lambda req: run_verify(req, progress=self.event.emit, stop=self.stop))
|
||||
self.results = []
|
||||
self.stop = Event()
|
||||
self.active = False
|
||||
self.paused = False
|
||||
self.invalidated = set()
|
||||
self.ready_names = set()
|
||||
self.running = False
|
||||
self.report = None
|
||||
self.report_error = ''
|
||||
self.pool = QThreadPool(self); self.pool.setMaxThreadCount(1)
|
||||
|
||||
def start(self):
|
||||
self.active = True
|
||||
self._next()
|
||||
|
||||
def cancel(self):
|
||||
self.stop.set(); self.queue.wake()
|
||||
if not self.running and self.active: self._next()
|
||||
|
||||
def pause(self):
|
||||
self.paused = True
|
||||
|
||||
def invalidate(self, names):
|
||||
self.invalidated.update(names)
|
||||
|
||||
def update_statuses(self, statuses):
|
||||
self.ready_names = (self.ready_names - statuses.keys()) | {
|
||||
name for name, status in statuses.items() if status == 'READY'}
|
||||
|
||||
def resume(self):
|
||||
self.paused = False; self.queue.wake()
|
||||
if not self.running and self.active: self._next()
|
||||
|
||||
def _next(self):
|
||||
if self.running or not self.active: return
|
||||
if self.stop.is_set() or self.results and not self.results[-1].safe_to_continue:
|
||||
self.results.extend(VerifyResult('SKIPPED', stderr='队列已停止,未操作此 CBB')
|
||||
for _ in self.requests[len(self.results):])
|
||||
if len(self.results) == len(self.requests):
|
||||
self._report(); return
|
||||
if self.paused: return
|
||||
request = self.requests[len(self.results)]
|
||||
def check():
|
||||
try:
|
||||
def execute():
|
||||
if request.block_name in self.ready_names:
|
||||
return VerifyResult('SKIPPED', stderr='工程已为 READY,跳过 ICDB 检查。')
|
||||
if request.block_name in self.invalidated:
|
||||
return VerifyResult('SKIPPED', stderr='目标已有后续管理操作,请重新检查。')
|
||||
self.event.emit({'stage': 'icdb_check_start', 'block': request.block_name})
|
||||
return self.verifier(request)
|
||||
return self.queue.run(execute, stop=self.stop, ready=lambda: not self.paused,
|
||||
waiting=lambda: self.event.emit({'stage': 'waiting_native_slot', 'block': request.block_name,
|
||||
'detail': '已排队,等待当前原生操作结束'}))
|
||||
except QueueCancelled as error:
|
||||
return VerifyResult('CANCELLED', stderr=str(error))
|
||||
except Exception as error:
|
||||
return VerifyResult('FAIL', stderr=str(error), safe_to_continue=False,
|
||||
error_category='ICDB_INSPECTION_UNCONFIRMED')
|
||||
self.running = True
|
||||
self.worker = ServiceWorker(check)
|
||||
self.worker.signals.succeeded.connect(self._record)
|
||||
self.worker.signals.finished.connect(self._item_finished)
|
||||
self.pool.start(self.worker)
|
||||
|
||||
def _record(self, result):
|
||||
name = self.requests[len(self.results)].block_name
|
||||
self.results.append(result)
|
||||
if result.status in ('CANCELLED', 'QUEUE_STOP'): self.stop.set()
|
||||
self.item_done.emit(name, result)
|
||||
|
||||
def _item_finished(self):
|
||||
self.running = False
|
||||
self._next()
|
||||
|
||||
def _report(self):
|
||||
self.running = True
|
||||
def write():
|
||||
try:
|
||||
report = write_batch_report(self.requests, self.results, self.report_root)
|
||||
write_maintenance_report(self.requests, self.results, report, ())
|
||||
return report, ''
|
||||
except Exception as error:
|
||||
return None, str(error)
|
||||
self.worker = ServiceWorker(write)
|
||||
self.worker.signals.succeeded.connect(self._report_ready)
|
||||
self.worker.signals.finished.connect(self._complete)
|
||||
self.pool.start(self.worker)
|
||||
|
||||
def _report_ready(self, payload):
|
||||
self.report, self.report_error = payload
|
||||
|
||||
def _complete(self):
|
||||
self.running = self.active = False
|
||||
self.finished.emit(self)
|
||||
@@ -1,6 +1,7 @@
|
||||
from pathlib import Path
|
||||
from threading import Event
|
||||
import os
|
||||
import ntpath
|
||||
import time
|
||||
from collections import Counter
|
||||
from dataclasses import replace
|
||||
@@ -20,6 +21,26 @@ def _path_key(value):
|
||||
if not raw:
|
||||
return ''
|
||||
return os.path.normcase(os.path.normpath(os.path.abspath(raw)))
|
||||
|
||||
|
||||
def _library_path_keys(value, lease=None):
|
||||
"""Use known mapping aliases without resolving unavailable network paths."""
|
||||
if not value:
|
||||
return set()
|
||||
keys = {_path_key(value)}
|
||||
mentor = getattr(lease, 'mentor_path', None)
|
||||
display = getattr(lease, 'display_path', None)
|
||||
if mentor and display:
|
||||
for source, alias in ((mentor, display), (display, mentor)):
|
||||
if _path_key(value) == _path_key(source):
|
||||
keys.add(_path_key(alias))
|
||||
elif _path_key(Path(value).parent) == _path_key(source):
|
||||
keys.add(_path_key(Path(alias)/Path(value).name))
|
||||
drive, tail = ntpath.splitdrive(str(value))
|
||||
if (getattr(lease, 'remote_root', '') and drive
|
||||
and drive.upper() == getattr(lease, 'drive', '').upper()):
|
||||
keys.add(_path_key(lease.remote_root + tail))
|
||||
return keys
|
||||
try:
|
||||
from dx_productivity.trial_task_center.ui.workers import ServiceWorker
|
||||
except ImportError:
|
||||
@@ -75,6 +96,7 @@ class MainWindow(QWidget):
|
||||
self.management_capabilities = self.management_adapter.capabilities()
|
||||
self._management_unsafe = False
|
||||
self._management_unsafe_library = None
|
||||
self._management_unsafe_libraries = set()
|
||||
self._management_operation_library = None
|
||||
self._maintenance_recovery_view = False
|
||||
self._reload_after_maintenance = False
|
||||
@@ -105,6 +127,16 @@ class MainWindow(QWidget):
|
||||
p, names, mapping_store=self.data_root/'image-status-map.json'),
|
||||
)
|
||||
self.pool = QThreadPool(self); self.pool.setMaxThreadCount(1)
|
||||
self._lease_pending = 0
|
||||
self._lease_workers = set()
|
||||
self._mapping_busy = 0
|
||||
self._mapping_auto_idle = False
|
||||
self._mapping_finish_waiters = []
|
||||
self._closing = self._close_ready = False
|
||||
from cbb_refresh_verify.operation_queue import NativeQueue
|
||||
self.native_queue = NativeQueue()
|
||||
self.icdb_task = None
|
||||
self.icdb_tasks = []
|
||||
self.busy = False; self.loaded_path = None; self.stop = Event(); self.ready_names = set()
|
||||
self._row_by_name = {}
|
||||
self._records_by_name = {}
|
||||
@@ -236,6 +268,9 @@ class MainWindow(QWidget):
|
||||
maintenance_layout.addWidget(self.native_backup_button)
|
||||
maintenance_row = QHBoxLayout()
|
||||
maintenance_row.addWidget(self.icdb_repair_button)
|
||||
self.icdb_stop_button = QPushButton('停止检查')
|
||||
self.icdb_stop_button.clicked.connect(self._stop_icdb_check)
|
||||
maintenance_row.addWidget(self.icdb_stop_button)
|
||||
maintenance_row.addWidget(self.backup_restore_button)
|
||||
maintenance_row.addWidget(self.reimport_button)
|
||||
maintenance_layout.addLayout(maintenance_row)
|
||||
@@ -264,7 +299,7 @@ class MainWindow(QWidget):
|
||||
management_layout.insertWidget(0, self.management_capability_label)
|
||||
self.unfinished_label = QLabel(); self.unfinished_label.setWordWrap(True)
|
||||
management_layout.addWidget(self.unfinished_label)
|
||||
self.release_library_button = QPushButton('检查占用…')
|
||||
self.release_library_button = QPushButton('释放残留会话…')
|
||||
self.release_library_button.clicked.connect(self.check_library_release)
|
||||
management_buttons.addWidget(self.release_library_button)
|
||||
self.section_stack.addWidget(management)
|
||||
@@ -293,20 +328,62 @@ class MainWindow(QWidget):
|
||||
self._records_by_name = {}
|
||||
self.ready_names = set(); self.skipped_names = set(); self.skip_reasons = {}; self._update()
|
||||
self._global_icdb_run = False
|
||||
self.icdb_progress.hide(); self.icdb_phase.hide()
|
||||
if not self._icdb_active():
|
||||
self.icdb_progress.hide(); self.icdb_phase.hide()
|
||||
|
||||
def _release_library_lease(self):
|
||||
lease, self.library_lease = self.library_lease, None
|
||||
if self._native_backup_session is not None and self._native_backup_session.path_lease is lease:
|
||||
return # The visible native session still needs this mapping.
|
||||
if self._icdb_active() and self.icdb_task.path_lease is lease:
|
||||
return # This background task still uses its captured mapping.
|
||||
if lease is None:
|
||||
return
|
||||
try:
|
||||
lease.close()
|
||||
self._close_path_lease(lease)
|
||||
except Exception as error:
|
||||
if self.logging_context:
|
||||
self.logging_context.logger.warning('library_lease_release_failed error=%s', error)
|
||||
|
||||
def _close_path_lease(self, lease):
|
||||
self._lease_action(lease.close, hold_busy=self.busy)
|
||||
|
||||
def _retain_path_lease(self, lease, *, hold_busy=False):
|
||||
if lease is not None:
|
||||
self._lease_action(lease.retain_for_recovery, hold_busy=hold_busy)
|
||||
|
||||
def _lease_action(self, action, completed=None, failed=None, *, hold_busy=False):
|
||||
# The serial pool orders retain before every subsequent close.
|
||||
self._lease_pending += 1
|
||||
if hold_busy:
|
||||
if not self._mapping_busy and not self.busy:
|
||||
self._mapping_auto_idle = True
|
||||
self._mapping_busy += 1
|
||||
self.busy = True
|
||||
self._update()
|
||||
worker = ServiceWorker(action)
|
||||
self._lease_workers.add(worker)
|
||||
if completed is not None: worker.signals.succeeded.connect(completed)
|
||||
worker.signals.failed.connect(failed or self._display_error)
|
||||
def finished():
|
||||
self._lease_workers.discard(worker)
|
||||
self._lease_pending -= 1
|
||||
if hold_busy: self._mapping_busy -= 1
|
||||
if not self._mapping_busy:
|
||||
callbacks, self._mapping_finish_waiters = self._mapping_finish_waiters, []
|
||||
auto_idle, self._mapping_auto_idle = self._mapping_auto_idle, False
|
||||
for callback in callbacks: callback()
|
||||
if auto_idle and not callbacks: self._finished()
|
||||
self._update()
|
||||
worker.signals.finished.connect(finished)
|
||||
self.pool.start(worker)
|
||||
|
||||
def _defer_mapping_finish(self, callback):
|
||||
if not self._mapping_busy: return False
|
||||
if callback not in self._mapping_finish_waiters:
|
||||
self._mapping_finish_waiters.append(callback)
|
||||
return True
|
||||
|
||||
def _update(self):
|
||||
# The refresh flow needs only the library and a CBB; LibSpec/DMS config
|
||||
# are optional and only enable the extra contents check.
|
||||
@@ -318,7 +395,8 @@ class MainWindow(QWidget):
|
||||
ready = ready and not self._native_backup_same_library()
|
||||
self.batch_button.setEnabled(ready and bool(self._eligible_names()))
|
||||
self.selected_batch_button.setEnabled(ready and bool(self._eligible_names(checked_only=True)))
|
||||
self.icdb_repair_button.setEnabled(ready and bool(self._maintenance_names()))
|
||||
self.icdb_repair_button.setEnabled(ready and not self._icdb_active() and bool(self._maintenance_names()))
|
||||
self.icdb_stop_button.setEnabled(self._icdb_active() and not self.icdb_task.stop.is_set())
|
||||
self.backup_restore_button.setEnabled(ready and bool(
|
||||
self._eligible_names(checked_only=bool(self.selected_records()))))
|
||||
self.release_library_button.setEnabled(not self.busy and bool(self.lmc_edit.text().strip()))
|
||||
@@ -331,19 +409,18 @@ class MainWindow(QWidget):
|
||||
reasons.append(reason)
|
||||
self.management_capability_label.setText('\n'.join(dict.fromkeys(reasons)))
|
||||
current_library = _path_key(self.mentor_lmc_path or self.lmc_edit.text()) if self.lmc_edit.text().strip() else None
|
||||
notice = ('上次管理操作尚未确认安全释放,请检查该操作的结果。'
|
||||
if (self._management_unsafe and self._management_unsafe_library is not None
|
||||
and current_library == _path_key(self._management_unsafe_library)) else '')
|
||||
notice = ('上次操作结果待复查,执行前将重新检查占用。'
|
||||
if self._management_library_unsafe(current_library) else '')
|
||||
self.library_notice.setText(notice)
|
||||
self.library_notice.setVisible(bool(notice))
|
||||
for widget in (self.lmc_edit, self.browse_button, self.load_button, self.cbb_table,
|
||||
self.timeout_spin, self.advanced_toggle, self.advanced_panel,
|
||||
self.search_edit, self.status_filter, self.select_visible_button, self.clear_selection_button):
|
||||
for widget in (self.lmc_edit, self.browse_button, self.load_button,
|
||||
self.timeout_spin, self.advanced_toggle, self.advanced_panel):
|
||||
widget.setEnabled(not self.busy)
|
||||
counts = self.visible_counts()
|
||||
self.counts_label.setText(f'可见 {counts["visible"]} / {len(self._records_by_name)} · '
|
||||
f'READY {counts["ready"]} · 异常/待确认 {counts["error"]}')
|
||||
self.stop_button.setEnabled(self.busy and self.loaded_path is not None and not self.stop.is_set())
|
||||
self.stop_button.setEnabled((self.busy and self.loaded_path is not None and not self.stop.is_set())
|
||||
or self._icdb_active() and not self.icdb_task.stop.is_set())
|
||||
self.stop_button.setText('取消当前任务并停止队列')
|
||||
available = bool(self._reimport_offers) and not self.busy and self.management_capabilities['update'].supported
|
||||
self.reimport_button.setVisible(bool(self._reimport_offers))
|
||||
@@ -351,6 +428,13 @@ class MainWindow(QWidget):
|
||||
self.reimport_button.setToolTip(self.management_capabilities['update'].reason)
|
||||
if self._reimport_summary_action is not None:
|
||||
self._reimport_summary_action.setEnabled(available)
|
||||
if getattr(self, '_residual_release_action', None) is not None:
|
||||
self._residual_release_action.setEnabled(not self.busy)
|
||||
if getattr(self, '_resume_batch_action', None) is not None:
|
||||
pending = getattr(self, '_resume_batch', None)
|
||||
same = bool(pending and _library_path_keys(pending['library'], self.library_lease)
|
||||
& _library_path_keys(self.mentor_lmc_path or self.loaded_path, self.library_lease))
|
||||
self._resume_batch_action.setEnabled(not self.busy and same and pending['released'])
|
||||
|
||||
def _show_unfinished_management(self):
|
||||
from cbb_refresh_verify.management import unfinished_operations
|
||||
@@ -364,48 +448,79 @@ class MainWindow(QWidget):
|
||||
def check_library_release(self):
|
||||
if self.busy or not self.lmc_edit.text().strip():
|
||||
return
|
||||
if QMessageBox.question(self, '检查原生会话释放',
|
||||
'检查所有原生编辑器/管理进程、库内数据库地址记录及数据库独占可读性。'
|
||||
'\n全部通过后归档阻止记录并释放本应用保留的库锁。'
|
||||
'\n数据恢复结果和未完成管理任务仍需单独审查。继续?',
|
||||
QMessageBox.Yes | QMessageBox.No, QMessageBox.No) != QMessageBox.Yes:
|
||||
return
|
||||
from cbb_refresh_verify.library_lock import release_retained_library
|
||||
from .residual_release_dialog import ResidualReleaseDialog
|
||||
library = Path(self.mentor_lmc_path or self.lmc_edit.text().strip())
|
||||
if library.is_dir():
|
||||
library = select_library_file(library)
|
||||
def completed(result):
|
||||
current_library = _path_key(self.mentor_lmc_path or self.lmc_edit.text().strip())
|
||||
if current_library == _path_key(library):
|
||||
self._management_unsafe = False
|
||||
self._management_unsafe_library = None
|
||||
session = self._native_backup_session
|
||||
if session is not None and session.library == library and session.process.poll() is not None:
|
||||
self._release_native_backup_session(session)
|
||||
message = f'原生会话释放检查通过。请审查未完成任务后重新读取中心库。\n{result["evidence_path"]}'
|
||||
self.status_label.setText(message); self.output.append(message)
|
||||
block_name = None
|
||||
if len(self._batch_requests) == 1:
|
||||
block_name = self._batch_requests[0].block_name
|
||||
elif len(self.selected_records()) == 1:
|
||||
block_name = self.selected_records()[0].name
|
||||
import inspect
|
||||
if 'block_name' in inspect.signature(release_retained_library).parameters:
|
||||
action = lambda: release_retained_library(library, self.data_root/'release-checks',
|
||||
block_name=block_name)
|
||||
else:
|
||||
action = lambda: release_retained_library(library, self.data_root/'release-checks')
|
||||
self._start(action, completed)
|
||||
self.release_dialog = ResidualReleaseDialog(library, self.data_root/'release-checks', self)
|
||||
self.release_dialog.native_queue = self.native_queue
|
||||
self.release_dialog.before_release.connect(self._stop_icdb_check)
|
||||
self.release_dialog.released.connect(lambda result: self._complete_library_release(self.release_dialog.library, result))
|
||||
self.release_dialog.finished.connect(self._release_dialog_finished)
|
||||
self.busy = True; self._update()
|
||||
self.release_dialog.show()
|
||||
|
||||
def _release_dialog_finished(self, _=None):
|
||||
if self._defer_mapping_finish(self._release_dialog_finished): return
|
||||
self._finished()
|
||||
pending = getattr(self, '_resume_batch', None)
|
||||
if pending and pending['released']:
|
||||
self.summary.setText('会话已释放,可以继续未执行项。')
|
||||
self.summary.show()
|
||||
|
||||
def _complete_library_release(self, library, result):
|
||||
from cbb_refresh_verify.network_path import release_retained_path_leases
|
||||
try:
|
||||
if (not isinstance(result, dict) or result.get('status') != 'RELEASE_CONFIRMED'
|
||||
or not (_library_path_keys(result.get('library'), self.library_lease)
|
||||
& _library_path_keys(library, self.library_lease))):
|
||||
raise ValueError('RELEASE_PROOF_UNCONFIRMED: 释放证明未确认或不属于当前中心库。')
|
||||
except Exception as error:
|
||||
self._failed(error)
|
||||
return
|
||||
lease = self.library_lease
|
||||
def release():
|
||||
try:
|
||||
release_retained_path_leases(result, current_lease=lease)
|
||||
except Exception:
|
||||
if lease is not None: lease.retain_for_recovery()
|
||||
raise
|
||||
self._lease_action(release, lambda _: self._library_release_ready(library, result),
|
||||
self._display_error, hold_busy=True)
|
||||
|
||||
def _library_release_ready(self, library, result):
|
||||
current_library = _path_key(self.mentor_lmc_path or self.lmc_edit.text().strip())
|
||||
if current_library == _path_key(library):
|
||||
self._management_unsafe = False
|
||||
self._management_unsafe_library = None
|
||||
self._management_unsafe_libraries.discard(_path_key(library))
|
||||
session = self._native_backup_session
|
||||
if self._native_backup_matches_library(library) and session.process.poll() is not None:
|
||||
self._release_native_backup_session(session)
|
||||
pending = getattr(self, '_resume_batch', None)
|
||||
if pending and (_library_path_keys(pending['library'], self.library_lease)
|
||||
& _library_path_keys(library, self.library_lease)):
|
||||
pending['released'] = True
|
||||
message = f'相关会话已释放,可以重试未完成的项目。\n{result["evidence_path"]}'
|
||||
self.status_label.setText(message); self.output.append(message)
|
||||
|
||||
def _resume_released_batch(self):
|
||||
pending = getattr(self, '_resume_batch', None)
|
||||
if self.busy or not pending or not pending['released']: return
|
||||
if not (_library_path_keys(pending['library'], self.library_lease)
|
||||
& _library_path_keys(self.mentor_lmc_path or self.loaded_path, self.library_lease)):
|
||||
return
|
||||
self._resume_batch = None
|
||||
self._run(pending['names'], maintenance=pending['maintenance'])
|
||||
|
||||
def _management_library_unsafe(self, library):
|
||||
if self._management_unsafe and self._management_unsafe_library is not None:
|
||||
self._management_unsafe_libraries.add(_path_key(self._management_unsafe_library))
|
||||
return _path_key(library) in self._management_unsafe_libraries
|
||||
|
||||
def _management_block_reason(self, operation):
|
||||
if self.busy:
|
||||
return '当前任务尚未结束,请等待后再执行库管理操作。'
|
||||
if self._native_backup_same_library():
|
||||
return '该库的版本与备份窗口仍在使用,关闭后可执行写入操作。'
|
||||
current_library = _path_key(self.mentor_lmc_path or self.lmc_edit.text()) if self.lmc_edit.text().strip() else None
|
||||
if (self._management_unsafe and self._management_unsafe_library is not None
|
||||
and current_library == _path_key(self._management_unsafe_library)):
|
||||
return '上次管理操作的会话尚未安全释放,请先查看异常证据并执行释放检查。'
|
||||
capability = self.management_capabilities[operation]
|
||||
if not capability.supported:
|
||||
return capability.reason
|
||||
@@ -441,8 +556,12 @@ class MainWindow(QWidget):
|
||||
self.stop.clear()
|
||||
self._management_is_recovery = bool(recovery_from)
|
||||
self._management_operation_library = _path_key(requests[0].library) if requests else None
|
||||
requests = [replace(request, check_previous_release=True) if self._management_library_unsafe(request.library)
|
||||
else request for request in requests]
|
||||
self.management_dialog = ManagementDialog(requests, self, adapter=self.management_adapter,
|
||||
recovery_from=recovery_from)
|
||||
self.management_dialog.native_queue = self.native_queue
|
||||
self.management_dialog.before_execute.connect(lambda names: self._invalidate_check_targets(requests[0].library, names))
|
||||
self._management_results = []
|
||||
self.management_dialog.completed.connect(self._management_completed)
|
||||
self.management_dialog.finished.connect(self._management_closed)
|
||||
@@ -471,8 +590,41 @@ class MainWindow(QWidget):
|
||||
|
||||
def _management_completed(self, results):
|
||||
self._management_results = results
|
||||
if (getattr(self, '_management_is_recovery', False) and results
|
||||
proofs = [result.release_proof for result in results if isinstance(getattr(result, 'release_proof', None), dict)
|
||||
and result.release_proof.get('status') == 'RELEASE_CONFIRMED'
|
||||
and bool(_library_path_keys(result.release_proof.get('library'), self.library_lease)
|
||||
& _library_path_keys(self._management_operation_library, self.library_lease))
|
||||
]
|
||||
safe = all(result.safe_to_continue for result in results)
|
||||
lease = self.library_lease
|
||||
if proofs and safe:
|
||||
from cbb_refresh_verify.network_path import release_retained_path_leases
|
||||
def release():
|
||||
try:
|
||||
release_retained_path_leases(proofs[-1], current_lease=lease)
|
||||
except Exception:
|
||||
if lease is not None: lease.retain_for_recovery()
|
||||
raise
|
||||
def failed(error):
|
||||
self._management_unsafe = True
|
||||
self._management_unsafe_library = self._management_operation_library
|
||||
self._management_unsafe_libraries.add(_path_key(self._management_operation_library))
|
||||
self._display_error(error)
|
||||
self._management_results_ready(results, proofs, False)
|
||||
self._lease_action(release, lambda _: self._management_results_ready(results, proofs, True),
|
||||
failed, hold_busy=True)
|
||||
elif not safe and lease is not None:
|
||||
self._lease_action(lease.retain_for_recovery,
|
||||
lambda _: self._management_results_ready(results, proofs, True),
|
||||
lambda error: (self._display_error(error), self._management_results_ready(results, proofs, False)),
|
||||
hold_busy=True)
|
||||
else:
|
||||
self._management_results_ready(results, proofs, True)
|
||||
|
||||
def _management_results_ready(self, results, proofs, mapping_released):
|
||||
if (mapping_released and (getattr(self, '_management_is_recovery', False) or proofs) and results
|
||||
and all(result.safe_to_continue for result in results)):
|
||||
self._management_unsafe_libraries.discard(_path_key(self._management_operation_library))
|
||||
self._management_unsafe = False
|
||||
self._management_unsafe_library = None
|
||||
self._maintenance_recovery_view = False
|
||||
@@ -482,20 +634,25 @@ class MainWindow(QWidget):
|
||||
for result in results:
|
||||
self.output.append(f'{result.name}:{RESULT_LABELS.get(result.status, result.status)} '
|
||||
f'{result.detail}\n{result.evidence_path or ""}')
|
||||
if self.logging_context:
|
||||
self.logging_context.logger.info('management_result operation=%s block=%s status=%s safe=%s evidence=%s detail=%s',
|
||||
result.operation, result.name, result.status, result.safe_to_continue, result.evidence_path, result.detail)
|
||||
if getattr(self, '_management_is_recovery', False) and result.status == 'UPLOADED_VERIFIED':
|
||||
self.output.append('副本恢复校验通过,版本待核对。')
|
||||
if any(not result.safe_to_continue for result in results):
|
||||
self._management_unsafe = True
|
||||
self._management_unsafe_library = self._management_operation_library
|
||||
if self.library_lease:
|
||||
self.library_lease.retain_for_recovery()
|
||||
self._management_unsafe_libraries.add(_path_key(self._management_operation_library))
|
||||
self.status_label.setText('管理操作需要人工确认恢复/释放;已停止写入,未再次读取原生目录。')
|
||||
self._show_unfinished_management()
|
||||
|
||||
def _management_closed(self, *_):
|
||||
if self._defer_mapping_finish(self._management_closed): return
|
||||
from PySide6.QtCore import QTimer
|
||||
self.busy = False; self._update()
|
||||
if self._management_results and not self._management_unsafe:
|
||||
changed = any(result.status in {'REMOVED', 'UPLOADED', 'UPLOADED_VERIFIED', 'UPLOADED_VERIFY_FAILED', 'RECOVERY_REQUIRED'}
|
||||
for result in self._management_results)
|
||||
if changed and not self._management_library_unsafe(self.mentor_lmc_path or self.loaded_path):
|
||||
# Whole catalog reload is necessary for inserted/deleted identities;
|
||||
# existing local search/filter controls are intentionally retained.
|
||||
QTimer.singleShot(0, self.load_library)
|
||||
@@ -574,23 +731,177 @@ class MainWindow(QWidget):
|
||||
if path: self.lmc_edit.setText(path); self.load_library()
|
||||
|
||||
def _start(self, action, callback):
|
||||
self.stop.clear()
|
||||
self.busy = True; self._update()
|
||||
self.worker = ServiceWorker(action)
|
||||
self.worker = ServiceWorker(self._queued_action(action))
|
||||
self.worker.signals.succeeded.connect(callback)
|
||||
self.worker.signals.failed.connect(self._failed)
|
||||
self.worker.signals.finished.connect(self._finished)
|
||||
self.pool.start(self.worker)
|
||||
|
||||
def _queued_action(self, action):
|
||||
return lambda: self.native_queue.run(action, stop=self.stop,
|
||||
waiting=lambda: self.signals.event.emit({'stage': 'waiting_native_slot',
|
||||
'detail': '已排队,等待当前原生操作结束'}))
|
||||
|
||||
def _icdb_active(self):
|
||||
return self.icdb_task is not None and self.icdb_task.active
|
||||
|
||||
def _check_matches_library(self, library):
|
||||
return self._icdb_active() and bool(_library_path_keys(library, self.library_lease)
|
||||
& _library_path_keys(self.icdb_task.requests[0].lmc_file, self.icdb_task.path_lease))
|
||||
|
||||
def _invalidate_check_targets(self, library, names):
|
||||
names = set(names)
|
||||
for task in self.icdb_tasks:
|
||||
if not (_library_path_keys(library, self.library_lease)
|
||||
& _library_path_keys(task.requests[0].lmc_file, task.path_lease)): continue
|
||||
task.invalidate(names)
|
||||
if hasattr(task, 'summary'):
|
||||
prefix = '已更新的工程:'+', '.join(sorted(task.invalidated))+'。下列为此前检查记录。\n'
|
||||
task.summary.setDetailedText(prefix+task.summary.detailedText())
|
||||
if names & getattr(task, 'recovery_names', set()):
|
||||
task.recovery_action.setEnabled(False)
|
||||
task.recovery_action.setToolTip('工程已有后续管理操作,请重新检查。')
|
||||
self._reimport_offers = tuple(offer for offer in self._reimport_offers if offer[0].block_name not in names
|
||||
or not (_library_path_keys(library, self.library_lease) & _library_path_keys(offer[0].lmc_file)))
|
||||
|
||||
def _stop_icdb_check(self):
|
||||
if self._icdb_active():
|
||||
self.icdb_task.cancel()
|
||||
self.icdb_phase.setText('正在停止检查,等待本项退出…')
|
||||
self._update()
|
||||
|
||||
def _publish_check_statuses(self, library, statuses, lease=None):
|
||||
for task in tuple(self.icdb_tasks):
|
||||
if task.active and (_library_path_keys(library, lease or self.library_lease)
|
||||
& _library_path_keys(task.requests[0].lmc_file, task.path_lease)):
|
||||
task.update_statuses(statuses)
|
||||
|
||||
def _start_icdb_check(self, names):
|
||||
if self.busy or self._icdb_active() or not self.loaded_path or self._native_backup_same_library(): return
|
||||
eligible = set(self._maintenance_names())
|
||||
names = [name for name in names if name in eligible]
|
||||
if not names: return
|
||||
from .icdb_check_task import IcdbCheckTask
|
||||
requests = tuple(replace(self._request(name), maintenance=True, auto_repair=False) for name in names)
|
||||
task = IcdbCheckTask(requests, self.native_queue, self.data_root/'reports',
|
||||
verifier=self.verifier, path_lease=self.library_lease, parent=self)
|
||||
task.records = {name: self._records_by_name[name] for name in names}
|
||||
self.icdb_task = task
|
||||
self.icdb_tasks.append(task)
|
||||
task.event.connect(lambda event: self._icdb_event(task, event))
|
||||
task.item_done.connect(lambda name, result: self._icdb_item_done(task, name, result))
|
||||
task.finished.connect(self._icdb_done)
|
||||
self.icdb_progress.setVisible(True); self.icdb_phase.setVisible(True)
|
||||
self.icdb_progress.setRange(0, len(requests)); self.icdb_progress.setValue(0)
|
||||
self.icdb_progress.setFormat('已处理 %v / %m 个 CBB')
|
||||
self.icdb_phase.setText('准备后台检查…')
|
||||
task.start(); self._update()
|
||||
|
||||
def _icdb_event(self, task, event):
|
||||
name, stage = str(event.get('block', '')), str(event.get('stage', ''))
|
||||
detail = str(event.get('detail') or stage)
|
||||
self.icdb_phase.setText(f'{name} · '+({'icdb_check_start': '正在检查',
|
||||
'icdb_startup_check': '正在打开工程', 'waiting_native_slot': '已排队,等待执行'}.get(stage, detail)))
|
||||
if not self.busy: self.status_label.setText('后台 ICDB 检查:'+self.icdb_phase.text())
|
||||
if self.logging_context:
|
||||
self.logging_context.logger.info('icdb_background block=%s stage=%s detail=%s', name, stage, detail)
|
||||
|
||||
def _icdb_item_done(self, task, name, result):
|
||||
self.icdb_progress.setValue(len(task.results))
|
||||
if not (_library_path_keys(task.requests[0].lmc_file, task.path_lease)
|
||||
& _library_path_keys(self.mentor_lmc_path or self.loaded_path, self.library_lease)):
|
||||
return
|
||||
row = self._row_by_name.get(name)
|
||||
if row is None: return
|
||||
if not result.safe_to_continue: self._defer_status_refresh([name])
|
||||
if name in task.invalidated:
|
||||
text = '内容已更新,待重新检查'
|
||||
elif result.status == 'CHECKED': text = '未发现 ICDB 错误'
|
||||
elif result.error_category == 'ICDB_REPAIR_REQUIRED': text = '发现 ICDB 错误'
|
||||
elif result.status == 'CANCELLED': text = '检查已取消'
|
||||
elif result.status == 'SKIPPED':
|
||||
text = '已为 READY,跳过检查' if name in task.ready_names else '未检查'
|
||||
elif result.error_category == 'DATABASE_SAFETY_STOP':
|
||||
if 'read/write access permission' in result.stderr.casefold():
|
||||
text = '未确认:需处理读写确认'
|
||||
elif not result.safe_to_continue:
|
||||
text = '未确认:会话释放未确认'
|
||||
else:
|
||||
text = '未确认:会话或数据库状态待确认'
|
||||
elif result.error_category == 'PCB_VERSION_CHOICE_REQUIRED': text = '未确认:需选择工程版本'
|
||||
else: text = '未确认:'+(result.stderr.splitlines()[0][:120] if result.stderr else result.status)
|
||||
cell = self.cbb_table.item(row, 3)
|
||||
cell.setText(text); cell.setToolTip(result.stderr or result.stdout)
|
||||
cell.setBackground(QColor('#E8F5E9' if result.status == 'CHECKED' and name not in task.invalidated
|
||||
else '#FFEBEE' if result.error_category == 'ICDB_REPAIR_REQUIRED' else '#FFF8E1'))
|
||||
|
||||
def _icdb_done(self, task):
|
||||
from cbb_refresh_verify.icdb_maintenance import maintenance_counts
|
||||
counts = maintenance_counts(task.results)
|
||||
lease = task.path_lease
|
||||
if lease is not None:
|
||||
if any(not result.safe_to_continue for result in task.results): self._retain_path_lease(lease)
|
||||
held_by_native = self._native_backup_session is not None and self._native_backup_session.path_lease is lease
|
||||
if lease is not self.library_lease and not held_by_native:
|
||||
self._close_path_lease(lease)
|
||||
for request, result in zip(task.requests, task.results):
|
||||
if result.status == 'SKIPPED': self._icdb_item_done(task, request.block_name, result)
|
||||
text = (f'ICDB 检查结束:未发现异常 {counts["checked_without_repair"]},发现问题 {counts["issues_found"]},'
|
||||
f'占用 {counts["in_use"]},无法确认 {counts["unconfirmed"]},取消 {counts["cancelled"]},未执行 {counts["skipped"]}')
|
||||
from cbb_refresh_verify.reimport_recovery import offers_reimport
|
||||
offers = tuple((req, task.records[req.block_name], result) for req, result in zip(task.requests, task.results)
|
||||
if req.block_name not in task.invalidated and offers_reimport(result))
|
||||
same_library = bool(_library_path_keys(task.requests[0].lmc_file, task.path_lease)
|
||||
& _library_path_keys(self.mentor_lmc_path or self.loaded_path, self.library_lease))
|
||||
if offers: text += '\n可选择工程副本恢复。'
|
||||
if same_library and not self.busy: self._reimport_offers = offers
|
||||
self.icdb_phase.setText(text)
|
||||
if not self.busy: self.status_label.setText(text)
|
||||
self.output.append(text+'\n'+str(task.report or task.report_error))
|
||||
summary = QMessageBox(self); self.icdb_summary = summary
|
||||
task.summary = summary
|
||||
if not self.busy: self.summary = summary
|
||||
summary.setWindowTitle('ICDB 批量检查结果'); summary.setText(text)
|
||||
summary.setDetailedText(str(task.report or task.report_error)+'\n'+'\n'.join(
|
||||
req.block_name+':'+('内容已更新,以下为旧检查结果:' if req.block_name in task.invalidated else '')
|
||||
+(result.stderr or result.stdout or result.status)
|
||||
for req, result in zip(task.requests, task.results)))
|
||||
summary.setTextFormat(Qt.PlainText); summary.setAttribute(Qt.WA_ShowWithoutActivating)
|
||||
if any(not result.safe_to_continue for result in task.results):
|
||||
def release_task():
|
||||
if not (_library_path_keys(task.requests[0].lmc_file, task.path_lease)
|
||||
& _library_path_keys(self.mentor_lmc_path or self.loaded_path, self.library_lease)):
|
||||
self.status_label.setText(f'请切回 {task.requests[0].lmc_file} 后释放该检查的残留。')
|
||||
return
|
||||
self.check_library_release()
|
||||
summary.addButton('查看残留并释放…', QMessageBox.ActionRole).clicked.connect(release_task)
|
||||
if offers:
|
||||
action = summary.addButton('选择副本恢复…', QMessageBox.ActionRole)
|
||||
task.recovery_action = action
|
||||
task.recovery_names = {req.block_name for req, _, _ in offers}
|
||||
def recover():
|
||||
if task.recovery_names & task.invalidated: return
|
||||
if self.busy or not (_library_path_keys(task.requests[0].lmc_file, task.path_lease)
|
||||
& _library_path_keys(self.mentor_lmc_path or self.loaded_path, self.library_lease)): return
|
||||
self._reimport_offers = offers
|
||||
self.reimport_failed()
|
||||
action.clicked.connect(recover)
|
||||
summary.show(); self._update()
|
||||
|
||||
def load_library(self):
|
||||
if self.busy or not self.lmc_edit.text(): return
|
||||
self._maintenance_recovery_view = False
|
||||
self._global_icdb_run = False
|
||||
if self._management_unsafe_library is not None:
|
||||
self._management_library_unsafe(self._management_unsafe_library)
|
||||
requested_library = _path_key(self.lmc_edit.text())
|
||||
if requested_library != _path_key(self._management_unsafe_library):
|
||||
self._management_unsafe = False
|
||||
self._management_unsafe_library = None
|
||||
self.icdb_progress.hide(); self.icdb_phase.hide()
|
||||
if not self._icdb_active():
|
||||
self.icdb_progress.hide(); self.icdb_phase.hide()
|
||||
self._release_library_lease()
|
||||
self.loaded_path = None; self.cbb_table.setRowCount(0); self._row_by_name = {}; self.ready_names = set()
|
||||
self._records_by_name = {}
|
||||
@@ -607,6 +918,8 @@ class MainWindow(QWidget):
|
||||
lease = self.path_lease_factory(Path(path))
|
||||
mentor_path = (select_library_file(lease.mentor_path)
|
||||
if lease.mentor_path.is_dir() else lease.mentor_path)
|
||||
if isinstance(lease, LibraryPathLease):
|
||||
lease.mentor_path = mentor_path
|
||||
if self.logging_context:
|
||||
self.logging_context.logger.info(
|
||||
'library_path_lease display=%s mentor=%s drive=%s remote=%s created=%s',
|
||||
@@ -614,6 +927,9 @@ class MainWindow(QWidget):
|
||||
lease.remote_root or '-', lease.created)
|
||||
recovery_view = False
|
||||
result = self.reader(mentor_path)
|
||||
if not result.error:
|
||||
self._publish_check_statuses(mentor_path,
|
||||
{record.name: record.status for record in result.records}, lease)
|
||||
if self.logging_context:
|
||||
statuses = Counter(record.status for record in result.records)
|
||||
unknown = [record.name for record in result.records if record.status in {'UNKNOWN', 'UNAVAILABLE'}]
|
||||
@@ -636,10 +952,10 @@ class MainWindow(QWidget):
|
||||
def loaded(payload):
|
||||
result, skip_reasons, lease, mentor_path, recovery_view = payload
|
||||
if path != self.lmc_edit.text():
|
||||
lease.close()
|
||||
self._close_path_lease(lease)
|
||||
return
|
||||
if result.error:
|
||||
lease.close()
|
||||
self._close_path_lease(lease)
|
||||
self.status_label.setText(result.error); return
|
||||
self.library_lease = lease
|
||||
self._maintenance_recovery_view = recovery_view
|
||||
@@ -747,8 +1063,13 @@ class MainWindow(QWidget):
|
||||
self._run(names, maintenance=True)
|
||||
|
||||
def _native_backup_same_library(self):
|
||||
return self._native_backup_matches_library(self.mentor_lmc_path or self.lmc_edit.text())
|
||||
|
||||
def _native_backup_matches_library(self, library, lease=None):
|
||||
session = self._native_backup_session
|
||||
return session is not None and Path(self.mentor_lmc_path or self.lmc_edit.text()) == session.library
|
||||
return session is not None and bool(
|
||||
_library_path_keys(library, lease or self.library_lease)
|
||||
& _library_path_keys(session.library, getattr(session, 'path_lease', None)))
|
||||
|
||||
def open_native_backup(self):
|
||||
if self.busy or not self.loaded_path or self._native_backup_session is not None:
|
||||
@@ -763,6 +1084,9 @@ class MainWindow(QWidget):
|
||||
self._global_icdb_run = False
|
||||
self._reimport_offers = ()
|
||||
self.status_label.setText(f'正在打开 {request.block_name} 的版本与备份…')
|
||||
paused_check = self.icdb_task if self._check_matches_library(request.lmc_file) else None
|
||||
if paused_check is not None:
|
||||
paused_check.pause(); paused_check.invalidate([request.block_name])
|
||||
def opened(session):
|
||||
session.path_lease = self.library_lease
|
||||
self._native_backup_session = session
|
||||
@@ -770,30 +1094,33 @@ class MainWindow(QWidget):
|
||||
self.status_label.setText(f'正在打开 {session.block} 的原生备份窗口,请在其中选择版本。')
|
||||
self.output.append(f'{session.block} · 原生版本与备份\n{session.job}')
|
||||
self.busy = True; self._update()
|
||||
self.worker = ServiceWorker(lambda: launcher(request))
|
||||
self.stop.clear()
|
||||
self.worker = ServiceWorker(self._queued_action(lambda: launcher(request)))
|
||||
self.worker.signals.succeeded.connect(opened)
|
||||
self.worker.signals.failed.connect(lambda error: self.status_label.setText(f'无法打开版本与备份:{error}'))
|
||||
def failed(error):
|
||||
self.status_label.setText(f'无法打开版本与备份:{error}')
|
||||
if paused_check is not None: paused_check.resume()
|
||||
self.worker.signals.failed.connect(failed)
|
||||
self.worker.signals.finished.connect(self._finished)
|
||||
self.pool.start(self.worker)
|
||||
|
||||
def _release_native_backup_session(self, session):
|
||||
self._native_backup_session = None
|
||||
if session.path_lease is not None and session.path_lease is not self.library_lease:
|
||||
transfer = getattr(session.path_lease, 'transfer_ownership', None)
|
||||
if transfer is not None:
|
||||
transfer(self.library_lease)
|
||||
session.path_lease.close()
|
||||
self._close_path_lease(session.path_lease)
|
||||
if self._icdb_active(): self.icdb_task.resume()
|
||||
|
||||
def _poll_native_backup(self):
|
||||
session = self._native_backup_session
|
||||
if session is None or self.busy or session.process.poll() is None:
|
||||
return
|
||||
self.native_backup_timer.stop()
|
||||
same_library = Path(self.mentor_lmc_path or self.lmc_edit.text()) == session.library
|
||||
same_library = self._native_backup_same_library()
|
||||
def read_result():
|
||||
import json
|
||||
result = json.loads(session.job.with_name('result.json').read_text('utf-8'))
|
||||
if Path(result['library']) != session.library or result['block'] != session.block:
|
||||
if (not self._native_backup_matches_library(result['library'], getattr(session, 'path_lease', None))
|
||||
or result['block'] != session.block):
|
||||
raise ValueError('原生会话返回的工程身份不一致。')
|
||||
refresh = (self._read_affected_records((session.block,))
|
||||
if result.get('safe_to_continue') is True and same_library else None)
|
||||
@@ -816,7 +1143,8 @@ class MainWindow(QWidget):
|
||||
self.status_label.setText('原生窗口退出尚未确认,请关闭窗口后检查释放。')
|
||||
self.output.append(f'{session.block} · 退出尚未确认:{error}\n{session.job}')
|
||||
self.busy = True; self._update()
|
||||
self.worker = ServiceWorker(read_result)
|
||||
self.stop.clear()
|
||||
self.worker = ServiceWorker(self._queued_action(read_result))
|
||||
self.worker.signals.succeeded.connect(completed)
|
||||
self.worker.signals.failed.connect(unconfirmed)
|
||||
self.worker.signals.finished.connect(self._finished)
|
||||
@@ -830,6 +1158,7 @@ class MainWindow(QWidget):
|
||||
if not names:
|
||||
return
|
||||
self.backup_dialog = BackupRecoveryDialog(names, self._backup_request, self)
|
||||
self.backup_dialog.native_queue = self.native_queue
|
||||
row = self.cbb_table.currentRow()
|
||||
if row >= 0 and self.cbb_table.item(row, 0).text() in names:
|
||||
self.backup_dialog.block_combo.setCurrentText(self.cbb_table.item(row, 0).text())
|
||||
@@ -847,6 +1176,7 @@ class MainWindow(QWidget):
|
||||
return self._request(name)
|
||||
|
||||
def _backup_started(self, name):
|
||||
self._invalidate_check_targets(self.mentor_lmc_path or self.loaded_path, [name])
|
||||
self.busy = True
|
||||
self._global_icdb_run = False
|
||||
self.ready_names.discard(name)
|
||||
@@ -864,7 +1194,7 @@ class MainWindow(QWidget):
|
||||
|
||||
def _backup_completed(self, name, result):
|
||||
if not result.safe_to_continue and self.library_lease is not None:
|
||||
self.library_lease.retain_for_recovery()
|
||||
self._retain_path_lease(self.library_lease, hold_busy=True)
|
||||
row = self._row_by_name.get(name)
|
||||
if row is not None and result.status != 'PASS':
|
||||
self.cbb_table.item(row, 2).setText('未知 / 需确认')
|
||||
@@ -881,6 +1211,7 @@ class MainWindow(QWidget):
|
||||
self._finished()
|
||||
|
||||
def _run(self, names, *, maintenance=False):
|
||||
if maintenance: return self._start_icdb_check(names)
|
||||
if self.busy or not self.loaded_path: return
|
||||
if self._native_backup_same_library():
|
||||
self.status_label.setText('请先关闭该库的版本与备份窗口。')
|
||||
@@ -897,8 +1228,8 @@ class MainWindow(QWidget):
|
||||
self._reimport_offers = ()
|
||||
self._global_icdb_run = maintenance
|
||||
self._icdb_completed = 0
|
||||
self.icdb_progress.setVisible(maintenance)
|
||||
self.icdb_phase.setVisible(maintenance)
|
||||
self.icdb_progress.setVisible(maintenance or self._icdb_active())
|
||||
self.icdb_phase.setVisible(maintenance or self._icdb_active())
|
||||
if maintenance:
|
||||
self.icdb_progress.setRange(0, len(requests))
|
||||
self.icdb_progress.setValue(0)
|
||||
@@ -922,10 +1253,14 @@ class MainWindow(QWidget):
|
||||
progress=lambda name, result: self.signals.event.emit({'block': name, 'stage': result.status,
|
||||
'error_category': result.error_category, 'evidence': str(result.evidence_path or ''),
|
||||
'detail': result.stderr or result.stdout}))
|
||||
report = write_batch_report(requests, results, self.data_root/'reports')
|
||||
if maintenance:
|
||||
from cbb_refresh_verify.icdb_maintenance import write_maintenance_report
|
||||
write_maintenance_report(requests, results, report, ())
|
||||
report = None
|
||||
try:
|
||||
report = write_batch_report(requests, results, self.data_root/'reports')
|
||||
if maintenance:
|
||||
from cbb_refresh_verify.icdb_maintenance import write_maintenance_report
|
||||
write_maintenance_report(requests, results, report, ())
|
||||
except Exception as error:
|
||||
self.signals.event.emit({'stage': 'report_failed', 'detail': str(error)})
|
||||
affected = [req.block_name for req, result in zip(requests, results) if result.status != 'SKIPPED']
|
||||
safe = all(result.safe_to_continue for result in results)
|
||||
refresh = self._read_affected_records(affected) if safe else None
|
||||
@@ -940,6 +1275,8 @@ class MainWindow(QWidget):
|
||||
path = Path(self.mentor_lmc_path or self.loaded_path)
|
||||
try:
|
||||
statuses = self.status_refresher(tuple(names), path)
|
||||
# Publish before yielding the native queue, ahead of Qt callbacks.
|
||||
self._publish_check_statuses(path, statuses)
|
||||
reasons = {name: reason for name in names
|
||||
if (reason := preflight_skip_reason(path, name))}
|
||||
return tuple(names), statuses, reasons, ''
|
||||
@@ -950,6 +1287,8 @@ class MainWindow(QWidget):
|
||||
|
||||
def _apply_refreshed_records(self, payload):
|
||||
names, statuses, reasons, error = payload
|
||||
self._publish_check_statuses(self.mentor_lmc_path or self.loaded_path,
|
||||
{name: statuses.get(name, 'UNKNOWN') for name in names})
|
||||
self.cbb_table.blockSignals(True)
|
||||
try:
|
||||
for name in names:
|
||||
@@ -1061,6 +1400,8 @@ class MainWindow(QWidget):
|
||||
|
||||
def _batch_done(self, outcome):
|
||||
results, report = outcome[:2]
|
||||
failure_report = failure_report_path(report) if report is not None else '未写入'
|
||||
report = report if report is not None else '未写入'
|
||||
from cbb_refresh_verify.reimport_recovery import offers_reimport
|
||||
self._reimport_offers = tuple((req, self._batch_records[req.block_name], result)
|
||||
for req, result in zip(self._batch_requests, results)
|
||||
@@ -1072,7 +1413,7 @@ class MainWindow(QWidget):
|
||||
else:
|
||||
self._apply_refreshed_records(refresh)
|
||||
if self.library_lease is not None and any(not result.safe_to_continue for result in results):
|
||||
self.library_lease.retain_for_recovery()
|
||||
self._retain_path_lease(self.library_lease, hold_busy=True)
|
||||
for result in results:
|
||||
if not result.safe_to_continue and result.evidence_path:
|
||||
self.recovery_path = result.evidence_path.parent
|
||||
@@ -1083,7 +1424,7 @@ class MainWindow(QWidget):
|
||||
repaired = sum(r.status == 'REPAIRED' for r in results)
|
||||
failed = len(results)-passed-skipped-checked-repaired
|
||||
text = (f'已结束:成功 {passed},失败 {failed},预检跳过 {len(self.skipped_names)},'
|
||||
f'队列未执行 {skipped}。\n完整日志:{report}\n仅失败日志:{failure_report_path(report)}')
|
||||
f'队列未执行 {skipped}。\n完整日志:{report}\n仅失败日志:{failure_report}')
|
||||
if self._global_icdb_run:
|
||||
from cbb_refresh_verify.icdb_maintenance import maintenance_counts
|
||||
counts = maintenance_counts(results)
|
||||
@@ -1091,7 +1432,7 @@ class MainWindow(QWidget):
|
||||
f'未发现异常 {counts["checked_without_repair"]},发现问题 {counts["issues_found"]},'
|
||||
f'占用 {counts["in_use"]},无法确认 {counts["unconfirmed"]},'
|
||||
f'取消 {counts["cancelled"]},队列未执行 {skipped}\n'
|
||||
f'完整日志:{report}\n仅失败日志:{failure_report_path(report)}')
|
||||
f'完整日志:{report}\n仅失败日志:{failure_report}')
|
||||
self.icdb_phase.setText('批量检查已结束')
|
||||
if any(not result.safe_to_continue for result in results):
|
||||
text += '\n未确认数据库或会话安全,已停止剩余校验。请查看恢复现场。'
|
||||
@@ -1124,6 +1465,21 @@ class MainWindow(QWidget):
|
||||
self.summary.setDetailedText(text)
|
||||
self.summary.setIcon(QMessageBox.Warning if failed else QMessageBox.Information)
|
||||
self._reimport_summary_action = None
|
||||
self._residual_release_action = None
|
||||
self._resume_batch_action = None
|
||||
self._resume_batch = None
|
||||
if any(not result.safe_to_continue for result in results):
|
||||
self._residual_release_action = self.summary.addButton('查看残留并释放…', QMessageBox.ActionRole)
|
||||
self._residual_release_action.clicked.connect(self.check_library_release)
|
||||
self._residual_release_action.setEnabled(False)
|
||||
names = [req.block_name for req, result in zip(self._batch_requests, results)
|
||||
if result.status == 'SKIPPED']
|
||||
if names:
|
||||
self._resume_batch = {'library': self._batch_requests[0].lmc_file, 'names': names,
|
||||
'maintenance': self._global_icdb_run, 'released': False}
|
||||
self._resume_batch_action = self.summary.addButton('继续未执行项', QMessageBox.ActionRole)
|
||||
self._resume_batch_action.clicked.connect(self._resume_released_batch)
|
||||
self._resume_batch_action.setEnabled(False)
|
||||
if self._reimport_offers:
|
||||
self.summary.setStandardButtons(QMessageBox.Close)
|
||||
self._reimport_summary_action = self.summary.addButton('选择副本恢复…', QMessageBox.ActionRole)
|
||||
@@ -1146,6 +1502,9 @@ class MainWindow(QWidget):
|
||||
self.version_dialog.show()
|
||||
|
||||
def request_stop(self):
|
||||
if self._icdb_active():
|
||||
self._stop_icdb_check()
|
||||
if not self.busy: return
|
||||
if self.version_dialog is not None:
|
||||
self.version_dialog.reject()
|
||||
management = getattr(self, 'management_dialog', None)
|
||||
@@ -1155,12 +1514,17 @@ class MainWindow(QWidget):
|
||||
'已请求取消;检查将停止,原生写入只等待安全结束,不强制终止。'); self._update()
|
||||
|
||||
def _failed(self, error):
|
||||
if self.library_lease is not None:
|
||||
self.library_lease.retain_for_recovery()
|
||||
from cbb_refresh_verify.operation_queue import QueueCancelled
|
||||
if self.library_lease is not None and not isinstance(error, QueueCancelled):
|
||||
self._retain_path_lease(self.library_lease, hold_busy=True)
|
||||
self._display_error(error)
|
||||
|
||||
def _display_error(self, error):
|
||||
self.status_label.setText(str(error)); self.output.append(str(error))
|
||||
if self.logging_context: self.logging_context.logger.error('cbb_worker_failed %s', error)
|
||||
|
||||
def _finished(self):
|
||||
if self._defer_mapping_finish(self._finished): return
|
||||
if self.version_dialog is not None:
|
||||
self.version_dialog.reject()
|
||||
self.version_dialog = None
|
||||
@@ -1176,16 +1540,45 @@ class MainWindow(QWidget):
|
||||
def recover(self):
|
||||
if not self.recovery_path: return
|
||||
try: os.startfile(str(self.recovery_path))
|
||||
except Exception as error: self._failed(error)
|
||||
except Exception as error: self._display_error(error)
|
||||
|
||||
def closeEvent(self, event):
|
||||
if self.busy:
|
||||
if self._close_ready:
|
||||
event.accept()
|
||||
elif self._closing:
|
||||
event.ignore()
|
||||
elif self._icdb_active():
|
||||
self._stop_icdb_check(); event.ignore()
|
||||
elif self.busy:
|
||||
self.request_stop(); event.ignore()
|
||||
else:
|
||||
self._closing = True
|
||||
self.busy = True; self._update()
|
||||
retained = None
|
||||
if self._native_backup_session is not None:
|
||||
self.native_backup_timer.stop()
|
||||
lease = self._native_backup_session.path_lease
|
||||
if lease is not None:
|
||||
lease.retain_for_recovery()
|
||||
self._release_library_lease()
|
||||
event.accept()
|
||||
retained = self._native_backup_session.path_lease
|
||||
lease, self.library_lease = self.library_lease, None
|
||||
def release():
|
||||
if retained is not None: retained.retain_for_recovery()
|
||||
if lease is not None and lease is not retained: lease.close()
|
||||
self._lease_action(release)
|
||||
self._close_when_idle()
|
||||
event.ignore()
|
||||
|
||||
def _close_when_idle(self):
|
||||
owners = [self, *self.icdb_tasks]
|
||||
for name in ('management_dialog', 'backup_dialog', 'release_dialog'):
|
||||
owners.append(getattr(self, name, None))
|
||||
active = False
|
||||
for owner in owners:
|
||||
try:
|
||||
pool = getattr(owner, 'pool', None)
|
||||
active = active or bool(pool is not None and pool.activeThreadCount())
|
||||
except RuntimeError:
|
||||
pass # Qt may already have deleted a closed dialog's pool.
|
||||
if self._lease_pending or active:
|
||||
QTimer.singleShot(20, self._close_when_idle)
|
||||
return
|
||||
self._close_ready = True
|
||||
self.close()
|
||||
@@ -34,6 +34,7 @@ class ManagementSignals(QObject):
|
||||
|
||||
class ManagementDialog(QDialog):
|
||||
completed = Signal(object)
|
||||
before_execute = Signal(object)
|
||||
|
||||
def __init__(self, requests, parent=None, *, adapter=None, runner=None, recovery_from=None):
|
||||
super().__init__(parent)
|
||||
@@ -41,6 +42,7 @@ class ManagementDialog(QDialog):
|
||||
self.template = self.templates[0]
|
||||
self.operation = self.template.operation
|
||||
self.adapter = adapter
|
||||
self.native_queue = None
|
||||
self.recovery_from = dict(recovery_from or {})
|
||||
self.runner = runner or run_management_batch
|
||||
if self.recovery_from and runner is None:
|
||||
@@ -160,8 +162,20 @@ class ManagementDialog(QDialog):
|
||||
return
|
||||
self.busy = True; self.executed = True
|
||||
self._enabled(False)
|
||||
self.worker = ServiceWorker(lambda: self.runner(requests, adapter=self.adapter, stop=self.stop,
|
||||
progress=self.signals.progress.emit))
|
||||
self.before_execute.emit([r.name for r in requests])
|
||||
def execute():
|
||||
action = lambda: self.runner(requests, adapter=self.adapter, stop=self.stop,
|
||||
progress=self.signals.progress.emit)
|
||||
if self.native_queue is None: return action()
|
||||
from ..operation_queue import QueueCancelled
|
||||
try:
|
||||
return self.native_queue.run(action, stop=self.stop, waiting=lambda: self.signals.progress.emit(
|
||||
{'stage': 'waiting_native_slot', 'detail': '已排队,等待当前检查结束'}))
|
||||
except QueueCancelled as error:
|
||||
from ..management import ManagementResult
|
||||
return [ManagementResult(r.operation, r.library, r.name, r.partition, r.source, r.auto_verify,
|
||||
'complete', 'BLOCKED', True, str(error)) for r in requests]
|
||||
self.worker = ServiceWorker(execute)
|
||||
self.worker.signals.succeeded.connect(self._result)
|
||||
self.worker.signals.failed.connect(self._failed)
|
||||
self.worker.signals.finished.connect(self._finished)
|
||||
@@ -176,6 +190,7 @@ class ManagementDialog(QDialog):
|
||||
def _progress(self, event):
|
||||
stage = str(event.get('stage', ''))
|
||||
text = f'{event.get("block", "")} {STAGE_LABELS.get(stage, RESULT_LABELS.get(stage, "正在处理"))}'
|
||||
if stage == 'waiting_native_slot': text = str(event.get('detail', '已排队,等待执行'))
|
||||
self.output.append(str(event))
|
||||
if 'copied_files' in event:
|
||||
text += f' {event["copied_files"]}/{event.get("total_files", "?")}'
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
"""User-confirmed, asynchronous native-session release."""
|
||||
from pathlib import Path
|
||||
from threading import Event
|
||||
|
||||
from PySide6.QtCore import QThreadPool, Signal
|
||||
from PySide6.QtWidgets import (QDialog, QVBoxLayout, QHBoxLayout, QLabel, QPushButton,
|
||||
QTableWidget, QTableWidgetItem, QHeaderView, QMessageBox)
|
||||
|
||||
from .workers import ServiceWorker
|
||||
|
||||
|
||||
class ResidualReleaseDialog(QDialog):
|
||||
released = Signal(object)
|
||||
before_release = Signal()
|
||||
|
||||
def __init__(self, library, evidence_dir, parent=None):
|
||||
super().__init__(parent)
|
||||
self.library, self.evidence_dir = Path(library), Path(evidence_dir)
|
||||
self.plan = None
|
||||
self.native_queue = None
|
||||
self.busy = False
|
||||
self.stop = Event()
|
||||
self._refresh_after = False
|
||||
self.pool = QThreadPool(self)
|
||||
self.setWindowTitle('释放残留会话')
|
||||
self.setModal(True)
|
||||
self.resize(760, 350)
|
||||
layout = QVBoxLayout(self)
|
||||
self.message = QLabel('正在检查当前库关联的会话…')
|
||||
self.message.setWordWrap(True)
|
||||
layout.addWidget(self.message)
|
||||
self.table = QTableWidget(0, 4)
|
||||
self.table.setHorizontalHeaderLabels(['工程', '程序', 'PID', '状态'])
|
||||
self.table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)
|
||||
self.table.horizontalHeader().setSectionResizeMode(3, QHeaderView.Stretch)
|
||||
self.table.setEditTriggers(QTableWidget.NoEditTriggers)
|
||||
layout.addWidget(self.table)
|
||||
buttons = QHBoxLayout()
|
||||
self.refresh_button = QPushButton('重新检查')
|
||||
self.confirm_button = QPushButton('确认释放')
|
||||
self.prompt_button = QPushButton('处理保存提示…')
|
||||
self.force_button = QPushButton('强制结束所列会话…')
|
||||
self.force_button.setEnabled(False)
|
||||
self.prompt_button.setEnabled(False)
|
||||
self.close_button = QPushButton('关闭')
|
||||
for button in (self.refresh_button, self.confirm_button, self.prompt_button, self.force_button, self.close_button): buttons.addWidget(button)
|
||||
layout.addLayout(buttons)
|
||||
self.refresh_button.clicked.connect(self.refresh)
|
||||
self.confirm_button.clicked.connect(self.confirm_release)
|
||||
self.close_button.clicked.connect(self.close)
|
||||
self.prompt_button.clicked.connect(self.answer_prompt)
|
||||
self.force_button.clicked.connect(self.force_release)
|
||||
self.table.itemSelectionChanged.connect(self._update_prompt)
|
||||
self.refresh()
|
||||
|
||||
def _start(self, action, completed):
|
||||
self.busy = True
|
||||
self.confirm_button.setEnabled(False)
|
||||
self.refresh_button.setEnabled(False)
|
||||
self.prompt_button.setEnabled(False)
|
||||
self.force_button.setEnabled(False)
|
||||
self.close_button.setText('停止释放')
|
||||
self.worker = ServiceWorker(action)
|
||||
self.worker.signals.succeeded.connect(completed)
|
||||
self.worker.signals.failed.connect(lambda error: self.message.setText(str(error)))
|
||||
self.worker.signals.finished.connect(self._finished)
|
||||
self.pool.start(self.worker)
|
||||
|
||||
def _finished(self):
|
||||
self.busy = False
|
||||
self.refresh_button.setEnabled(True)
|
||||
self.confirm_button.setEnabled(self.plan is not None)
|
||||
self.force_button.setEnabled(bool(self.plan and any(
|
||||
r.get('scope_confirmed', True) for r in self.plan['sessions'])))
|
||||
self.close_button.setText('关闭')
|
||||
self._update_prompt()
|
||||
if self._refresh_after:
|
||||
self._refresh_after = False
|
||||
self.refresh()
|
||||
|
||||
def _rows(self, sessions):
|
||||
self.table.setRowCount(len(sessions))
|
||||
for index, session in enumerate(sessions):
|
||||
for column, value in enumerate((session.get('project', ''), session['name'],
|
||||
session['pid'], session.get('detail', ''))):
|
||||
self.table.setItem(index, column, QTableWidgetItem(str(value)))
|
||||
if sessions: self.table.setCurrentCell(0, 0)
|
||||
|
||||
def _update_prompt(self):
|
||||
row = self.table.currentRow()
|
||||
rows = self.plan['sessions'] if self.plan else []
|
||||
self.prompt_button.setEnabled(not self.busy and 0 <= row < len(rows) and bool(rows[row].get('prompt')))
|
||||
|
||||
def answer_prompt(self):
|
||||
if self.busy or not self.plan: return
|
||||
row = self.table.currentRow()
|
||||
if row < 0: return
|
||||
session = self.plan['sessions'][row]
|
||||
prompt = session.get('prompt')
|
||||
if not prompt: return
|
||||
choice = QMessageBox.question(self, '关闭工程前保存', prompt['text']+
|
||||
'\n\n是:保存后关闭;否:放弃未保存更改;取消:保留会话。',
|
||||
QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel, QMessageBox.Cancel)
|
||||
code = {QMessageBox.Yes: 6, QMessageBox.No: 7, QMessageBox.Cancel: 2}[choice]
|
||||
from cbb_refresh_verify.residual_sessions import answer_save_question
|
||||
self._start(lambda: answer_save_question(session, code),
|
||||
lambda _: setattr(self, '_refresh_after', True))
|
||||
|
||||
def refresh(self):
|
||||
if self.busy: return
|
||||
from cbb_refresh_verify.library_lock import inspect_residual_sessions
|
||||
self.plan = None
|
||||
self.message.setText('正在检查当前库关联的会话…')
|
||||
def ready(plan):
|
||||
self.library = Path(plan['library'])
|
||||
self.plan = plan
|
||||
self._rows(plan['sessions'])
|
||||
text = ('确认后逐项正常关闭下列会话;有未保存更改时,可选择保存或保留。'
|
||||
if plan['sessions'] else '未发现活跃会话。')
|
||||
records = plan.get('previous_records', [])
|
||||
if records:
|
||||
dates = ', '.join(sorted({r['time'][:10] for r in records if r.get('time')}))
|
||||
text += f'\n有 {len(records)} 条历史操作记录'+(f'({dates})' if dates else '')+',确认后将复核并清理。'
|
||||
elif not plan['sessions']:
|
||||
text += '确认后将复查库占用状态。'
|
||||
self.message.setText(text)
|
||||
def inspect():
|
||||
from cbb_refresh_verify.network_path import select_library_file
|
||||
library = self.library if self.library.suffix.casefold() == '.lmc' else select_library_file(self.library)
|
||||
return inspect_residual_sessions(library)
|
||||
self._start(inspect, ready)
|
||||
|
||||
def force_release(self):
|
||||
if self.busy or not self.plan or not self.plan['sessions']: return
|
||||
targets = [r for r in self.plan['sessions'] if r.get('scope_confirmed', True)]
|
||||
if not targets: return
|
||||
names = '\n'.join(f'{r.get("project", "")} — {r["name"]} (PID {r["pid"]})' for r in targets)
|
||||
answer = QMessageBox.warning(self, '强制结束会话',
|
||||
'将强制结束以下进程,未保存的更改会丢失,正在写入的工程可能需要恢复。\n\n'+names+
|
||||
'\n\n仍要结束这些进程吗?', QMessageBox.Yes | QMessageBox.Cancel, QMessageBox.Cancel)
|
||||
if answer == QMessageBox.Yes: self.confirm_release(force=True)
|
||||
|
||||
def confirm_release(self, checked=False, *, force=False):
|
||||
if self.busy or self.plan is None: return
|
||||
from cbb_refresh_verify.library_lock import release_residual_sessions
|
||||
self.stop.clear()
|
||||
plan = self.plan
|
||||
self.before_release.emit()
|
||||
self.message.setText('正在逐项释放,请稍候…')
|
||||
def done(result):
|
||||
self.plan = {**plan, 'sessions': result['sessions']}
|
||||
self._rows(result['sessions'])
|
||||
count = sum(row['release_status'] == 'RELEASED' for row in result['sessions'])
|
||||
if result['status'] == 'RELEASE_CONFIRMED':
|
||||
self.plan = None
|
||||
self.message.setText(f'已释放 {count} 个会话,旧占用记录已解除。')
|
||||
self.released.emit(result['proof'])
|
||||
else:
|
||||
self.message.setText(f'已释放 {count} 个会话,其余会话或库状态仍待确认。'
|
||||
+ ('\n'+result['detail'] if result.get('detail') else '请处理原生窗口后重新检查。'))
|
||||
def execute():
|
||||
action = lambda: release_residual_sessions(plan, self.evidence_dir, stop=self.stop, force=force)
|
||||
return self.native_queue.run(action, stop=self.stop) if self.native_queue is not None else action()
|
||||
self._start(execute, done)
|
||||
|
||||
def closeEvent(self, event):
|
||||
if self.busy:
|
||||
self.stop.set()
|
||||
self.message.setText('正在停止释放,等待本次操作返回…')
|
||||
event.ignore()
|
||||
else:
|
||||
super().closeEvent(event)
|
||||
|
||||
def reject(self):
|
||||
if self.busy:
|
||||
self.stop.set()
|
||||
else:
|
||||
super().reject()
|
||||
@@ -7,6 +7,7 @@ once after cleanup if the worker was killed while a native file was open.
|
||||
from pathlib import Path
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import stat
|
||||
import tempfile
|
||||
import subprocess
|
||||
@@ -124,7 +125,7 @@ def collect_native_failure_logs(pcb_path, evidence_root, *, max_bytes=NATIVE_LOG
|
||||
|
||||
def _collect_icdb_recovery(source, evidence_root):
|
||||
"""Only promote a native error whose log changed after this launch."""
|
||||
from .icdb_recovery import read_log_failure
|
||||
from .icdb_recovery import read_log_failure, read_icdb_error
|
||||
root = Path(evidence_root)/'diagnostics'
|
||||
try:
|
||||
baseline = json.loads((root/'startup-log-baseline.json').read_text('utf-8'))
|
||||
@@ -135,6 +136,9 @@ def _collect_icdb_recovery(source, evidence_root):
|
||||
_, recovery = read_log_failure(source, checkpoint)
|
||||
if recovery:
|
||||
_write_record(root/'icdb-recovery.json', {**recovery, 'source': str(source)})
|
||||
message = read_icdb_error(source, checkpoint)
|
||||
if message:
|
||||
_write_record(root/'icdb-error-content.json', {'native_message': message, 'source': str(source)})
|
||||
except (OSError, ValueError, KeyError, TypeError):
|
||||
pass # Unknown freshness must not replace the original failure.
|
||||
|
||||
@@ -143,9 +147,56 @@ def _collect_icdb_recovery(source, evidence_root):
|
||||
def failure_logs_main(request_path):
|
||||
job = json.loads(Path(request_path).read_text(encoding='utf-8'))
|
||||
collect_native_failure_logs(job['pcb'], job['root'])
|
||||
collect_native_client_error(job['root'])
|
||||
return 0
|
||||
|
||||
|
||||
def collect_native_client_error(evidence_root):
|
||||
"""Read only this PCB PID's new iCDB manager log in the bounded log helper."""
|
||||
root = Path(evidence_root)/'diagnostics'
|
||||
try:
|
||||
context = json.loads((root/'native-client-context.json').read_text('utf-8'))
|
||||
pid, started = context['native_pid'], context['started_ns']
|
||||
if type(pid) is not int or pid <= 0 or type(started) is not int:
|
||||
return
|
||||
target = str(context['database']).replace('/', '\\').casefold()
|
||||
if not target:
|
||||
return
|
||||
from .icdb_recovery import decode_log
|
||||
for directory in Path(context['client_log_root']).glob(f'*-{pid}'):
|
||||
for source in directory.glob('*.iCDBManager.txt'):
|
||||
with source.open('rb') as stream:
|
||||
metadata = os.fstat(stream.fileno())
|
||||
if (metadata.st_mtime_ns < started
|
||||
or getattr(metadata, 'st_birthtime_ns', started) < started):
|
||||
continue
|
||||
header = stream.read(16*1024)
|
||||
stream.seek(0, os.SEEK_END)
|
||||
size = stream.tell()
|
||||
stream.seek(max(0, size-NATIVE_LOG_MAX_BYTES))
|
||||
tail = stream.read(NATIVE_LOG_MAX_BYTES)
|
||||
if not re.search(rf'\bPID\s*\[{pid}\]', decode_log(header)):
|
||||
continue
|
||||
# The native iCDB logger supplies the domain; a pathname in a
|
||||
# generic PCB error alone never establishes this identity.
|
||||
lines = decode_log(tail).splitlines()
|
||||
if size > NATIVE_LOG_MAX_BYTES:
|
||||
lines = lines[1:] # The first bounded-tail line may start mid-message.
|
||||
message = next((line for line in lines
|
||||
if re.search(r'\bERROR\s*:', line, re.I)
|
||||
and target in line.replace('/', '\\').casefold()), '')
|
||||
if message:
|
||||
target_file = root/'native-logs/current-icdb-manager.txt'
|
||||
target_file.parent.mkdir(parents=True, exist_ok=True)
|
||||
target_file.write_bytes(tail)
|
||||
_write_record(root/'icdb-error-content.json', {'native_message': 'iCDB: '+message,
|
||||
'source': str(source), 'native_pid': pid, 'started_ns': started,
|
||||
'database': context['database'], 'evidence': str(target_file)})
|
||||
return
|
||||
except (OSError, ValueError, KeyError, TypeError):
|
||||
pass # A missing/ambiguous native log must not replace the open failure.
|
||||
|
||||
|
||||
def capture_failure_logs_with_timeout(request_path, *, timeout_seconds=8):
|
||||
"""Post-cleanup retry in a killable helper, not a potentially stuck SMB thread."""
|
||||
request_path = Path(request_path)
|
||||
|
||||
@@ -14,6 +14,7 @@ native menu invocation happens on the worker's private desktop.
|
||||
from dataclasses import asdict, dataclass, field, replace
|
||||
from pathlib import Path
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import platform
|
||||
import re
|
||||
@@ -32,6 +33,22 @@ ERROR_TEXT = re.compile(r'failed|error|cannot connect|bad data', re.IGNORECASE)
|
||||
INVALID_NAME_CHARS = '\\/:*?"<>|'
|
||||
|
||||
|
||||
def _notify_progress(callback, *args):
|
||||
"""A failed observer cannot change native execution or release facts."""
|
||||
if callback is not None:
|
||||
try:
|
||||
callback(*args)
|
||||
except Exception:
|
||||
logging.getLogger(__name__).warning('Progress notification failed', exc_info=True)
|
||||
|
||||
|
||||
def _write_optional_evidence(path, value):
|
||||
try:
|
||||
path.write_text(json.dumps(value, ensure_ascii=False, default=str, indent=2), encoding='utf-8')
|
||||
except OSError:
|
||||
logging.getLogger(__name__).warning('Could not write diagnostic evidence %s', path, exc_info=True)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class VerifyRequest:
|
||||
lmc_file: Path
|
||||
@@ -511,7 +528,7 @@ def _cleanup_session_processes(root, *, lm_pid, target_pid, pcb, pcb_baseline, l
|
||||
except OSError:
|
||||
pass
|
||||
if progress:
|
||||
progress(event)
|
||||
_notify_progress(progress, event)
|
||||
|
||||
return cleanup_verify_processes(
|
||||
lm_pid,
|
||||
@@ -545,11 +562,12 @@ def run_verify(request, *, progress=None, flag_reader=None, process_runner=None,
|
||||
win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED)
|
||||
if not acquired:
|
||||
return VerifyResult('BLOCKED', stderr='已有 CBB 校验任务运行,请等待结束。',
|
||||
safe_to_continue=False)
|
||||
safe_to_continue=True, error_category='NATIVE_CHANNEL_BUSY')
|
||||
if request.maintenance:
|
||||
from .maintenance_entry import run_icdb_check
|
||||
return run_icdb_check(request, progress=progress, stop=stop)
|
||||
from .library_lock import LibraryLock, LibraryBusy
|
||||
import pywintypes
|
||||
if Path(request.lmc_file).is_file():
|
||||
try:
|
||||
library_lock = LibraryLock(request.lmc_file, checkpoint=False,
|
||||
@@ -557,6 +575,8 @@ def run_verify(request, *, progress=None, flag_reader=None, process_runner=None,
|
||||
library_lock.__enter__()
|
||||
except LibraryBusy as error:
|
||||
return VerifyResult('FAIL', stderr=str(error), error_category='LIBRARY_IN_USE')
|
||||
except (OSError, pywintypes.error) as error:
|
||||
return VerifyResult('FAIL', stderr=str(error), error_category='LIBRARY_ACCESS_FAILED')
|
||||
release_confirmed = False
|
||||
result = _run_verify_serialized(
|
||||
request, progress=progress, flag_reader=flag_reader,
|
||||
@@ -726,23 +746,24 @@ def _run_verify_serialized(request, *, progress=None, flag_reader=None, process_
|
||||
error_stage=(result.error_stage or (unfinished[-1] if unfinished else 'execution')
|
||||
if result.status not in {"PASS", "SKIPPED"} else ""))
|
||||
if result.evidence_path:
|
||||
result.evidence_path.write_text(json.dumps(
|
||||
{'block_name': request.block_name, **asdict(result)},
|
||||
ensure_ascii=False, default=str, indent=2), encoding='utf-8')
|
||||
result.evidence_path.with_name('performance.json').write_text(json.dumps({
|
||||
_write_optional_evidence(result.evidence_path, {'block_name': request.block_name, **asdict(result)})
|
||||
_write_optional_evidence(result.evidence_path.with_name('performance.json'), {
|
||||
'block_name': request.block_name, 'status': result.status,
|
||||
'unit': 'seconds', 'timings_seconds': durations,
|
||||
'incomplete_timing_phases': unfinished,
|
||||
'clock': 'monotonic; save helper subphases: VBScript Timer (midnight adjusted)',
|
||||
'notes': 'phase totals overlap action/call subphases; skipped phases are absent',
|
||||
}, ensure_ascii=False, indent=2), encoding='utf-8')
|
||||
})
|
||||
if progress:
|
||||
progress({'stage': 'performance', 'block': request.block_name,
|
||||
_notify_progress(progress, {'stage': 'performance', 'block': request.block_name,
|
||||
'timings_seconds': durations, 'incomplete_timing_phases': unfinished,
|
||||
'detail': ' '.join(f'{key}={value:.3f}s' for key, value in durations.items())})
|
||||
if request.logging_context:
|
||||
request.logging_context.logger.info('operation=cbb_verify block=%s status=%s flag=%s evidence=%s error=%s timings_seconds=%s',
|
||||
request.block_name, result.status, result.library_flag, result.evidence_path, result.stderr, durations)
|
||||
try:
|
||||
request.logging_context.logger.info('operation=cbb_verify block=%s status=%s flag=%s evidence=%s error=%s timings_seconds=%s',
|
||||
request.block_name, result.status, result.library_flag, result.evidence_path, result.stderr, durations)
|
||||
except Exception:
|
||||
logging.getLogger(__name__).warning('Operation logging failed', exc_info=True)
|
||||
return result
|
||||
|
||||
|
||||
@@ -756,12 +777,14 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
not depend on the host's port reservations.
|
||||
"""
|
||||
root = Path(request.evidence_dir).resolve()/('verify-' + uuid4().hex[:12])
|
||||
root.mkdir(parents=True, exist_ok=False)
|
||||
try:
|
||||
root.mkdir(parents=True, exist_ok=False)
|
||||
except OSError as error:
|
||||
return VerifyResult('FAIL', stderr=f'无法创建操作记录目录:{error}')
|
||||
fingerprint = runtime_fingerprint(request.mentor_bin)
|
||||
(root/'runtime.json').write_text(
|
||||
json.dumps(fingerprint, ensure_ascii=False, indent=2), encoding='utf-8')
|
||||
_write_optional_evidence(root/'runtime.json', fingerprint)
|
||||
if progress:
|
||||
progress({'stage': 'runtime_fingerprint', 'block': request.block_name,
|
||||
_notify_progress(progress, {'stage': 'runtime_fingerprint', 'block': request.block_name,
|
||||
**fingerprint})
|
||||
result_path = root/'result.json'
|
||||
runner = process_runner or (lambda command, timeout, cwd:
|
||||
@@ -797,7 +820,7 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
return finish(VerifyResult('BLOCKED', stderr=str(error)))
|
||||
command = build_content_check_command(request, executable)
|
||||
if progress:
|
||||
progress({'stage': 'content_check_start', 'block': request.block_name,
|
||||
_notify_progress(progress, {'stage': 'content_check_start', 'block': request.block_name,
|
||||
'detail': ' '.join(command)})
|
||||
timing.begin('content_check')
|
||||
try:
|
||||
@@ -819,7 +842,7 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
stdout=stdout, report_path=report, content_check_exit_code=exit_code,
|
||||
safe_to_continue=not timed_out))
|
||||
if progress:
|
||||
progress({'stage': 'content_check_done', 'block': request.block_name, 'status': 'PASS'})
|
||||
_notify_progress(progress, {'stage': 'content_check_done', 'block': request.block_name, 'status': 'PASS'})
|
||||
|
||||
# Sampling cannot establish that the whole native port range is unusable.
|
||||
from .mentor_adapter import icdb_ports_bindable
|
||||
@@ -827,7 +850,7 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
ports_ok, ports_detail = check_ports()
|
||||
if not ports_ok:
|
||||
if progress:
|
||||
progress({'stage': 'port_warning', 'block': request.block_name, 'detail': ports_detail})
|
||||
_notify_progress(progress, {'stage': 'port_warning', 'block': request.block_name, 'detail': ports_detail})
|
||||
if request.strict_port_check:
|
||||
return finish(VerifyResult('BLOCKED', stderr=ports_detail))
|
||||
|
||||
@@ -844,14 +867,17 @@ 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')}
|
||||
consent = None
|
||||
if request.post_repair_proof is not None:
|
||||
from .post_repair_consent import PostRepairProof, ConsentController, exact_prompt
|
||||
if not isinstance(request.post_repair_proof, PostRepairProof):
|
||||
return finish(VerifyResult('BLOCKED', stderr='POST_REPAIR_PROOF_REQUIRED', safe_to_continue=False))
|
||||
job['post_repair_consent'] = request.post_repair_proof.for_job(job)
|
||||
consent = ConsentController(request.post_repair_proof, job)
|
||||
job_path = root/'request.json'
|
||||
job_path.write_text(json.dumps(job, ensure_ascii=False), encoding='utf-8')
|
||||
try:
|
||||
if request.post_repair_proof is not None:
|
||||
from .post_repair_consent import PostRepairProof, ConsentController, exact_prompt
|
||||
if not isinstance(request.post_repair_proof, PostRepairProof):
|
||||
return finish(VerifyResult('BLOCKED', stderr='POST_REPAIR_PROOF_REQUIRED'))
|
||||
job['post_repair_consent'] = request.post_repair_proof.for_job(job)
|
||||
consent = ConsentController(request.post_repair_proof, job)
|
||||
job_path.write_text(json.dumps(job, ensure_ascii=False), encoding='utf-8')
|
||||
except Exception as error:
|
||||
return finish(VerifyResult('FAIL', stderr=str(error)))
|
||||
events = root/'events.jsonl'
|
||||
offset = 0
|
||||
target_pid = None
|
||||
@@ -871,10 +897,13 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
lock_status = win32event.WaitForSingleObject(mutex, 0)
|
||||
if lock_status not in (win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED):
|
||||
mutex.Close()
|
||||
return finish(VerifyResult('BLOCKED', stderr='已有 CBB 校验任务运行,请等待结束。', safe_to_continue=False))
|
||||
return finish(VerifyResult('BLOCKED', stderr='已有 CBB 校验任务运行;本次未启动。',
|
||||
safe_to_continue=True, error_category='NATIVE_CHANNEL_BUSY'))
|
||||
worker_launch_attempted = False
|
||||
try:
|
||||
timing.begin('worker_setup')
|
||||
with (root/'worker.log').open('w', encoding='utf-8') as log:
|
||||
worker_launch_attempted = True
|
||||
if request.interactive_input:
|
||||
process = DesktopWorker(
|
||||
worker_command(job_path), None, interactive_input=True)
|
||||
@@ -892,9 +921,10 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
if hasattr(process, 'start_companion'):
|
||||
from .dialog_agent import DialogAgentClient
|
||||
from .dialog_rules import default_rules_path, load_rules
|
||||
dialog_agent = DialogAgentClient.start(process, root/'dialog-agent')
|
||||
dialog_agent = DialogAgentClient.start(process, root/'dialog-agent', stop=stop)
|
||||
dialog_supervisor = DialogSupervisor(
|
||||
AgentDialogBackend(dialog_agent),
|
||||
AgentDialogBackend(dialog_agent, pids=lambda: {
|
||||
int(pid) for pid in (target_pid, lm_pid, launcher_pid) if pid}),
|
||||
rules=load_rules(default_rules_path()),
|
||||
)
|
||||
else:
|
||||
@@ -907,6 +937,8 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
desktop=process.desktop,
|
||||
pids=lambda: ({value for value in (target_pid, lm_pid) if value is not None}),
|
||||
)
|
||||
if stop is not None and stop.is_set():
|
||||
raise InterruptedError('VERIFY_CANCELLED: 启动已取消,未启动 PCB')
|
||||
Path(job['start_gate']).touch()
|
||||
while process.poll() is None:
|
||||
if stop is not None and stop.is_set():
|
||||
@@ -947,7 +979,7 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
0.1, float(request.timeout_seconds))
|
||||
deadline.touch()
|
||||
last_activity_key = activity_key
|
||||
if progress: progress(event)
|
||||
if progress: _notify_progress(progress, event)
|
||||
offset = stream.tell()
|
||||
if verify_invoked and target_pid is None and time.monotonic() - last_observation >= .5:
|
||||
from .post_verify_diagnostics import observe_post_verify
|
||||
@@ -1051,7 +1083,7 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
if dispatch_failure is not None:
|
||||
status, detail = dispatch_failure
|
||||
if progress:
|
||||
progress({
|
||||
_notify_progress(progress, {
|
||||
'stage': 'verify_dispatch_failed',
|
||||
'block': request.block_name,
|
||||
'detail': detail,
|
||||
@@ -1070,7 +1102,21 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
except Exception as error:
|
||||
if 'process' in locals() and process.poll() is None:
|
||||
_stop_worker(process)
|
||||
return finish(VerifyResult('FAIL', stderr=str(error), safe_to_continue=False))
|
||||
launch_release = getattr(error, 'worker_launch_release', None) if 'process' not in locals() else None
|
||||
if not worker_launch_attempted:
|
||||
launch_release = {'process_created': False, 'worker_exited': True,
|
||||
'safe_to_continue': True, 'remaining_pids': []}
|
||||
no_launch = (isinstance(launch_release, dict)
|
||||
and launch_release.get('process_created') is False
|
||||
and launch_release.get('worker_exited') is True
|
||||
and launch_release.get('safe_to_continue') is True
|
||||
and launch_release.get('remaining_pids') == [])
|
||||
if no_launch:
|
||||
_write_optional_evidence(root/'session-release.json', {
|
||||
**launch_release, 'block': request.block_name, 'library': str(request.lmc_file),
|
||||
'worker_pid': None})
|
||||
status = 'CANCELLED' if stop is not None and stop.is_set() else 'FAIL'
|
||||
return finish(VerifyResult(status, stderr=str(error), safe_to_continue=no_launch))
|
||||
finally:
|
||||
close_errors = []
|
||||
worker_exited = False
|
||||
@@ -1178,16 +1224,16 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
def record_attempt(record):
|
||||
bridge_records.append(record)
|
||||
if progress:
|
||||
progress({'stage': 'library_flag_probe', 'block': request.block_name, **record})
|
||||
_notify_progress(progress, {'stage': 'library_flag_probe', 'block': request.block_name, **record})
|
||||
try:
|
||||
probe = read_library_flag_with_retry(
|
||||
flag_reader or read_library_flag_if_available, Path(request.lmc_file),
|
||||
request.block_name, on_attempt=record_attempt)
|
||||
result = apply_post_verify_status(result, probe)
|
||||
result = replace(result, bridge_attempts=tuple(bridge_records))
|
||||
(root/'bridge-status.json').write_text(json.dumps(bridge_records, ensure_ascii=False, indent=2), encoding='utf-8')
|
||||
_write_optional_evidence(root/'bridge-status.json', bridge_records)
|
||||
if progress:
|
||||
progress({'stage': 'library_flag', 'block': request.block_name,
|
||||
_notify_progress(progress, {'stage': 'library_flag', 'block': request.block_name,
|
||||
'library_flag': result.library_flag, 'detail': result.library_flag_detail})
|
||||
finally:
|
||||
timing.end('library_flag')
|
||||
@@ -1216,7 +1262,7 @@ def run_batch(requests, max_workers=1, verifier=None, *, stop=None, progress=Non
|
||||
queue_stop = queue_stop or result.status in {'QUEUE_STOP', 'CANCELLED'} or not result.safe_to_continue
|
||||
if queue_stop and stop is not None:
|
||||
stop.set()
|
||||
if progress: progress(request.block_name, result)
|
||||
if progress: _notify_progress(progress, request.block_name, result)
|
||||
return results
|
||||
|
||||
|
||||
@@ -1273,7 +1319,7 @@ def write_batch_report(requests, results, root):
|
||||
lines = ['CBB Verify 批量结果',
|
||||
'流程: LMC 原生 Verify / ReusableCircuit PCB -> Project Integration -> Save/Close -> IsVerifiedReuseBlock READY(金标准)']
|
||||
if requests and all(req.maintenance for req in requests):
|
||||
lines = ['ICDB 批量检查结果', '流程: 原生 Project Backup 加载检查;不执行 Repair、Restore 或 CBB 校验。']
|
||||
lines = ['ICDB 批量检查结果', '流程: 原生 PCB 打开检查;不执行 Repair、Restore 或 CBB 校验。']
|
||||
for req, result in zip(requests, results):
|
||||
detail = _report_field(result.stderr or result.stdout.strip()[:200])
|
||||
seconds = ' '.join(f'{key}={value:.3f}s' +
|
||||
|
||||
Reference in new issue
Block a user