feat: prefer isolated native CLI for component inventory
This commit is contained in:
1 parent
72853900de
commit
0415ecc73c
10 files changed
+629
-1
No files matched your search
@@ -144,7 +144,8 @@ class DiscoveryCache:
|
||||
if entry is not None:
|
||||
stamp, covered, has_components, discovery = entry
|
||||
if (before is not None and before == stamp and requested <= covered
|
||||
and (not collect_components or has_components)):
|
||||
and (not collect_components or has_components)
|
||||
and (collect_components or getattr(discovery, 'complete_sheet_manifest', True))):
|
||||
self._entries[key] = entry
|
||||
check_cancelled(stop_event)
|
||||
return deepcopy(discovery)
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
"""Supervise official inventory CLIs on a disposable, isolated database copy."""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import tempfile
|
||||
import time
|
||||
from uuid import uuid4
|
||||
|
||||
from .errors import TaskCenterError
|
||||
from .isolated_desktop import PrivateDesktop
|
||||
from .native_inventory_protocol import NativeInventoryUnsupported, read_ascii_discovery, read_native_text
|
||||
from .operation_control import check_cancelled, report_progress
|
||||
|
||||
|
||||
def _hash(path):
|
||||
with path.open('rb') as stream:
|
||||
return hashlib.file_digest(stream, 'sha256').hexdigest()
|
||||
|
||||
|
||||
def _verify_sources(hashes):
|
||||
try:
|
||||
if any(path.resolve(strict=True) != path or _hash(path) != digest for path, digest in hashes.items()):
|
||||
raise OSError('source identity changed')
|
||||
except OSError as error:
|
||||
raise TaskCenterError('target_identity', '原生采集期间源工程或数据库已变化或无法核验,请重新导入') from error
|
||||
|
||||
|
||||
def _project_options(project):
|
||||
text = read_native_text(project)
|
||||
def option(name, default=None):
|
||||
values = set(re.findall(r'^KEY ' + name + r' "([^"\r\n]*)"\s*$', text, re.MULTILINE))
|
||||
if not values and default is not None:
|
||||
return default
|
||||
if len(values) != 1:
|
||||
raise NativeInventoryUnsupported(f'工程 {name} 未明确指定唯一值')
|
||||
return values.pop()
|
||||
block = option('RootBlock')
|
||||
if not re.fullmatch(r'[\w .()+-]+', block) or block in ('.', '..'):
|
||||
raise NativeInventoryUnsupported('工程根块名称不适合原生清单导出')
|
||||
snapshot = option('FrontEndSnapshot', 'DxD')
|
||||
if snapshot.casefold() != 'dxd':
|
||||
raise NativeInventoryUnsupported('当前工程不是已验证的 DxD 数据库快照')
|
||||
database = (project.parent / option('iCDBDir') / 'icdb.dat').resolve(strict=True)
|
||||
if not database.is_relative_to(project.parent) or not database.is_file():
|
||||
raise NativeInventoryUnsupported('数据库不在当前工程目录内')
|
||||
return text, block, snapshot, database
|
||||
|
||||
|
||||
class NativeInventoryReader:
|
||||
def __init__(self, data_root, *, tool_directory=None, desktop_factory=None,
|
||||
temporary_root=None, timeout=30):
|
||||
self.data_root = Path(data_root)
|
||||
self.tool_directory = tool_directory
|
||||
self.desktop_factory = desktop_factory or PrivateDesktop
|
||||
self.temporary_root = temporary_root
|
||||
self.timeout = timeout
|
||||
|
||||
def _tools(self):
|
||||
directory = self.tool_directory
|
||||
if directory is None:
|
||||
from .isolated_cad import _designer_executable
|
||||
directory = _designer_executable().parents[3] / 'iCDB/win32/bin'
|
||||
directory = Path(directory).resolve(strict=True)
|
||||
tools = (directory / 'icdb2ascii.exe',)
|
||||
if not all(path.is_file() for path in tools):
|
||||
raise NativeInventoryUnsupported('本机未安装完整的原生器件清单工具')
|
||||
return tools
|
||||
|
||||
def read(self, project, old_part_numbers, *, stop_event=None, on_progress=None):
|
||||
check_cancelled(stop_event)
|
||||
try:
|
||||
project = Path(project).resolve(strict=True)
|
||||
text, block, snapshot, database = _project_options(project)
|
||||
tools = self._tools()
|
||||
except (NativeInventoryUnsupported, OSError, ImportError, UnicodeError, TaskCenterError) as error:
|
||||
report_progress(on_progress, f'使用 CAD 核验位号:{str(error)[:160]}')
|
||||
return None
|
||||
return self._read(project, text, block, snapshot, database, tools, old_part_numbers,
|
||||
stop_event=stop_event, on_progress=on_progress)
|
||||
|
||||
def _read(self, project, text, block, snapshot, database, tools, old_part_numbers, *, stop_event, on_progress):
|
||||
token = uuid4().hex
|
||||
evidence = self.data_root / 'quick-run-history' / ('native-inventory-' + token)
|
||||
evidence.mkdir(parents=True, exist_ok=False)
|
||||
base = Path(self.temporary_root or Path(os.environ.get('LOCALAPPDATA') or tempfile.gettempdir())
|
||||
/ 'DxProductivity' / 'native-inventory').resolve()
|
||||
base.mkdir(parents=True, exist_ok=True)
|
||||
workspace = Path(tempfile.mkdtemp(prefix='dx-cli-', dir=base)).resolve()
|
||||
desktop = self.desktop_factory('dx-cli-' + token, enabled=True)
|
||||
record = {'backend': 'native_cli', 'project': str(project), 'state': 'reading',
|
||||
'workspace': str(workspace), 'tools': []}
|
||||
started = time.monotonic()
|
||||
clean = False
|
||||
result = None
|
||||
source_hashes = {}
|
||||
try:
|
||||
source_hashes = {project: _hash(project), database: _hash(database)}
|
||||
if read_native_text(project) != text:
|
||||
raise TaskCenterError('target_identity', '创建原生采集快照时工程配置已变化,请重新导入')
|
||||
source = workspace / 'input.prj'
|
||||
target_database = workspace / 'database'
|
||||
target_database.mkdir()
|
||||
shutil.copyfile(database, target_database / 'icdb.dat')
|
||||
# No server address files or running database directory are copied.
|
||||
text = re.sub(r'^KEY iCDBDir "[^"\r\n]*"\s*$',
|
||||
'KEY iCDBDir "database"', text, flags=re.MULTILINE)
|
||||
text = re.sub(r'^KEY DedicatedServerName "[^"\r\n]*"\s*$',
|
||||
'KEY DedicatedServerName ""', text, flags=re.MULTILINE)
|
||||
source.write_text(text, encoding='utf-8')
|
||||
if len(str(workspace)) > 180 or _hash(target_database / 'icdb.dat') != source_hashes[database]:
|
||||
raise NativeInventoryUnsupported('无法创建稳定的短路径数据库快照')
|
||||
output = workspace / 'output'
|
||||
output.mkdir()
|
||||
commands = (
|
||||
(str(tools[0]), '-project=' + str(source), '-icdb=' + str(target_database),
|
||||
'-snap=' + snapshot, '-h', '-t', '-offline', '-file=' + str(output / 'scope.txt')),
|
||||
)
|
||||
report_progress(on_progress, '正在使用原生接口读取工程快照中的器件和位号…')
|
||||
try:
|
||||
desktop.__enter__()
|
||||
environment = dict(os.environ, SDD_HOME=str(tools[0].parents[3]))
|
||||
for command in commands:
|
||||
self._run_tool(desktop, command, workspace, environment, output,
|
||||
record, stop_event)
|
||||
finally:
|
||||
try:
|
||||
desktop.close()
|
||||
clean = True
|
||||
except Exception as error:
|
||||
record.update(state='uncertain', cleanup_error=str(error))
|
||||
try:
|
||||
(evidence / 'uncertain.flag').write_text(str(error), encoding='utf-8')
|
||||
except OSError as marker_error:
|
||||
record['uncertain_marker_error'] = str(marker_error)
|
||||
raise TaskCenterError('inventory_cleanup',
|
||||
f'原生采集进程未能确认安全释放,请保留诊断记录:{evidence}') from error
|
||||
_verify_sources(source_hashes)
|
||||
check_cancelled(stop_event)
|
||||
result = read_ascii_discovery(project, output / 'scope.txt', old_part_numbers, expected_root=block)
|
||||
record.update(state='ready', components=len(result.components), source_hashes_unchanged=True)
|
||||
report_progress(on_progress, f'原生采集完成,已核对 {len(result.components)} 个目标位号及 UID。')
|
||||
except (NativeInventoryUnsupported, OSError, UnicodeError) as error:
|
||||
if record['state'] == 'uncertain':
|
||||
raise TaskCenterError('inventory_cleanup', f'原生采集清理状态不确定:{evidence}') from error
|
||||
_verify_sources(source_hashes)
|
||||
record.update(state='fallback', reason=str(error))
|
||||
report_progress(on_progress, f'原生清单未能完整核对,改用 CAD 采集:{str(error)[:160]}')
|
||||
except TaskCenterError as error:
|
||||
if record['state'] != 'uncertain':
|
||||
record.update(state='cancelled' if error.code == 'operation_cancelled' else 'failed', reason=error.message)
|
||||
raise
|
||||
finally:
|
||||
record.update(seconds=time.monotonic() - started,
|
||||
cleanup=getattr(desktop, 'cleanup_record', None))
|
||||
# All diagnostics happen after process/desktop cleanup, never in
|
||||
# between an exit request and the wait that confirms it.
|
||||
try:
|
||||
if (workspace / 'output').is_dir():
|
||||
shutil.copytree(workspace / 'output', evidence / 'output')
|
||||
finally:
|
||||
if clean or not record['tools'] and record['state'] != 'uncertain':
|
||||
if workspace.parent == base and workspace.resolve() == workspace:
|
||||
shutil.rmtree(workspace)
|
||||
(evidence / 'native-inventory.json').write_text(
|
||||
json.dumps(record, ensure_ascii=False, indent=2), encoding='utf-8')
|
||||
return result
|
||||
|
||||
def _run_tool(self, desktop, command, workspace, environment, output, record, stop_event):
|
||||
check_cancelled(stop_event)
|
||||
name = Path(command[0]).stem
|
||||
started = time.monotonic()
|
||||
metric = {'name': name, 'exit_code': None}
|
||||
record['tools'].append(metric)
|
||||
try:
|
||||
with (output / (name + '.stdout.txt')).open('wb') as stdout, (
|
||||
output / (name + '.stderr.txt')).open('wb') as stderr:
|
||||
process = desktop.start_process(command, cwd=workspace, env=environment,
|
||||
stdout=stdout, stderr=stderr)
|
||||
deadline = started + self.timeout
|
||||
while process.poll() is None:
|
||||
check_cancelled(stop_event)
|
||||
if time.monotonic() >= deadline:
|
||||
raise NativeInventoryUnsupported(f'{name} 原生读取超时')
|
||||
time.sleep(0.05)
|
||||
metric['exit_code'] = process.poll()
|
||||
if metric['exit_code'] != 0:
|
||||
raise NativeInventoryUnsupported(f'{name} 返回退出码 {metric["exit_code"]}')
|
||||
finally:
|
||||
metric['seconds'] = time.monotonic() - started
|
||||
@@ -0,0 +1,96 @@
|
||||
"""Read complete, unfiltered offline iCDB reports as immutable CAD identities."""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
|
||||
from .quick_run_protocol import ProjectDiscovery
|
||||
from .target_plan import ComponentTarget
|
||||
|
||||
|
||||
class NativeInventoryUnsupported(ValueError):
|
||||
"""The native report cannot certify the existing inventory contract."""
|
||||
|
||||
|
||||
_UID = re.compile(r'^\$\d+I\d+$')
|
||||
|
||||
|
||||
def read_native_text(path: Path) -> str:
|
||||
if path.stat().st_size > 32 * 1024 * 1024:
|
||||
raise NativeInventoryUnsupported('原生清单超过读取上限')
|
||||
data = path.read_bytes()
|
||||
try:
|
||||
return data.decode('utf-8-sig')
|
||||
except UnicodeDecodeError:
|
||||
return data.decode('mbcs' if os.name == 'nt' else 'cp1252')
|
||||
|
||||
|
||||
def _parse_scope(text, requested):
|
||||
blocks, sheets, targets = set(), set(), set()
|
||||
block, symbol, attributes = '', None, {}
|
||||
def finish():
|
||||
if symbol is not None and attributes.get('Part Number', '').casefold() in requested:
|
||||
uid, sheet = symbol
|
||||
ref, part = attributes.get('Ref Designator', ''), attributes['Part Number']
|
||||
if not _UID.fullmatch(uid) or not ref:
|
||||
raise NativeInventoryUnsupported('全工程报告中的请求物料缺少唯一身份')
|
||||
target = block, sheet, uid, ref, part, attributes.get('Value', '')
|
||||
if target in targets:
|
||||
raise NativeInventoryUnsupported('全工程报告含重复器件身份')
|
||||
targets.add(target)
|
||||
if len(targets) > 100000:
|
||||
raise NativeInventoryUnsupported('原生器件数量超过读取上限')
|
||||
for line in text.splitlines():
|
||||
if line.startswith('Block '):
|
||||
finish()
|
||||
name = line[6:].split('\t', 1)[0].rstrip()
|
||||
if not name or name in blocks:
|
||||
raise NativeInventoryUnsupported('全工程报告含不明确的原理图身份')
|
||||
blocks.add(name)
|
||||
block, symbol, attributes = name, None, {}
|
||||
elif line.startswith(' Symbol '):
|
||||
finish()
|
||||
match = re.fullmatch(r' Symbol (.+?)\tpage (.+)', line)
|
||||
if not block or match is None:
|
||||
raise NativeInventoryUnsupported('全工程报告含不明确的图页身份')
|
||||
symbol, attributes = match.groups(), {}
|
||||
sheets.add((block, symbol[1]))
|
||||
elif symbol is not None and line.startswith('\tProp '):
|
||||
# Pin properties have two tabs and must never override a component.
|
||||
match = re.fullmatch(r'\tProp (Ref Designator|Part Number|Value)(?: (.*))?', line)
|
||||
if match:
|
||||
key, value = match.groups()
|
||||
if key in attributes:
|
||||
raise NativeInventoryUnsupported('全工程报告的器件属性不唯一')
|
||||
attributes[key] = value or ''
|
||||
finish()
|
||||
if not blocks or not sheets:
|
||||
raise NativeInventoryUnsupported('全工程报告缺少原理图或图页')
|
||||
return blocks, sheets, targets
|
||||
|
||||
|
||||
def read_ascii_discovery(project, report_path, old_part_numbers, *, expected_root=None):
|
||||
text = read_native_text(report_path)
|
||||
required = {'REPORT FORMAT': 'FREEFORM', 'MODE': 'HIER BLOCKS', 'TEXT LISTS': 'ON',
|
||||
'SYMBOLS ONLY': 'OFF', 'NETS ONLY': 'OFF', 'USER BLOCKS': 'NONE'}
|
||||
for name, value in required.items():
|
||||
values = re.findall(r'^\s*' + re.escape(name) + r':[ \t]*([^\r\n]+)', text, re.MULTILINE)
|
||||
if [item.strip() for item in values] != [value]:
|
||||
raise NativeInventoryUnsupported('原生全工程报告缺字段、被筛选或格式不受支持')
|
||||
requested = {part.casefold() for part in old_part_numbers}
|
||||
blocks, available, targets = _parse_scope(text, requested)
|
||||
if expected_root is not None and expected_root not in blocks:
|
||||
raise NativeInventoryUnsupported('原生全工程报告与工程根块身份不一致')
|
||||
components = tuple(ComponentTarget(Path(project), *row) for row in sorted(targets))
|
||||
sheets = tuple(sorted(available))
|
||||
matches = {sheet: set() for sheet in sheets}
|
||||
seen = set()
|
||||
for target in components:
|
||||
if target.key in seen:
|
||||
raise NativeInventoryUnsupported('原生全工程报告的 UID 身份重复')
|
||||
seen.add(target.key)
|
||||
matches[(target.schematic_name, target.sheet_number)].add(target.old_part_number.casefold())
|
||||
# Symbol reports certify component inventory, but cannot enumerate empty pages.
|
||||
return ProjectDiscovery(sheets, {key: frozenset(value) for key, value in matches.items()},
|
||||
components, complete_sheet_manifest=False)
|
||||
@@ -717,6 +717,13 @@ class QuickRunPreparer:
|
||||
from .project_discovery import DiscoveryRuntime, discover_project
|
||||
from .operation_control import control_options
|
||||
|
||||
if collect_components and self._process_runner is _run_process:
|
||||
from .native_inventory import NativeInventoryReader
|
||||
native = NativeInventoryReader(self._data_root).read(
|
||||
project_path, old_part_numbers, stop_event=stop_event, on_progress=on_progress)
|
||||
if native is not None:
|
||||
return native
|
||||
|
||||
process_runner = self._process_runner
|
||||
if stop_event is not None and process_runner is _run_process:
|
||||
def process_runner(command, timeout):
|
||||
|
||||
@@ -58,6 +58,7 @@ class ProjectDiscovery:
|
||||
sheets: tuple[tuple[str, str], ...]
|
||||
matched_old_parts: dict[tuple[str, str], frozenset[str]]
|
||||
components: tuple = ()
|
||||
complete_sheet_manifest: bool = True
|
||||
|
||||
|
||||
# Preserve callers that injected the original discovery boundary.
|
||||
|
||||
Reference in new issue
Block a user