This commit is contained in:
orosmatthew 2024-02-17 15:43:39 -05:00
commit 78af9a8909
4 changed files with 153 additions and 133 deletions

View File

@ -1,7 +1,7 @@
import dotenv from 'dotenv'; import dotenv from 'dotenv';
import fs from 'fs-extra'; import fs from 'fs-extra';
import urlJoin from 'url-join'; import urlJoin from 'url-join';
import { string, z } from 'zod'; import { z } from 'zod';
import os, { EOL } from 'os'; import os, { EOL } from 'os';
import { join } from 'path'; import { join } from 'path';
import { simpleGit, SimpleGit } from 'simple-git'; import { simpleGit, SimpleGit } from 'simple-git';
@ -11,7 +11,13 @@ import { runCpp } from './run/cpp.js';
export const timeoutSeconds = 30; export const timeoutSeconds = 30;
const RunResultKind = z.enum(['CompileFailed', 'TimeLimitExceeded', 'Completed', 'SandboxError', 'RunError']); const RunResultKind = z.enum([
'CompileFailed',
'TimeLimitExceeded',
'Completed',
'SandboxError',
'RunError'
]);
export type RunResultKind = z.infer<typeof RunResultKind>; export type RunResultKind = z.infer<typeof RunResultKind>;
const RunResult = z const RunResult = z
@ -84,12 +90,10 @@ async function cloneAndRun(submissionData: SubmissionGetData) {
return; return;
} }
const tmpDir = os.tmpdir(); const tmpDir = os.tmpdir();
const buildDir = join(tmpDir, 'bwcontest-build'); const repoDir = join(tmpDir, 'bwcontest-src');
if (fs.existsSync(buildDir)) { if (fs.existsSync(repoDir)) {
fs.removeSync(buildDir); fs.removeSync(repoDir);
} }
fs.mkdirSync(buildDir);
const repoDir = join(buildDir, 'src');
fs.mkdirSync(repoDir); fs.mkdirSync(repoDir);
const teamRepoUrl = urlJoin( const teamRepoUrl = urlJoin(
@ -108,7 +112,7 @@ async function cloneAndRun(submissionData: SubmissionGetData) {
try { try {
if (submissionData.submission.teamLanguage === 'Java') { if (submissionData.submission.teamLanguage === 'Java') {
let res = await runJava({ let res = await runJava({
srcDir: buildDir, srcDir: repoDir,
mainFile: join(repoDir, problemName, problemName + '.java'), mainFile: join(repoDir, problemName, problemName + '.java'),
mainClass: problemName, mainClass: problemName,
input: submissionData.submission.problem.realInput input: submissionData.submission.problem.realInput

View File

@ -4,7 +4,8 @@ import util from 'util';
import { RunResult, timeoutSeconds } from '../index.js'; import { RunResult, timeoutSeconds } from '../index.js';
import { IRunner, IRunnerParams, IRunnerReturn } from './types.js'; import { IRunner, IRunnerParams, IRunnerReturn } from './types.js';
import kill from 'tree-kill'; import kill from 'tree-kill';
import * as fs from 'fs'; import os from 'os';
import fs from 'fs-extra';
const execPromise = util.promisify(exec); const execPromise = util.promisify(exec);
@ -21,9 +22,16 @@ interface IRunnerParamsCpp extends IRunnerParams {
export const runCpp: IRunner<IRunnerParamsCpp> = async function ( export const runCpp: IRunner<IRunnerParamsCpp> = async function (
params: IRunnerParamsCpp params: IRunnerParamsCpp
): IRunnerReturn { ): IRunnerReturn {
const tmpDir = os.tmpdir();
const buildDir = join(tmpDir, 'bwcontest-cpp');
if (fs.existsSync(buildDir)) {
fs.removeSync(buildDir);
}
fs.mkdirSync(buildDir);
console.log(`- BUILD: ${params.problemName}`); console.log(`- BUILD: ${params.problemName}`);
const configureCommand = `cmake -S ${params.srcDir} -B ${join(params.srcDir, 'build')}`; const configureCommand = `cmake -S ${params.srcDir} -B ${buildDir}`;
try { try {
await execPromise(configureCommand); await execPromise(configureCommand);
} catch (e) { } catch (e) {
@ -35,7 +43,7 @@ export const runCpp: IRunner<IRunnerParamsCpp> = async function (
}; };
} }
const compileCommand = `cmake --build ${join(params.srcDir, 'build')} --target ${params.problemName}`; const compileCommand = `cmake --build ${buildDir} --target ${params.problemName}`;
try { try {
await execPromise(compileCommand); await execPromise(compileCommand);
} catch (e) { } catch (e) {
@ -51,9 +59,9 @@ export const runCpp: IRunner<IRunnerParamsCpp> = async function (
let runCommand = ''; let runCommand = '';
if (params.cppPlatform === 'VisualStudio') { if (params.cppPlatform === 'VisualStudio') {
runCommand = `${join(params.srcDir, 'build', 'Debug', `${params.problemName}.exe`)}`; runCommand = `${join(buildDir, 'Debug', `${params.problemName}.exe`)}`;
} else { } else {
runCommand = `${join(params.srcDir, 'build', params.problemName)}`; runCommand = `${join(buildDir, params.problemName)}`;
} }
try { try {
let outputBuffer = ''; let outputBuffer = '';

View File

@ -14,76 +14,80 @@ export const runCSharp: IRunner = async function (params: {
console.log(`- RUN: ${params.srcDir}`); console.log(`- RUN: ${params.srcDir}`);
const child = spawn('dotnet run', { shell: true, cwd: params.srcDir }); const child = spawn('dotnet run', { shell: true, cwd: params.srcDir });
let outputBuffer = ''; try {
child.stdout.setEncoding('utf8'); let outputBuffer = '';
child.stdout.on('data', (data) => { child.stdout.setEncoding('utf8');
outputBuffer += data.toString(); child.stdout.on('data', (data) => {
params.outputCallback?.(data.toString()); outputBuffer += data.toString();
}); params.outputCallback?.(data.toString());
child.stderr.setEncoding('utf8'); });
child.stderr.on('data', (data) => { child.stderr.setEncoding('utf8');
outputBuffer += data.toString(); child.stderr.on('data', (data) => {
params.outputCallback?.(data.toString()); outputBuffer += data.toString();
}); params.outputCallback?.(data.toString());
});
let runStartTime = performance.now(); let runStartTime = performance.now();
child.stdin.write(params.input); child.stdin.write(params.input);
child.stdin.end(); child.stdin.end();
let timeLimitExceeded = false; let timeLimitExceeded = false;
let completedNormally = false; let completedNormally = false;
return { return {
success: true, success: true,
runResult: new Promise<RunResult>((resolve) => { runResult: new Promise<RunResult>((resolve) => {
child.on('close', () => { child.on('close', () => {
completedNormally = !timeLimitExceeded; completedNormally = !timeLimitExceeded;
let runEndTime = performance.now(); let runEndTime = performance.now();
const runtimeMilliseconds = Math.floor(runEndTime - runStartTime); const runtimeMilliseconds = Math.floor(runEndTime - runStartTime);
if (completedNormally) { if (completedNormally) {
clearTimeout(timeoutHandle); clearTimeout(timeoutHandle);
resolve({ resolve({
kind: 'Completed', kind: 'Completed',
output: outputBuffer, output: outputBuffer,
exitCode: child.exitCode!, exitCode: child.exitCode!,
runtimeMilliseconds runtimeMilliseconds
}); });
} else { } else {
console.log(`Process terminated, total sandbox time: ${runtimeMilliseconds}ms`); console.log(`Process terminated, total sandbox time: ${runtimeMilliseconds}ms`);
resolve({ resolve({
kind: 'TimeLimitExceeded', kind: 'TimeLimitExceeded',
output: outputBuffer, output: outputBuffer,
resultKindReason: `Timeout after ${timeoutSeconds} seconds` resultKindReason: `Timeout after ${timeoutSeconds} seconds`
}); });
} }
}); });
let timeoutHandle = setTimeout(() => { let timeoutHandle = setTimeout(() => {
if (completedNormally) { if (completedNormally) {
return; return;
} }
console.log(`Run timed out after ${timeoutSeconds} seconds, killing process...`); console.log(`Run timed out after ${timeoutSeconds} seconds, killing process...`);
timeLimitExceeded = true; timeLimitExceeded = true;
child.stdin.end(); child.stdin.end();
child.stdin.destroy(); child.stdin.destroy();
child.stdout.destroy(); child.stdout.destroy();
child.stderr.destroy(); child.stderr.destroy();
if (child.pid !== undefined) {
kill(child.pid);
}
}, timeoutSeconds * 1000);
}),
killFunc() {
if (child.pid !== undefined) { if (child.pid !== undefined) {
kill(child.pid); if (!completedNormally && !timeLimitExceeded) {
} kill(child.pid);
}, timeoutSeconds * 1000); params.outputCallback?.('\n[Manually stopped]');
}), }
killFunc() {
if (child.pid !== undefined) {
if (!completedNormally && !timeLimitExceeded) {
kill(child.pid);
params.outputCallback?.('\n[Manually stopped]');
} }
} }
} };
}; } catch (error) {
return { success: false, runResult: { kind: 'RunError' } };
}
}; };

View File

@ -35,73 +35,77 @@ export const runJava: IRunner<IRunnerParamsJava> = async function (
console.log(`- RUN: ${params.mainClass}`); console.log(`- RUN: ${params.mainClass}`);
const runCommand = `java -cp "${join(params.srcDir, 'build')}" ${params.mainClass}`; const runCommand = `java -cp "${join(params.srcDir, 'build')}" ${params.mainClass}`;
let outputBuffer = ''; try {
const child = spawn(runCommand, { shell: true }); let outputBuffer = '';
child.stdout.setEncoding('utf8'); const child = spawn(runCommand, { shell: true });
child.stdout.on('data', (data) => { child.stdout.setEncoding('utf8');
outputBuffer += data.toString(); child.stdout.on('data', (data) => {
}); outputBuffer += data.toString();
child.stderr.setEncoding('utf8'); });
child.stderr.on('data', (data) => { child.stderr.setEncoding('utf8');
outputBuffer += data.toString(); child.stderr.on('data', (data) => {
}); outputBuffer += data.toString();
});
let runStartTime = performance.now(); let runStartTime = performance.now();
child.stdin.write(params.input); child.stdin.write(params.input);
child.stdin.end(); child.stdin.end();
let timeLimitExceeded = false; let timeLimitExceeded = false;
let completedNormally = false; let completedNormally = false;
return { return {
success: true, success: true,
runResult: new Promise<RunResult>(async (resolve) => { runResult: new Promise<RunResult>(async (resolve) => {
child.on('close', () => { child.on('close', () => {
completedNormally = !timeLimitExceeded; completedNormally = !timeLimitExceeded;
let runEndTime = performance.now(); let runEndTime = performance.now();
const runtimeMilliseconds = Math.floor(runEndTime - runStartTime); const runtimeMilliseconds = Math.floor(runEndTime - runStartTime);
if (completedNormally) { if (completedNormally) {
clearTimeout(timeoutHandle); clearTimeout(timeoutHandle);
resolve({ resolve({
kind: 'Completed', kind: 'Completed',
output: outputBuffer, output: outputBuffer,
exitCode: child.exitCode!, exitCode: child.exitCode!,
runtimeMilliseconds runtimeMilliseconds
}); });
} else { } else {
console.log(`Process terminated, total sandbox time: ${runtimeMilliseconds}ms`); console.log(`Process terminated, total sandbox time: ${runtimeMilliseconds}ms`);
resolve({ resolve({
kind: 'TimeLimitExceeded', kind: 'TimeLimitExceeded',
output: outputBuffer, output: outputBuffer,
resultKindReason: `Timeout after ${timeoutSeconds} seconds` resultKindReason: `Timeout after ${timeoutSeconds} seconds`
}); });
} }
}); });
let timeoutHandle = setTimeout(() => { let timeoutHandle = setTimeout(() => {
if (completedNormally) { if (completedNormally) {
return; return;
} }
console.log(`Run timed out after ${timeoutSeconds} seconds, killing process...`); console.log(`Run timed out after ${timeoutSeconds} seconds, killing process...`);
timeLimitExceeded = true; timeLimitExceeded = true;
child.stdin.end(); child.stdin.end();
child.stdin.destroy(); child.stdin.destroy();
child.stdout.destroy(); child.stdout.destroy();
child.stderr.destroy(); child.stderr.destroy();
child.kill('SIGKILL'); child.kill('SIGKILL');
}, timeoutSeconds * 1000); }, timeoutSeconds * 1000);
}), }),
killFunc() { killFunc() {
if (child.pid !== undefined) { if (child.pid !== undefined) {
if (!completedNormally && !timeLimitExceeded) { if (!completedNormally && !timeLimitExceeded) {
kill(child.pid); kill(child.pid);
params.outputCallback?.('\n[Manually stopped]'); params.outputCallback?.('\n[Manually stopped]');
}
} }
} }
} };
}; } catch (error) {
return { success: false, runResult: { kind: 'RunError' } };
}
}; };