"""Open the official backup UI; version selection and writes stay native.""" from dataclasses import dataclass import json from pathlib import Path import stat import subprocess import sys import time from uuid import uuid4 def native_backup_executable(mentor_bin=''): from .mentor_paths import discover_sdd_home home = discover_sdd_home(mentor_bin) executable = home/'iCDB/win32/bin/iCDBProjectBackup.exe' if home else None if executable is None or not executable.is_file(): raise ValueError('未找到 iCDB Project Backup,请检查 Mentor 安装位置。') return executable def native_backup_project(library, block): from .verify_runner import INVALID_NAME_CHARS library = Path(library).absolute() if not block or block in ('.', '..') or any(c in block for c in INVALID_NAME_CHARS): raise ValueError('CBB 名称非法。') if not library.is_file(): raise ValueError('中心库文件不存在。') work = library.parent/'ReusableBlocksLP'/block/'Work' expected = library.parent.resolve()/'ReusableBlocksLP'/block/'Work' if work.resolve() != expected: raise ValueError('工程路径通过链接指向其他位置。') projects = list(work.glob('*.prj')) if len(projects) != 1 or not projects[0].is_file(): raise ValueError('无法唯一确定所选 CBB 的工程 PRJ。') project = projects[0] if (project.lstat().st_file_attributes & stat.FILE_ATTRIBUTE_REPARSE_POINT or not project.resolve().is_relative_to(expected)): raise ValueError('工程文件通过链接指向其他位置。') return project @dataclass class NativeBackupSession: process: object job: Path library: Path block: str path_lease: object = None def launch_native_backup(request): project = native_backup_project(request.lmc_file, request.block_name) native_backup_executable(request.mentor_bin) root = Path(request.evidence_dir).resolve()/('native-backup-'+uuid4().hex[:12]) library_root = Path(request.lmc_file).resolve().parent if root.is_relative_to(library_root) or library_root.is_relative_to(root): raise ValueError('运行记录目录需位于中心库之外。') root.mkdir(parents=True) job = root/'request.json' job.write_text(json.dumps({'library': str(request.lmc_file), 'block': request.block_name, 'project': str(project), 'mentor_bin': request.mentor_bin}, ensure_ascii=False), 'utf-8') command = ([sys.executable] if getattr(sys, 'frozen', False) else [sys.executable, '-m', 'cbb_refresh_verify'])+['--native-backup-worker', str(job)] process = subprocess.Popen(command, creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0)) return NativeBackupSession(process, job, Path(request.lmc_file), request.block_name) class _NativeBackupProcess: """Track this visible tool and its descendants without killing on close.""" def __init__(self, command, cwd): import win32con, win32job, win32process self.job = win32job.CreateJobObject(None, '') startup = win32process.STARTUPINFO() try: self.handle, thread, self.pid, _ = win32process.CreateProcess( command[0], subprocess.list2cmdline(command), None, None, False, win32con.CREATE_SUSPENDED, None, str(cwd), startup) except Exception: self.job.Close() raise try: win32job.AssignProcessToJobObject(self.job, self.handle) win32process.ResumeThread(thread) except Exception: # No native code has run while suspended; there can be no DB write. win32process.TerminateProcess(self.handle, 1) self.handle.Close(); self.job.Close() raise finally: thread.Close() def poll(self): import win32process code = win32process.GetExitCodeProcess(self.handle) return None if code == 259 else code def session_pids(self): import win32job return win32job.QueryInformationJobObject(self.job, win32job.JobObjectBasicProcessIdList) def close(self): self.handle.Close(); self.job.Close() def native_backup_worker_main(job, *, process_factory=None): from .library_lock import LibraryLock from .management import _write_json job = Path(job) result = {'status': 'FAILED', 'safe_to_continue': True, 'restore_confirmed': False} native = None def write_evidence(name, value): try: _write_json(job.with_name(name), value) except Exception as error: # Evidence storage must never end supervision of a live transaction. result['evidence_error'] = str(error) try: record = json.loads(job.read_text('utf-8')) library, block = Path(record['library']), record['block'] result.update(library=str(library), block=block) project = native_backup_project(library, block) if project != Path(record['project']): raise ValueError('工程身份已变化,未打开原生工具。') executable = native_backup_executable(record.get('mentor_bin', '')) released = True with LibraryLock(library, checkpoint=False, safe_to_release=lambda: released): native = (process_factory or _NativeBackupProcess)([str(executable), '-p', str(project)], project.parent) released = False result.update(status='OPEN', native_pid=native.pid, project=str(project), safe_to_continue=False) write_evidence('state.json', result) waiting = False while True: try: pids, exit_code = native.session_pids(), native.poll() except Exception as error: write_evidence('state.json', {**result, 'status': 'RELEASE_UNCONFIRMED', 'detail': str(error)}) time.sleep(.5) continue # Keep the lease while the live session cannot be observed. if not pids and exit_code is not None: break if exit_code is not None and not waiting: waiting = True write_evidence('state.json', {**result, 'status': 'WAITING_RELEASE'}) time.sleep(.25) released = True result.update(status='CLOSED', native_exit_code=exit_code, safe_to_continue=True) return 0 if result['native_exit_code'] == 0 else 1 except Exception as error: result.update(status='FAILED', detail=str(error), safe_to_continue=native is None) return 1 finally: write_evidence('result.json', result) if native is not None: native.close() # No kill-on-close: never interrupt a native transaction.