190 lines
11 KiB
Python
190 lines
11 KiB
Python
"""User-requested native inspection of a project with an existing advertisement.
|
|
|
|
An advertisement is never deleted, quarantined or called stale by this module.
|
|
Exclusive access permits a backed-up official inspection, not ordinary Verify.
|
|
"""
|
|
from contextlib import contextmanager, ExitStack
|
|
from dataclasses import asdict, replace
|
|
import json
|
|
import os
|
|
from pathlib import Path, PureWindowsPath
|
|
import re
|
|
from uuid import uuid4
|
|
|
|
|
|
def assert_native_idle():
|
|
import win32com.client
|
|
from .native_management import _retained_workers
|
|
if any(worker.poll() is None 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',
|
|
'python.exe', 'pythonw.exe', 'CbbRefreshVerify.exe')
|
|
service = win32com.client.GetObject('winmgmts:')
|
|
query = 'SELECT ProcessId, Name, CommandLine FROM Win32_Process WHERE ' + ' OR '.join(
|
|
f"Name='{name}'" for name in names)
|
|
owners = []
|
|
for item in service.ExecQuery(query):
|
|
if int(item.ProcessId) == os.getpid():
|
|
continue
|
|
name, command = str(item.Name).casefold(), str(item.CommandLine or '').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')):
|
|
owners.append({'pid': int(item.ProcessId), 'name': str(item.Name)})
|
|
if owners:
|
|
raise ValueError(f'MAINTENANCE_OWNER_ACTIVE: 请正常关闭原生程序/操作助手:{owners}')
|
|
|
|
|
|
def address_snapshot(paths):
|
|
from .scoped_manifest import hash_file
|
|
return {str(path.resolve()): {'sha256': hash_file(path), 'size': path.stat().st_size,
|
|
'mtime_ns': path.stat().st_mtime_ns}
|
|
for path in paths}
|
|
|
|
|
|
def select_maintenance_target(request):
|
|
from .verify_runner import preflight
|
|
from .backup_recovery import _project_text
|
|
from .native_repair import RepairTarget
|
|
from .scoped_manifest import scan_tree
|
|
if request.maintenance is not True:
|
|
raise ValueError('MAINTENANCE_INTENT_REQUIRED')
|
|
project, pcb = preflight(request)
|
|
scan_tree(project.parent)
|
|
candidates = []
|
|
for candidate in (project, pcb.parent/'pcb.prj'):
|
|
if not candidate.is_file():
|
|
raise ValueError('MAINTENANCE_TARGET_UNCONFIRMED: 缺少工程配置')
|
|
text = _project_text(candidate)
|
|
values = re.findall(r'^KEY iCDBDir "([^"]*)"', text, re.M)
|
|
if candidate != project and not re.search(r'^KEY iCDBDir\b', text, re.M):
|
|
continue
|
|
if (len(values) != 1 or not values[0] or PureWindowsPath(values[0]).drive
|
|
or PureWindowsPath(values[0]).root):
|
|
raise ValueError('MAINTENANCE_TARGET_UNCONFIRMED: iCDBDir 必须唯一且为工程内相对路径')
|
|
database = (candidate.parent/values[0]).resolve()
|
|
# The proven Project Backup route binds PRJ.parent/database; do not
|
|
# guess alternate stores or route shared data through another PRJ.
|
|
if database != (candidate.parent/'database').resolve() or not database.is_relative_to(project.parent.resolve()):
|
|
raise ValueError('MAINTENANCE_TARGET_UNCONFIRMED: 未验证的 PRJ 数据库映射')
|
|
if not (database/'icdb.dat').is_file():
|
|
raise ValueError('MAINTENANCE_TARGET_UNCONFIRMED: 缺少 icdb.dat')
|
|
candidates.append(RepairTarget(candidate, candidate.parent/'database'))
|
|
addresses = [path for path in scan_tree(Path(request.lmc_file).parent)
|
|
if path.name.casefold() == 'saddress.adr']
|
|
if len(addresses) != 1:
|
|
raise ValueError('MAINTENANCE_TARGET_UNCONFIRMED: 需要唯一工程地址记录;共享或多个数据库不能推测修复')
|
|
matches = [target for target in candidates
|
|
if (target.database/'cdbsvr/sAddress.adr').resolve() == addresses[0].resolve()]
|
|
if len(matches) != 1:
|
|
raise ValueError('SHARED_DATABASE_REPAIR_UNSUPPORTED: 地址记录不属于唯一匹配的工程数据库')
|
|
return matches[0], project, pcb, addresses
|
|
|
|
|
|
@contextmanager
|
|
def maintenance_target_guard(request, expected=None):
|
|
"""Simultaneously hold native database files, preserving every address."""
|
|
import win32con, win32file
|
|
from .scoped_manifest import scan_tree, hash_file
|
|
target, project, pcb, addresses = select_maintenance_target(request)
|
|
baseline = address_snapshot(addresses)
|
|
context = {'library': str(Path(request.lmc_file).resolve()), 'block': request.block_name,
|
|
'project': str(target.project.resolve()), 'database': str(target.database.resolve()),
|
|
'addresses': baseline,
|
|
'engineering_references': {str(p.resolve()): hash_file(p)
|
|
for p in (project, pcb, pcb.parent/'pcb.prj')}}
|
|
if expected is not None and context != expected:
|
|
raise ValueError('MAINTENANCE_SOURCE_CHANGED: 目标或地址记录在检查后变化')
|
|
assert_native_idle()
|
|
entries = scan_tree(Path(request.lmc_file).parent)
|
|
files = [path for path in entries if path.is_file() and (
|
|
path.suffix.casefold() == '.lmc' or path.name.casefold() in ('icdb.dat', 'layoutdb.lyt'))]
|
|
with ExitStack() as stack:
|
|
for path in files:
|
|
handle = win32file.CreateFile(str(path), win32con.GENERIC_READ, 0, None,
|
|
win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None)
|
|
stack.callback(handle.Close)
|
|
assert_native_idle()
|
|
current_addresses = [p for p in scan_tree(Path(request.lmc_file).parent)
|
|
if p.name.casefold() == 'saddress.adr']
|
|
if address_snapshot(current_addresses) != baseline:
|
|
raise ValueError('MAINTENANCE_SOURCE_CHANGED: 地址记录在检查期间变化')
|
|
yield {'target': target, 'context': context, 'project': project, 'pcb': pcb}
|
|
|
|
|
|
def maintenance_needed(request):
|
|
from .library_lock import has_blocker
|
|
from .icdb_ownership import unreleased_addresses
|
|
from .verify_runner import preflight
|
|
if has_blocker(request.lmc_file):
|
|
return True
|
|
project, pcb = preflight(request)
|
|
return bool(unreleased_addresses(request.lmc_file, project, pcb))
|
|
|
|
|
|
def run_existing_address_maintenance(request, *, verify, progress=None):
|
|
from .library_lock import LibraryLock
|
|
from .native_repair import run_native_repair, native_success_confirmed, repair_release_state
|
|
from .verify_runner import VerifyResult
|
|
root = Path(request.evidence_dir).resolve()/('maintenance-' + 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):
|
|
return VerifyResult('BLOCKED', stderr='维护证据必须位于目标库之外', safe_to_continue=False)
|
|
root.mkdir(parents=True, exist_ok=False)
|
|
record = {'operation': 'explicit_project_maintenance', 'library': str(request.lmc_file),
|
|
'block': request.block_name, 'stage': 'preflight'}
|
|
report = root/'result.json'
|
|
owner_safe = False
|
|
recovery = None
|
|
def emit(stage, **values):
|
|
record['stage'] = stage
|
|
if progress: progress({'stage': stage, 'block': request.block_name, **values})
|
|
def save(result):
|
|
result = replace(result, evidence_path=report)
|
|
record['result'] = asdict(result)
|
|
report.write_text(json.dumps(record, ensure_ascii=False, default=str, indent=2), encoding='utf-8')
|
|
return result
|
|
try:
|
|
lease = LibraryLock.for_maintenance(request.lmc_file, root/'takeover',
|
|
lambda: maintenance_target_guard(request), safe_to_release=lambda: owner_safe)
|
|
with lease:
|
|
checked = lease.maintenance_proof
|
|
target, context = checked['target'], checked['context']
|
|
record['maintenance_context'] = context
|
|
native_root = root/'native-repair'; native_root.mkdir()
|
|
attempt = native_root/'attempt.json'
|
|
with attempt.open('x', encoding='utf-8') as stream:
|
|
json.dump({'intent': 'explicit_maintenance', 'target': asdict(target),
|
|
'maintenance_context': context}, stream, default=str, ensure_ascii=False)
|
|
emit('native_repair_start', detail='先完整备份工程与地址记录,再由官方工具检查/修复')
|
|
# Repeat immediately before dispatch; worker repeats after complete
|
|
# backup and before launching its native process as well.
|
|
with maintenance_target_guard(request, context): pass
|
|
recovery = run_native_repair(target, native_root, mentor_bin=request.mentor_bin,
|
|
timeout_seconds=max(60, request.timeout_seconds), progress=progress,
|
|
maintenance_context=context)
|
|
assert_native_idle()
|
|
recovery = {**recovery, 'native_status': recovery.get('status'), 'validation_passed': False}
|
|
recovery['release'] = repair_release_state(request, target, recovery)
|
|
safe = recovery['release'].get('safe_to_continue') is True
|
|
owner_safe = safe
|
|
if recovery.get('status') == 'REPAIRED' and safe and native_success_confirmed(target, recovery):
|
|
emit('repair_verify', detail='原生修复及释放已确认,重新打开同一工程校验')
|
|
owner_safe = False
|
|
verified = verify(replace(request, maintenance=False, auto_repair=False))
|
|
owner_safe = verified.safe_to_continue
|
|
good = verified.status == 'PASS' and verified.library_flag == 'GREEN' and owner_safe
|
|
recovery.update(status='REPAIRED' if good else 'REPAIR_VALIDATION_FAILED',
|
|
validation_passed=good, validation_evidence=str(verified.evidence_path or ''))
|
|
return save(replace(verified, status='PASS' if good else 'FAIL',
|
|
recovery_attempts=(recovery,)))
|
|
if recovery.get('status') == 'REPAIRED':
|
|
recovery['status'] = 'UNCONFIRMED'; owner_safe = False
|
|
return save(VerifyResult('FAIL', stderr=f'{recovery["status"]}: {recovery.get("detail", "原生维护未确认修复")}',
|
|
safe_to_continue=owner_safe, recovery_attempts=(recovery,), error_category='ICDB_MAINTENANCE_RESULT'))
|
|
except Exception as error:
|
|
return save(VerifyResult('BLOCKED' if recovery is None else 'FAIL', stderr=str(error),
|
|
safe_to_continue=False, recovery_attempts=(recovery,) if recovery else (),
|
|
error_category='ICDB_MAINTENANCE_BLOCKED'))
|