Connect production replacement and recovery to owned private CAD sessions
This commit is contained in:
1 parent
f26e868bfc
commit
fee1aff557
13 files changed
+553
-20
No files matched your search
@@ -35,6 +35,9 @@ def _parse_arguments(argv: Sequence[str] | None) -> argparse.Namespace:
|
||||
parser.add_argument("--native-helper", action="store_true", help=argparse.SUPPRESS)
|
||||
parser.add_argument("--snapshot", type=Path, help=argparse.SUPPRESS)
|
||||
parser.add_argument("--sceneos-cli", action="store_true", help=argparse.SUPPRESS)
|
||||
parser.add_argument('--private-cad-action', choices=('probe', 'quit'), help=argparse.SUPPRESS)
|
||||
parser.add_argument('--private-cad-evidence', type=Path, help=argparse.SUPPRESS)
|
||||
parser.add_argument('--private-cad-pid', type=int, help=argparse.SUPPRESS)
|
||||
return parser.parse_args(list(argv) if argv is not None else None)
|
||||
|
||||
|
||||
@@ -91,6 +94,11 @@ def _flush(context: LoggingContext) -> None:
|
||||
def main(argv: Sequence[str] | None = None) -> int:
|
||||
"""Run the Qt shell, returning a conventional process status code."""
|
||||
arguments = _parse_arguments(argv)
|
||||
if arguments.private_cad_action:
|
||||
if arguments.private_cad_evidence is None or arguments.private_cad_pid is None:
|
||||
return 2
|
||||
from .isolated_cad import native_action
|
||||
return native_action(arguments.private_cad_action, arguments.private_cad_evidence, arguments.private_cad_pid)
|
||||
if arguments.native_helper:
|
||||
if arguments.snapshot is None:
|
||||
return 2
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
"""Identity certificate shared by the private desktop worker and native helper."""
|
||||
from dataclasses import dataclass
|
||||
import ctypes
|
||||
from ctypes import wintypes
|
||||
import os
|
||||
import re
|
||||
|
||||
|
||||
def current_desktop_name():
|
||||
user = ctypes.WinDLL('user32', use_last_error=True)
|
||||
kernel = ctypes.WinDLL('kernel32', use_last_error=True)
|
||||
user.GetThreadDesktop.argtypes = [wintypes.DWORD]
|
||||
user.GetThreadDesktop.restype = wintypes.HANDLE
|
||||
user.GetUserObjectInformationW.argtypes = [wintypes.HANDLE, ctypes.c_int, ctypes.c_void_p,
|
||||
wintypes.DWORD, ctypes.POINTER(wintypes.DWORD)]
|
||||
desktop = user.GetThreadDesktop(kernel.GetCurrentThreadId())
|
||||
value, required = ctypes.create_unicode_buffer(256), wintypes.DWORD()
|
||||
if not user.GetUserObjectInformationW(desktop, 2, value, ctypes.sizeof(value), ctypes.byref(required)):
|
||||
raise ctypes.WinError(ctypes.get_last_error())
|
||||
return value.value
|
||||
|
||||
|
||||
def window_pid(handle):
|
||||
import win32process
|
||||
return win32process.GetWindowThreadProcessId(handle)[1]
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class CadBinding:
|
||||
desktop: str
|
||||
pid: int
|
||||
guid: str
|
||||
token: str
|
||||
|
||||
@classmethod
|
||||
def from_environment(cls, environment=None):
|
||||
environment = os.environ if environment is None else environment
|
||||
fields = ('DXPART_DESKTOP', 'DXPART_CAD_PID', 'DXPART_CAD_GUID', 'DXPART_SESSION_TOKEN')
|
||||
values = [environment.get(field, '') for field in fields]
|
||||
if not any(values):
|
||||
return None
|
||||
if not all(values):
|
||||
raise ValueError('incomplete private CAD identity')
|
||||
desktop, pid, guid, token = values
|
||||
if not re.fullmatch(r'dx-[A-Za-z0-9-]{1,80}', desktop) or int(pid) <= 0:
|
||||
raise ValueError('invalid private CAD desktop or PID')
|
||||
if not re.fullmatch(r'[0-9a-f]{32}', token):
|
||||
raise ValueError('invalid private CAD session token')
|
||||
return cls(desktop, int(pid), guid, token)
|
||||
|
||||
def environment(self):
|
||||
return dict(os.environ, DXPART_DESKTOP=self.desktop, DXPART_CAD_PID=str(self.pid),
|
||||
DXPART_CAD_GUID=self.guid, DXPART_SESSION_TOKEN=self.token)
|
||||
|
||||
|
||||
def verify_application(app, binding=None, *, require_view=True):
|
||||
binding = CadBinding.from_environment() if binding is None else binding
|
||||
if binding is None:
|
||||
return None
|
||||
if current_desktop_name() != binding.desktop:
|
||||
raise ValueError('CAD helper is not running on its owned desktop')
|
||||
if str(app.Guid()).casefold() != binding.guid.casefold():
|
||||
raise ValueError('CAD COM GUID does not match its owned session')
|
||||
if require_view:
|
||||
handle = int(app.ActiveViewHandle)
|
||||
if not handle or window_pid(handle) != binding.pid:
|
||||
raise ValueError('CAD view PID does not match its owned session')
|
||||
return binding
|
||||
@@ -0,0 +1,210 @@
|
||||
"""Start the real CAD and its automation on one owned Windows desktop."""
|
||||
from dataclasses import asdict
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from uuid import uuid4
|
||||
|
||||
from .cad_identity import CadBinding, current_desktop_name, verify_application
|
||||
from .isolated_desktop import PrivateDesktop
|
||||
from .worker_monitor import WorkerMonitorError
|
||||
|
||||
|
||||
def _helper_command(action, evidence, pid):
|
||||
if getattr(sys, 'frozen', False):
|
||||
return (sys.executable, '--private-cad-action', action, '--private-cad-evidence', str(evidence),
|
||||
'--private-cad-pid', str(pid))
|
||||
return (sys.executable, '-m', __name__, action, str(evidence), str(pid))
|
||||
|
||||
|
||||
def _child_environment(environment):
|
||||
environment = dict(environment)
|
||||
if not getattr(sys, 'frozen', False):
|
||||
environment['PYTHONPATH'] = str(Path(__file__).resolve().parents[2]) + os.pathsep + environment.get('PYTHONPATH', '')
|
||||
return environment
|
||||
|
||||
|
||||
def _designer_executable():
|
||||
import winreg
|
||||
with winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, r'Viewdraw.Application\CLSID') as key:
|
||||
clsid = winreg.QueryValue(key, None)
|
||||
with winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, rf'CLSID\{clsid}\LocalServer32',
|
||||
0, winreg.KEY_READ | winreg.KEY_WOW64_32KEY) as key:
|
||||
command = winreg.QueryValue(key, None)
|
||||
# Mentor registers an absolute LocalServer32 path, sometimes quoted.
|
||||
command = command.strip()
|
||||
executable = command.split('"', 2)[1] if command.startswith('"') else command[:command.lower().index('.exe') + 4]
|
||||
path = Path(executable)
|
||||
if path.name.casefold() != 'viewdraw.exe' or not path.is_file():
|
||||
raise WorkerMonitorError('registered DxDesigner executable is unavailable')
|
||||
return path
|
||||
|
||||
|
||||
class IsolatedCadSession:
|
||||
"""The supervisor never attaches to COM on the user's input desktop."""
|
||||
def __init__(self, root, *, abort_event=None):
|
||||
self.root = Path(root)
|
||||
self.token = uuid4().hex
|
||||
self.desktop = PrivateDesktop('dx-' + self.token, enabled=True)
|
||||
self.cad = None
|
||||
self.binding = None
|
||||
self.started = time.monotonic()
|
||||
self.abort_event = abort_event
|
||||
self.record = {'desktop': self.desktop.name, 'token': self.token, 'state': 'starting'}
|
||||
|
||||
def _record(self, **values):
|
||||
self.record.update(values)
|
||||
self.root.mkdir(parents=True, exist_ok=True)
|
||||
target = self.root / 'private-desktop.json'
|
||||
temporary = target.with_suffix('.tmp')
|
||||
temporary.write_text(json.dumps(self.record, ensure_ascii=False, indent=2), encoding='utf-8')
|
||||
temporary.replace(target)
|
||||
|
||||
def __enter__(self):
|
||||
try:
|
||||
self._check_abort()
|
||||
self.desktop.__enter__()
|
||||
self.cad = self.desktop.start_process((str(_designer_executable()),))
|
||||
self._record(cad_pid=self.cad.pid)
|
||||
bootstrap = self.root / ('cad-binding-' + self.token + '.json')
|
||||
environment = dict(os.environ, DXPART_DESKTOP=self.desktop.name,
|
||||
DXPART_CAD_PID=str(self.cad.pid), DXPART_SESSION_TOKEN=self.token)
|
||||
environment.pop('DXPART_CAD_GUID', None)
|
||||
probe = self.desktop.start_process(_helper_command('probe', bootstrap, self.cad.pid), env=_child_environment(environment),
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
try:
|
||||
deadline = time.monotonic() + 75
|
||||
while probe.poll() is None:
|
||||
self._check_abort()
|
||||
if time.monotonic() >= deadline:
|
||||
raise WorkerMonitorError('private CAD bootstrap timed out')
|
||||
time.sleep(0.05)
|
||||
code = probe.poll()
|
||||
if code:
|
||||
raise WorkerMonitorError('private CAD startup identity failed: ' + probe.stderr.read().decode('utf-8', errors='replace'))
|
||||
finally:
|
||||
probe.close()
|
||||
result = json.loads(bootstrap.read_text(encoding='utf-8'))
|
||||
self.binding = CadBinding(**result)
|
||||
if (self.binding.pid, self.binding.desktop, self.binding.token) != (self.cad.pid, self.desktop.name, self.token):
|
||||
raise WorkerMonitorError('private CAD bootstrap returned a foreign identity')
|
||||
self._record(state='ready', guid=self.binding.guid, startup_seconds=time.monotonic() - self.started)
|
||||
return self
|
||||
except Exception as error:
|
||||
try:
|
||||
self.desktop.close()
|
||||
except Exception as failure:
|
||||
self._uncertain('startup cleanup failed: ' + str(failure))
|
||||
raise WorkerMonitorError('private CAD startup cleanup requires reconciliation: ' + str(failure)) from error
|
||||
self._record(state='released', clean=False, startup_error=str(error))
|
||||
raise
|
||||
|
||||
def _check_abort(self):
|
||||
if self.abort_event is not None and self.abort_event.is_set():
|
||||
raise WorkerMonitorError('private CAD startup was cancelled before execution')
|
||||
|
||||
def start_worker(self, command, **options):
|
||||
if self.binding is None or self.cad.poll() is not None:
|
||||
raise WorkerMonitorError('owned private CAD is unavailable')
|
||||
return self.desktop.start_process(command, env=_child_environment(self.binding.environment()), **options)
|
||||
|
||||
def __exit__(self, error_type, error, traceback):
|
||||
closing_started = time.monotonic()
|
||||
cleanup_error = None
|
||||
try:
|
||||
self._record(state='closing')
|
||||
if error is not None:
|
||||
self._uncertain(str(error))
|
||||
if self.cad is not None and self.cad.poll() is not None:
|
||||
raise WorkerMonitorError('owned CAD exited before the authorized quit request')
|
||||
if self.cad is not None and self.binding is not None:
|
||||
closing = self.desktop.start_process(_helper_command('quit', self.root / 'private-desktop.json', self.cad.pid),
|
||||
env=_child_environment(self.binding.environment()), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
try:
|
||||
if closing.wait(timeout=20):
|
||||
raise WorkerMonitorError('owned CAD refused orderly exit: ' + closing.stderr.read().decode('utf-8', errors='replace'))
|
||||
if self.cad.wait(timeout=15) != 0:
|
||||
raise WorkerMonitorError('owned CAD returned a nonzero exit code after quit')
|
||||
finally:
|
||||
closing.close()
|
||||
except Exception as failure:
|
||||
cleanup_error = failure
|
||||
self._uncertain(str(failure))
|
||||
finally:
|
||||
try:
|
||||
self.desktop.close()
|
||||
self._record(state='released', clean=error is None and cleanup_error is None,
|
||||
shutdown_seconds=time.monotonic() - closing_started)
|
||||
except Exception as failure:
|
||||
self._uncertain(str(failure))
|
||||
cleanup_error = failure
|
||||
if cleanup_error is not None:
|
||||
raise WorkerMonitorError('private CAD cleanup requires reconciliation: ' + str(cleanup_error)) from cleanup_error
|
||||
|
||||
def _uncertain(self, message):
|
||||
from .quick_run import _write_uncertain_flag
|
||||
_write_uncertain_flag(self.root / 'uncertain.flag', 'private_desktop: ' + message)
|
||||
self._record(state='uncertain', error=message)
|
||||
|
||||
|
||||
def run_isolated_process(command, timeout, *, abort_event=None):
|
||||
from .worker_monitor import run_monitored_process
|
||||
with IsolatedCadSession(Path(command[3]), abort_event=abort_event) as session:
|
||||
return run_monitored_process(command, timeout, abort_event=abort_event, process_factory=session.start_worker)
|
||||
|
||||
|
||||
def native_action(action, evidence, expected_pid):
|
||||
"""Runs in a child created with lpDesktop, never in a Python thread switch."""
|
||||
import pythoncom
|
||||
import win32com.client
|
||||
import win32gui
|
||||
import win32process
|
||||
pythoncom.CoInitialize()
|
||||
try:
|
||||
desktop = os.environ.get('DXPART_DESKTOP', '')
|
||||
token = os.environ.get('DXPART_SESSION_TOKEN', '')
|
||||
if not desktop.startswith('dx-') or current_desktop_name() != desktop:
|
||||
raise ValueError('CAD bootstrap is not on the requested private desktop')
|
||||
expected_pid = int(expected_pid)
|
||||
if expected_pid <= 0 or str(expected_pid) != os.environ.get('DXPART_CAD_PID'):
|
||||
raise ValueError('invalid CAD bootstrap PID')
|
||||
deadline = time.monotonic() + 60
|
||||
while True:
|
||||
try:
|
||||
app = win32com.client.GetActiveObject('Viewdraw.Application')
|
||||
break
|
||||
except pythoncom.com_error:
|
||||
if action != 'probe' or time.monotonic() >= deadline:
|
||||
raise
|
||||
time.sleep(0.2)
|
||||
if action == 'probe':
|
||||
cad_windows = []
|
||||
win32gui.EnumWindows(lambda handle, _: cad_windows.append(handle)
|
||||
if win32process.GetWindowThreadProcessId(handle)[1] == expected_pid else None, None)
|
||||
if not cad_windows:
|
||||
raise ValueError('owned CAD has no windows on its private desktop')
|
||||
# ROT is scoped to this desktop. Certify the freshly launched instance
|
||||
# here; every subsequent VBS/helper attachment checks its GUID.
|
||||
binding = CadBinding(desktop, expected_pid, str(app.Guid()), token)
|
||||
verify_application(app, binding, require_view=False)
|
||||
Path(evidence).write_text(json.dumps(asdict(binding)), encoding='utf-8')
|
||||
elif action == 'quit':
|
||||
binding = CadBinding.from_environment()
|
||||
# ActiveViewHandle can retain a destroyed/reused HWND after closing
|
||||
# the last project. The private ROT/GUID binds this empty instance.
|
||||
verify_application(app, binding, require_view=False)
|
||||
if app.GetProjectData().GetProjectFilePath():
|
||||
raise ValueError('owned CAD still has a project open; no implicit save or discard')
|
||||
app.Quit()
|
||||
else:
|
||||
raise ValueError('unknown private CAD action')
|
||||
finally:
|
||||
pythoncom.CoUninitialize()
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
raise SystemExit(native_action(sys.argv[1], Path(sys.argv[2]), int(sys.argv[3])))
|
||||
@@ -1,4 +1,4 @@
|
||||
"""Research-only worker protocol for a single project.
|
||||
"""Legacy research-only request protocol; production uses isolated_cad.
|
||||
|
||||
The worker writes versioned request/evidence files and delegates process
|
||||
launching to an injected callback. It never attaches to an existing CAD
|
||||
@@ -88,7 +88,7 @@ class IsolatedDesktopWorker:
|
||||
*,
|
||||
evidence_root: Path | None = None,
|
||||
) -> IsolatedWorkerEvidence:
|
||||
"""Validate an already-created read-only probe result.
|
||||
"""Validate an injected callback result; this does not move CAD desktops.
|
||||
|
||||
The callback is the only native integration point and must return the
|
||||
PID and project identity it observed. Tests inject it; production can
|
||||
|
||||
@@ -205,6 +205,8 @@ def attach():
|
||||
api = win32com.client.gencache.EnsureModule(
|
||||
"{4ADEF4E1-690A-11CE-9261-0020C5E26659}", 0, 1, 0)
|
||||
app = api.IVdApp(win32com.client.GetActiveObject("Viewdraw.Application")._oleobj_)
|
||||
from .cad_identity import verify_application
|
||||
verify_application(app)
|
||||
return app, api
|
||||
|
||||
|
||||
@@ -226,6 +228,8 @@ def components_on_sheet(app, api):
|
||||
|
||||
|
||||
def check_active_context(app, metadata):
|
||||
from .cad_identity import verify_application
|
||||
verify_application(app)
|
||||
if os.path.normcase(os.path.abspath(app.GetProjectData().GetProjectFilePath())) != os.path.normcase(os.path.abspath(metadata[1])):
|
||||
raise ValueError("Active project changed")
|
||||
if f"{app.ActiveView.GetName(0)}:{app.ActiveView.Block.SheetNum}" != metadata[4]:
|
||||
|
||||
@@ -21,7 +21,7 @@ class ProjectSessionWorker:
|
||||
The VBS worker owns CAD. This driver never attaches to COM or terminates CAD.
|
||||
A separate monitor thread retains the existing idle watchdog and worker job.
|
||||
"""
|
||||
def __init__(self, project: Path, root: Path):
|
||||
def __init__(self, project: Path, root: Path, *, private_desktop=False):
|
||||
self.project, self.root = Path(project), Path(root)
|
||||
self.token = uuid4().hex
|
||||
self._done, self._abort = Event(), Event()
|
||||
@@ -33,10 +33,15 @@ class ProjectSessionWorker:
|
||||
self._failure_delivered = False
|
||||
self._timeout = 150
|
||||
self.starts = 0
|
||||
self.private_desktop = private_desktop
|
||||
|
||||
def _monitor(self, command, timeout):
|
||||
try:
|
||||
self._result = run_monitored_process(command, timeout, abort_event=self._abort)
|
||||
if self.private_desktop:
|
||||
from .isolated_cad import run_isolated_process
|
||||
self._result = run_isolated_process(command, timeout, abort_event=self._abort)
|
||||
else:
|
||||
self._result = run_monitored_process(command, timeout, abort_event=self._abort)
|
||||
except Exception as error:
|
||||
self._error = error
|
||||
finally:
|
||||
@@ -87,16 +92,20 @@ class ProjectSessionWorker:
|
||||
def close(self):
|
||||
if self._closed:
|
||||
return
|
||||
self._closed = True
|
||||
try:
|
||||
if self._thread is None:
|
||||
self._closed = True
|
||||
return
|
||||
if not self._done.is_set():
|
||||
_write_control(self.root / 'project-session-next.tsv', f'{self.token}\tclose')
|
||||
if not self._done.wait(min(30, max(10, self._timeout))):
|
||||
close_grace = 60 if self.private_desktop else min(30, max(10, self._timeout))
|
||||
if not self._done.wait(close_grace):
|
||||
self._abort.set()
|
||||
self._done.wait(10)
|
||||
if not self._done.wait(30):
|
||||
raise WorkerMonitorError('owned project cleanup is still pending; retry closing before another task')
|
||||
self._closed = True
|
||||
raise WorkerMonitorError('owned project did not acknowledge session closing')
|
||||
self._closed = True
|
||||
if self._error is not None:
|
||||
raise self._error
|
||||
if self._result.returncode != 0 and not self._failure_delivered:
|
||||
@@ -109,9 +118,10 @@ class ProjectSessionWorker:
|
||||
|
||||
class ProjectSessionScope:
|
||||
"""One serial task can visit projects, but can hold only one worker at a time."""
|
||||
def __init__(self, fallback, *, enabled):
|
||||
def __init__(self, fallback, *, enabled, private_desktop=False):
|
||||
self.fallback, self.enabled = fallback, enabled
|
||||
self.worker = None
|
||||
self.private_desktop = private_desktop
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
@@ -121,7 +131,7 @@ class ProjectSessionScope:
|
||||
return self.fallback(command, timeout)
|
||||
self.prepare(project)
|
||||
if self.worker is None:
|
||||
self.worker = ProjectSessionWorker(Path(project), Path(command[3]))
|
||||
self.worker = ProjectSessionWorker(Path(project), Path(command[3]), private_desktop=self.private_desktop)
|
||||
return self.worker.run_step(command, timeout)
|
||||
|
||||
def prepare(self, project):
|
||||
|
||||
@@ -300,7 +300,7 @@ class QuickRunPreparer:
|
||||
from .worker_monitor import WorkerMonitorError
|
||||
try:
|
||||
with ProjectSessionScope(self._process_runner,
|
||||
enabled=enabled and self._process_runner is _run_process) as scope:
|
||||
enabled=enabled and self._process_runner is _run_process, private_desktop=True) as scope:
|
||||
yield scope
|
||||
except (WorkerMonitorError, subprocess.TimeoutExpired) as error:
|
||||
_write_uncertain_flag(self._data_root / 'quick-run/uncertain.flag', 'project_session_cleanup')
|
||||
@@ -323,6 +323,10 @@ class QuickRunPreparer:
|
||||
uncertain_path = self._data_root / "quick-run" / "uncertain.flag"
|
||||
if uncertain_path.exists():
|
||||
raise TaskCenterError("quick_run_uncertain", "a previous quick-run worker timed out or returned an uncorrelated status; reconcile the project before retrying")
|
||||
if self._process_runner is _run_process and not batch_mode:
|
||||
from .single_step import prepare_private_single_step
|
||||
prepare_private_single_step(self, task_id, projects, rules, copy_part_number_to_value)
|
||||
batch_mode = True
|
||||
current_root = self._data_root / "quick-run"
|
||||
if batch_session is None and self.evidence_path(task_id) == current_root and (current_root / "status.tsv").is_file():
|
||||
recorded = _read_status_details(current_root / "status.tsv")
|
||||
@@ -1692,9 +1696,9 @@ def _cached_native_helper_launch_arguments(frozen: bool, executable: str) -> tup
|
||||
|
||||
|
||||
def _run_process(command: tuple[str, ...], timeout: int) -> subprocess.CompletedProcess[str]:
|
||||
from .worker_monitor import run_monitored_process
|
||||
from .isolated_cad import run_isolated_process
|
||||
|
||||
return run_monitored_process(command, timeout)
|
||||
return run_isolated_process(command, timeout)
|
||||
|
||||
|
||||
def _log_text(value: str) -> str:
|
||||
|
||||
@@ -237,7 +237,10 @@ def recover(preparer, task_id, projects, rules, *, copy_part_number_to_value=Fal
|
||||
raise
|
||||
progress = preparer.progress(task_id, projects, rules, copy_part_number_to_value=copy_part_number_to_value)
|
||||
message = ('磁盘工程与替换前快照一致,只读核验工程已关闭,已准备新的执行编号;尚未再次替换,请确认后执行。'
|
||||
if state == 'retry_ready' else '已核验并恢复本项任务记录;没有重复执行原生替换。若补做了属性恢复,请保存当前工程。')
|
||||
if state == 'retry_ready' else
|
||||
'已核验并恢复本项任务记录,属性已保存并重开回读,工程已关闭;没有重复执行原生替换。'
|
||||
if after[0][2] == 'recovery_saved_verified' else
|
||||
'已核验并恢复本项任务记录;没有重复执行原生替换。若补做了属性恢复,请保存当前工程。')
|
||||
return QuickRunStepResult(root / 'QuickPartReplace.vbs', root / 'command.tsv', root / 'status.tsv',
|
||||
audit / 'worker-output.txt', state, message, progress.next_project_path,
|
||||
progress.next_old_part_number, progress.next_new_part_number,
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
"""Give the legacy single-step entry the same durable private execution boundary."""
|
||||
from uuid import uuid4
|
||||
|
||||
from .errors import TaskCenterError
|
||||
from .schematic_backup import create_schematic_backup
|
||||
|
||||
|
||||
def prepare_private_single_step(preparer, task_id, projects, rules, copy_part_number_to_value):
|
||||
progress = preparer.progress(task_id, projects, rules,
|
||||
copy_part_number_to_value=copy_part_number_to_value)
|
||||
if progress.queue_complete or progress.next_project_path is None:
|
||||
raise TaskCenterError('quick_run_complete', 'all replacement rules in this queue are complete')
|
||||
# Back up before discovery or any CAD activation. A standalone invocation
|
||||
# has no batch backup coordinator to provide this boundary.
|
||||
create_schematic_backup(preparer.data_root, progress.next_project_path,
|
||||
preparer.data_root / 'single-step-backups' / uuid4().hex)
|
||||
preparer.ensure_batch_handoff(task_id, projects, rules,
|
||||
copy_part_number_to_value=copy_part_number_to_value)
|
||||
@@ -157,7 +157,8 @@ class _OwnedWorkers:
|
||||
self.job.Close()
|
||||
|
||||
|
||||
def run_monitored_process(command: tuple[str, ...], idle_timeout: float, *, abort_event=None) -> subprocess.CompletedProcess[str]:
|
||||
def run_monitored_process(command: tuple[str, ...], idle_timeout: float, *, abort_event=None,
|
||||
process_factory=None) -> subprocess.CompletedProcess[str]:
|
||||
root = Path(command[3])
|
||||
job_id = command[-1]
|
||||
token = uuid4().hex
|
||||
@@ -195,9 +196,14 @@ def run_monitored_process(command: tuple[str, ...], idle_timeout: float, *, abor
|
||||
output[channel].extend(line[:1024 * 1024 - len(output[channel])])
|
||||
|
||||
try:
|
||||
process = subprocess.Popen((*command, token), stdout=subprocess.PIPE, stderr=subprocess.PIPE,
|
||||
creationflags=subprocess.CREATE_NO_WINDOW)
|
||||
owned.assign(process)
|
||||
if process_factory is None:
|
||||
process = subprocess.Popen((*command, token), stdout=subprocess.PIPE, stderr=subprocess.PIPE,
|
||||
creationflags=subprocess.CREATE_NO_WINDOW)
|
||||
owned.assign(process)
|
||||
else:
|
||||
# PrivateDesktop already assigns its suspended process to an owned
|
||||
# Job before resuming it. Do not reassign it to another Job here.
|
||||
process = process_factory((*command, token), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
for channel, stream in enumerate((process.stdout, process.stderr)):
|
||||
thread = threading.Thread(target=read_stream, args=(stream, channel), daemon=True)
|
||||
thread.start()
|
||||
@@ -249,3 +255,5 @@ def run_monitored_process(command: tuple[str, ...], idle_timeout: float, *, abor
|
||||
for thread in threads:
|
||||
thread.join(0.2)
|
||||
owned.close()
|
||||
if process_factory is not None and process is not None:
|
||||
process.close()
|
||||
Reference in new issue
Block a user