Spaces:
Sleeping
Sleeping
File size: 9,051 Bytes
6cda6d8 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 | import { mkdir, readFile, writeFile } from 'node:fs/promises'
import fs from 'node:fs'
import { join } from 'node:path'
import { workspaceRenderOutputDirectory } from '../workspace-output-directory'
import {
StudioRunCancelledError,
readAbortReason,
throwIfStudioRunCancelled
} from '../../studio-agent/runtime/execution/run-cancellation'
import {
assertSandboxAvailable,
copyVerifiedRegularFile,
listPngArtifacts,
publishPngArtifacts,
resolvePythonRuntime,
spawnSandboxedProcess,
terminateSandboxProcess,
type SandboxInvocationInput,
} from '../sandbox'
export interface MatplotlibExecutionResult {
outputDir: string
scriptPath: string
imageDataUris: string[]
imagePaths: string[]
stdout: string
stderr: string
}
interface PrivateSandbox {
rootDirectory: string
inputDirectory: string
workDirectory: string
outputDirectory: string
}
function createPrivateSandbox(rootDirectory: string): PrivateSandbox {
fs.rmSync(rootDirectory, { recursive: true, force: true })
const sandbox: PrivateSandbox = {
rootDirectory,
inputDirectory: join(rootDirectory, 'input'),
workDirectory: join(rootDirectory, 'work'),
outputDirectory: join(rootDirectory, 'output'),
}
try {
for (const directory of [
sandbox.inputDirectory,
sandbox.workDirectory,
sandbox.outputDirectory,
join(sandbox.workDirectory, 'home'),
join(sandbox.workDirectory, '.cache'),
join(sandbox.workDirectory, '.config'),
join(sandbox.workDirectory, '.local', 'share'),
join(sandbox.workDirectory, 'mplconfig'),
]) {
fs.mkdirSync(directory, { recursive: true })
}
} catch (error) {
fs.rmSync(rootDirectory, { recursive: true, force: true })
throw error
}
return sandbox
}
export async function executeMatplotlibRender(input: {
workspaceDirectory: string
workspaceOutputDirectory?: string
renderId: string
code: string
signal?: AbortSignal
}): Promise<MatplotlibExecutionResult> {
throwIfStudioRunCancelled(input.signal)
// Fail before writing or executing any submitted source.
assertSandboxAvailable()
const outputDir = workspaceRenderOutputDirectory(input.workspaceDirectory, input.renderId, input.workspaceOutputDirectory)
await mkdir(outputDir, { recursive: true })
const sourcePath = join(outputDir, 'plot_script.py')
const wrapperPath = join(outputDir, 'plot_executor.py')
await writeFile(sourcePath, input.code, 'utf8')
await writeFile(wrapperPath, buildExecutorScript(), 'utf8')
const sandbox = createPrivateSandbox(join(outputDir, '.sandbox'))
try {
copyVerifiedRegularFile(sourcePath, join(sandbox.inputDirectory, 'plot_script.py'))
copyVerifiedRegularFile(wrapperPath, join(sandbox.inputDirectory, 'plot_executor.py'))
// MATPLOTLIB_PYTHON is an optional override; otherwise share the configured
// ManimGX render runtime, then the normal .venv/PATH discovery.
const matplotlibPython = process.env.MATPLOTLIB_PYTHON?.trim()
const runtime = resolvePythonRuntime(
matplotlibPython ? { explicit: matplotlibPython } : { envName: 'MANIMGX_PYTHON' }
)
const invocation: SandboxInvocationInput = {
label: `matplotlib-${input.renderId}`,
executable: runtime.executable,
args: [
'-u',
'/input/plot_executor.py',
'/input/plot_script.py',
'/output',
'/work/mplconfig',
],
cwd: '/work',
inputDirectory: sandbox.inputDirectory,
workDirectory: sandbox.workDirectory,
outputDirectory: sandbox.outputDirectory,
runtimeDirectories: runtime.mountDirectories,
pathEntries: runtime.pathEntries,
env: {
MPLCONFIGDIR: '/work/mplconfig',
},
}
const { stdout, stderr } = await runSandboxedPython(invocation, input.signal)
const sandboxImages = listPngArtifacts(sandbox.outputDirectory)
if (sandboxImages.length === 0) {
throw new Error(stderr.trim() || 'Matplotlib execution finished without producing any image output')
}
// Only verified bytes from the private output are published. stdout is never
// parsed for paths, so a malicious script cannot select a host file to read.
const imagePaths = publishPngArtifacts(sandboxImages, outputDir)
const imageDataUris = await Promise.all(imagePaths.map(async (imagePath) => {
const bytes = await readFile(imagePath)
return `data:image/png;base64,${bytes.toString('base64')}`
}))
return {
outputDir,
scriptPath: sourcePath,
imageDataUris,
imagePaths,
stdout,
stderr,
}
} finally {
fs.rmSync(sandbox.rootDirectory, { recursive: true, force: true })
}
}
function runSandboxedPython(
invocation: SandboxInvocationInput,
signal?: AbortSignal,
): Promise<{ stdout: string; stderr: string }> {
return new Promise((resolve, reject) => {
if (signal?.aborted) {
reject(new StudioRunCancelledError(readAbortReason(signal)))
return
}
let child: ReturnType<typeof spawnSandboxedProcess>
try {
child = spawnSandboxedProcess(invocation)
} catch (error) {
reject(error instanceof Error ? error : new Error(String(error)))
return
}
let stdout = ''
let stderr = ''
let finished = false
let aborted = false
let killTimer: NodeJS.Timeout | undefined
let forceSettleTimer: NodeJS.Timeout | undefined
const cleanup = () => {
signal?.removeEventListener('abort', handleAbort)
if (killTimer) {
clearTimeout(killTimer)
killTimer = undefined
}
if (forceSettleTimer) {
clearTimeout(forceSettleTimer)
forceSettleTimer = undefined
}
}
const settleReject = (error: Error) => {
if (finished) return
finished = true
cleanup()
reject(error)
}
const settleResolve = (value: { stdout: string; stderr: string }) => {
if (finished) return
finished = true
cleanup()
resolve(value)
}
const handleAbort = () => {
if (finished || aborted) return
aborted = true
terminateSandboxProcess(child, 'SIGTERM')
killTimer = setTimeout(() => {
if (!finished) terminateSandboxProcess(child, 'SIGKILL')
}, 2000)
killTimer.unref?.()
// A process stuck in uninterruptible I/O can ignore SIGKILL. Reject with a
// bounded fallback instead of leaving the Studio run pending forever.
forceSettleTimer = setTimeout(() => {
settleReject(new StudioRunCancelledError(readAbortReason(signal)))
}, 5000)
forceSettleTimer.unref?.()
}
signal?.addEventListener('abort', handleAbort, { once: true })
if (signal?.aborted) handleAbort()
child.stdout?.on('data', (chunk) => {
stdout += String(chunk)
})
child.stderr?.on('data', (chunk) => {
stderr += String(chunk)
})
child.on('error', (error) => {
settleReject(error instanceof Error ? error : new Error(String(error)))
})
child.on('close', (code) => {
if (finished) return
// bwrap has exited and its PID namespace is gone; do not signal the old
// process group because that PID/PGID may now belong to another process.
if (aborted) {
settleReject(new StudioRunCancelledError(readAbortReason(signal)))
return
}
if (code === 0) {
settleResolve({ stdout, stderr })
return
}
settleReject(new Error(stderr.trim() || `Python process exited with code ${code}`))
})
})
}
function buildExecutorScript(): string {
return [
'import os',
'import sys',
'import matplotlib',
"matplotlib.use('Agg')",
'import matplotlib.pyplot as plt',
'',
'source_path = sys.argv[1]',
'output_dir = sys.argv[2]',
'mpl_config_dir = sys.argv[3] if len(sys.argv) > 3 else None',
'if mpl_config_dir:',
' os.makedirs(mpl_config_dir, exist_ok=True)',
' os.environ["MPLCONFIGDIR"] = mpl_config_dir',
'os.makedirs(output_dir, exist_ok=True)',
'os.chdir(output_dir)',
"namespace = {'plt': plt, '__name__': '__main__', '__file__': source_path}",
'',
'with open(source_path, "r", encoding="utf-8") as f:',
' source = f.read()',
'',
'exec(compile(source, source_path, "exec"), namespace)',
'',
'figure_numbers = plt.get_fignums()',
'outputs = []',
'for index, figure_number in enumerate(figure_numbers, start=1):',
' figure = plt.figure(figure_number)',
' output_path = os.path.join(output_dir, f"plot_{index}.png")',
' figure.savefig(output_path, dpi=160, bbox_inches="tight")',
' outputs.append(output_path)',
'',
'if not outputs:',
' outputs = [',
' os.path.join(output_dir, name)',
' for name in sorted(os.listdir(output_dir))',
' if name.lower().endswith(".png")',
' ]',
'',
'if not outputs:',
' raise RuntimeError("No matplotlib figures or PNG outputs were produced by the script")',
].join('\n')
}
|