|
| 1 | +import { VM } from "@earendil-works/gondolin"; |
| 2 | + |
| 3 | +type SandboxOptions = { |
| 4 | + accel?: "kvm" | "hvf" | "tcg"; |
| 5 | + cpu?: string; |
| 6 | + machineType?: string; |
| 7 | +}; |
| 8 | + |
| 9 | +function parseCommand(argv: string[]): string[] { |
| 10 | + const args = argv.slice(2); |
| 11 | + if (args.length === 0) { |
| 12 | + throw new Error("missing command to execute"); |
| 13 | + } |
| 14 | + return args; |
| 15 | +} |
| 16 | + |
| 17 | +function resolveSandboxOptions(): SandboxOptions | undefined { |
| 18 | + const accel = process.env.GONDOLIN_SMOKE_ACCEL?.trim(); |
| 19 | + const cpu = process.env.GONDOLIN_SMOKE_CPU?.trim(); |
| 20 | + const machineType = process.env.GONDOLIN_SMOKE_MACHINE?.trim(); |
| 21 | + |
| 22 | + const out: SandboxOptions = {}; |
| 23 | + if (accel === "kvm" || accel === "hvf" || accel === "tcg") { |
| 24 | + out.accel = accel; |
| 25 | + } |
| 26 | + if (cpu) { |
| 27 | + out.cpu = cpu; |
| 28 | + } |
| 29 | + if (machineType) { |
| 30 | + out.machineType = machineType; |
| 31 | + } |
| 32 | + |
| 33 | + return Object.keys(out).length > 0 ? out : undefined; |
| 34 | +} |
| 35 | + |
| 36 | +async function main() { |
| 37 | + const command = parseCommand(process.argv); |
| 38 | + const sandbox = resolveSandboxOptions(); |
| 39 | + |
| 40 | + let vm: VM | null = null; |
| 41 | + try { |
| 42 | + vm = await VM.create({ |
| 43 | + sandbox, |
| 44 | + }); |
| 45 | + |
| 46 | + const result = await vm.exec(command); |
| 47 | + |
| 48 | + process.stdout.write(result.stdout); |
| 49 | + process.stderr.write(result.stderr); |
| 50 | + |
| 51 | + if (result.signal !== undefined) { |
| 52 | + process.stderr.write(`process exited due to signal ${result.signal}\n`); |
| 53 | + process.exit(1); |
| 54 | + } |
| 55 | + |
| 56 | + process.exit(result.exitCode); |
| 57 | + } finally { |
| 58 | + if (vm) { |
| 59 | + await vm.close().catch(() => { |
| 60 | + // ignore close errors |
| 61 | + }); |
| 62 | + } |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | +main().catch((error) => { |
| 67 | + const message = error instanceof Error ? error.message : String(error); |
| 68 | + process.stderr.write(`${message}\n`); |
| 69 | + process.exit(1); |
| 70 | +}); |
0 commit comments