Files
vibemake-pcb-studio/backend/api/app/provider.py
T
2026-11-10 19:04:27 +08:00

66 lines
3.4 KiB
Python

import json,os,signal,subprocess,sys,threading
from pathlib import Path
class UnknownOutcome(RuntimeError):pass
class Provider:
def __init__(self,settings):
self.settings=settings;self.active=set();self.lock=threading.Lock()
def shutdown(self):
with self.lock:processes=list(self.active)
for process in processes:
try:os.killpg(process.pid,signal.SIGTERM)
except ProcessLookupError:pass
def call(self,command,event_callback=None,timeout=None):
s=self.settings
if s.mode=='simulation':
if not s.simulator or not s.simulator.is_file():raise RuntimeError('模拟提供器未配置;真实服务不依赖测试网站目录')
argv=[sys.executable,str(s.simulator),'--root',str(s.core_root)]
else:
wrapper=Path(__file__).resolve().parents[2]/'tools/child_exec.py'
argv=[sys.executable,str(wrapper),str(os.getpid()),sys.executable,'-m','app.core_runner','--root',str(s.core_root),'--pack',str(s.pack)]
env=dict(os.environ);env['PYTHONPATH']=str(Path(__file__).resolve().parents[1])
proc=subprocess.Popen(argv,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=None,text=True,
cwd=Path(__file__).resolve().parents[1],env=env,start_new_session=True)
with self.lock:self.active.add(proc)
expired=threading.Event()
killer=None
def terminate():
nonlocal killer
expired.set()
try:os.killpg(proc.pid,signal.SIGTERM)
except ProcessLookupError:pass
def kill():
try:os.killpg(proc.pid,signal.SIGKILL)
except ProcessLookupError:pass
killer=threading.Timer(5,kill);killer.daemon=True;killer.start()
# Design/recovery may run until success or explicit cancellation. Individual
# model and EDA calls retain timeouts so hung calls enter recovery.
unlimited=s.mode!='simulation' and command.get('action') in {'create','select','message','advance','recover'} and timeout is None
timer=None if unlimited else threading.Timer(timeout or s.command_timeout,terminate)
if timer:timer.start()
result=None
try:
proc.stdin.write(json.dumps(command,ensure_ascii=False)+'\n');proc.stdin.close()
while True:
line=proc.stdout.readline(2*1024*1024+1)
if not line:break
if len(line)>2*1024*1024:terminate();raise UnknownOutcome('服务输出超过限制,需核对执行结果')
packet=json.loads(line)
if 'event' in packet and event_callback:event_callback(packet['event'])
if 'result' in packet:result=packet['result']
proc.wait(timeout=5)
if expired.is_set() or result is None:raise UnknownOutcome('执行结果未确认,请恢复检查,不要重复提交设计命令')
return result
finally:
if timer:timer.cancel()
if killer:killer.cancel()
if proc.poll() is None:
terminate()
try:proc.wait(timeout=5)
except subprocess.TimeoutExpired:
try:os.killpg(proc.pid,signal.SIGKILL)
except ProcessLookupError:pass
proc.wait()
proc.stdout.close()
with self.lock:self.active.discard(proc)