VEHwang's picture
Upload CoCogni4D-Bench (questions, media, scripts, render records, code) (part 6)
5afd2f7 verified
Raw History Blame Contribute Delete
2.45 kB
"""Pinned checkouts and bounded subprocess execution for console generation."""
import datetime
import json
import os
import signal
import subprocess
import time
from .errors import require
def encoded(data):
return json.dumps(data, ensure_ascii=False, sort_keys=True, separators=(',', ':'), allow_nan=False).encode()
def now():
return datetime.datetime.now(datetime.timezone.utc).isoformat()
def pin_checkout(checkout, expected_commit):
result = subprocess.run(['git', 'rev-parse', 'HEAD'], cwd=checkout, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, timeout=15)
require(result.returncode == 0 and result.stdout.decode().strip() == expected_commit,
'GENERATOR_COMMIT_MISMATCH', '生成器提交号与固定版本不符')
result = subprocess.run(['git', 'diff', '--quiet', 'HEAD', '--'], cwd=checkout, timeout=15)
require(result.returncode == 0, 'GENERATOR_DIRTY', '生成器有未提交的跟踪改动')
result = subprocess.run(['git', 'ls-files', '--others', '--exclude-standard'], cwd=checkout, stdout=subprocess.PIPE, timeout=15)
require(result.returncode == 0 and not any(p.endswith('.py') for p in result.stdout.decode().splitlines()),
'GENERATOR_DIRTY', '生成器含未登记的Python源码')
return {'kind': 'git_checkout', 'commit': expected_commit}
def stop(child):
if child.poll() is None:
try:
os.killpg(child.pid, signal.SIGTERM)
except ProcessLookupError:
return
try:
child.wait(timeout=5)
except subprocess.TimeoutExpired:
os.killpg(child.pid, signal.SIGKILL)
child.wait(timeout=5)
def execute(owner, command, cwd, env, log, limit):
begin = time.monotonic()
with log.open('wb') as stream:
with owner.lock:
require(not owner.closed, 'GENERATION_CLOSED', '服务已关闭')
child = subprocess.Popen(command, cwd=cwd, env=env, stdout=stream,
stderr=subprocess.STDOUT, start_new_session=True)
owner.child = child
try:
code = child.wait(timeout=limit)
except subprocess.TimeoutExpired:
stop(child)
code = 124
finally:
with owner.lock:
owner.child = None
return dict(argv=command, exit_code=code, wall_limit_s=limit,
seconds=time.monotonic() - begin, log=str(log))