From 9e78fa99aeac59124ec63700a3d92519201d505a Mon Sep 17 00:00:00 2001 From: partouf Date: Mon, 5 Sep 2022 17:34:01 +0200 Subject: [PATCH] tsify exec.js and the consequences --- lib/base-compiler.ts | 101 +++++++++++++------- lib/compilers/beebasm.ts | 14 ++- lib/compilers/dotnet.ts | 20 ++-- lib/compilers/pony.ts | 7 +- lib/compilers/rga.ts | 7 +- lib/compilers/rust.ts | 11 ++- lib/{exec.js => exec.ts} | 64 +++++++++---- test/base-compiler-tests.js | 12 ++- types/compilation/compilation.interfaces.ts | 5 + types/execution/execution.interfaces.ts | 13 +++ 10 files changed, 167 insertions(+), 87 deletions(-) rename lib/{exec.js => exec.ts} (91%) diff --git a/lib/base-compiler.ts b/lib/base-compiler.ts index 885ca6cd3..bb0934e1a 100644 --- a/lib/base-compiler.ts +++ b/lib/base-compiler.ts @@ -39,7 +39,7 @@ import { LLVMOptPipelineBackendOptions, LLVMOptPipelineOutput, } from '../types/compilation/llvm-opt-pipeline-output.interfaces'; -import {UnprocessedExecResult} from '../types/execution/execution.interfaces'; +import {BasicExecutionResult, UnprocessedExecResult} from '../types/execution/execution.interfaces'; import {ParseFilters} from '../types/features/filters.interfaces'; import {Language} from '../types/languages.interfaces'; import {Library, LibraryVersion, SelectedLibraryVersion} from '../types/libraries/libraries.interfaces'; @@ -346,10 +346,7 @@ export class BaseCompiler { } const result = await this.exec(compiler, options, execOptions); - result.inputFilename = inputFilename; - const transformedInput = result.filenameTransform(inputFilename); - this.parseCompilationOutput(result, transformedInput); - return result; + return this.transformToCompilationResult(result, inputFilename); } async runCompilerRawOutput(compiler, options, inputFilename, execOptions) { @@ -362,13 +359,10 @@ export class BaseCompiler { } const result = await this.exec(compiler, options, execOptions); - result.inputFilename = inputFilename; - return result; - } - - parseCompilationOutput(result, inputFilename: string) { - result.stdout = utils.parseOutput(result.stdout, inputFilename); - result.stderr = utils.parseOutput(result.stderr, inputFilename); + return { + ...result, + inputFilename, + }; } supportsObjdump() { @@ -423,30 +417,61 @@ export class BaseCompiler { return result; } - async execBinary(executable, maxSize, executeParameters, homeDir) { + processExecutionResult(input: UnprocessedExecResult, inputFilename?: string): BasicExecutionResult { + return { + ...input, + stdout: utils.parseOutput(input.stdout, inputFilename), + stderr: utils.parseOutput(input.stderr, inputFilename), + }; + } + + getEmptyExecutionResult(): BasicExecutionResult { + return { + code: -1, + okToCache: false, + filenameTransform: x => x, + stdout: [], + stderr: [], + execTime: '', + timedOut: false, + }; + } + + transformToCompilationResult(input: UnprocessedExecResult, inputFilename): CompilationResult { + const transformedInput = input.filenameTransform(inputFilename); + + return { + inputFilename, + ...this.processExecutionResult(input, transformedInput), + }; + } + + async execBinary(executable, maxSize, executeParameters, homeDir): Promise { // We might want to save this in the compilation environment once execution is made available const timeoutMs = this.env.ceProps('binaryExecTimeoutMs', 2000); try { - const execResult = await exec.sandbox(executable, executeParameters.args, { + const execResult: UnprocessedExecResult = await exec.sandbox(executable, executeParameters.args, { maxOutput: maxSize, timeoutMs: timeoutMs, - ldPath: _.union(this.compiler.ldPath, executeParameters.ldPath).join(':'), + ldPath: _.union(this.compiler.ldPath, executeParameters.ldPath), input: executeParameters.stdin, env: executeParameters.env, customCwd: homeDir, appHome: homeDir, }); - execResult.stdout = utils.parseOutput(execResult.stdout); - execResult.stderr = utils.parseOutput(execResult.stderr); - return execResult; + + return this.processExecutionResult(execResult); } catch (err: UnprocessedExecResult | any) { - // TODO: is this the best way? Perhaps failures in sandbox shouldn't reject - // with "results", but instead should play on? - return { - stdout: err.stdout ? utils.parseOutput(err.stdout) : [], - stderr: err.stderr ? utils.parseOutput(err.stderr) : [], - code: err.code !== undefined ? err.code : -1, - }; + if (err.code && err.stderr) { + return this.processExecutionResult(err); + } else { + return { + ...this.getEmptyExecutionResult(), + stdout: err.stdout ? utils.parseOutput(err.stdout) : [], + stderr: err.stderr ? utils.parseOutput(err.stderr) : [], + code: err.code !== undefined ? err.code : -1, + }; + } } } @@ -1494,9 +1519,11 @@ export class BaseCompiler { await fs.writeFile(outputFilename, source); executeParameters.args.unshift(outputFilename); const result = await this.runExecutable(this.compiler.exe, executeParameters, dirPath); - result.didExecute = true; - result.buildResult = {code: 0}; - return result; + return { + ...result, + didExecute: true, + buildResult: {code: 0}, + }; } async handleExecution(key, executeParameters) { @@ -1538,9 +1565,11 @@ export class BaseCompiler { executeParameters.ldPath = this.getSharedLibraryPathsAsLdLibraryPathsForExecution(key.libraries); const result = await this.runExecutable(buildResult.executableFilename, executeParameters, buildResult.dirPath); - result.didExecute = true; - result.buildResult = buildResult; - return result; + return { + ...result, + didExecute: true, + buildResult: buildResult, + }; } getCacheKey(source, options, backendOptions, filters, tools, libraries, files) { @@ -1791,9 +1820,7 @@ export class BaseCompiler { async doBuildstep(command, args, execParams) { const result = await this.exec(command, args, execParams); - result.stdout = utils.parseOutput(result.stdout); - result.stderr = utils.parseOutput(result.stderr); - return result; + return this.processExecutionResult(result); } handleUserError(error, dirPath) { @@ -1808,8 +1835,10 @@ export class BaseCompiler { } async doBuildstepAndAddToResult(result, name, command, args, execParams) { - const stepResult = await this.doBuildstep(command, args, execParams); - stepResult.step = name; + const stepResult = { + ...(await this.doBuildstep(command, args, execParams)), + step: name, + }; logger.debug(name); result.buildsteps.push(stepResult); return stepResult; diff --git a/lib/compilers/beebasm.ts b/lib/compilers/beebasm.ts index de250db63..f750604cf 100644 --- a/lib/compilers/beebasm.ts +++ b/lib/compilers/beebasm.ts @@ -63,16 +63,16 @@ export class BeebAsmCompiler extends BaseCompiler { const hasBootOption = options.some(opt => opt.includes('-boot')); - const result = await this.exec(compiler, options, execOptions); - result.inputFilename = inputFilename; - const transformedInput = result.filenameTransform(inputFilename); + const compilerExecResult = await this.exec(compiler, options, execOptions); - if (result.stdout.length > 0) { + if (compilerExecResult.stdout.length > 0) { const outputFilename = this.getOutputFilename(dirPath, this.outputFilebase); - fs.writeFileSync(outputFilename, result.stdout); - result.stdout = ''; + fs.writeFileSync(outputFilename, compilerExecResult.stdout); + compilerExecResult.stdout = ''; } + const result = this.transformToCompilationResult(compilerExecResult, inputFilename); + if (result.code === 0 && options.includes('-v')) { const diskfile = path.join(dirPath, 'disk.ssd'); if (await utils.fileExists(diskfile)) { @@ -89,8 +89,6 @@ export class BeebAsmCompiler extends BaseCompiler { } } - this.parseCompilationOutput(result, transformedInput); - const hasNoSaveError = result.stderr.some(opt => opt.text.includes('warning: no SAVE command in source file')); if (hasNoSaveError) { if (!result.hints) result.hints = []; diff --git a/lib/compilers/dotnet.ts b/lib/compilers/dotnet.ts index 28263bf42..264bad61e 100644 --- a/lib/compilers/dotnet.ts +++ b/lib/compilers/dotnet.ts @@ -26,6 +26,7 @@ import path from 'path'; import fs from 'fs-extra'; +import {CompilationResult, ExecutionOptions} from '../../types/compilation/compilation.interfaces'; import {BaseCompiler} from '../base-compiler'; import {DotNetAsmParser} from '../parsers/asm-parser-dotnet'; @@ -82,13 +83,18 @@ class DotNetCompiler extends BaseCompiler { ]; } - override async runCompiler(compiler, options, inputFileName, execOptions) { + override async runCompiler( + compiler: string, + options: string[], + inputFilename: string, + execOptions: ExecutionOptions, + ): Promise { if (!execOptions) { execOptions = this.getDefaultExecOptions(); } - const programDir = path.dirname(inputFileName); - const sourceFile = path.basename(inputFileName); + const programDir = path.dirname(inputFilename); + const sourceFile = path.basename(inputFilename); const projectFilePath = path.join(programDir, `CompilerExplorer${this.lang.extensions[0]}proj`); const crossgen2Path = path.join(this.clrBuildDir, 'crossgen2', 'crossgen2.dll'); @@ -149,7 +155,7 @@ class DotNetCompiler extends BaseCompiler { crossgen2Options.push(options[switchIndex]); } - const compilerResult = await super.runCompiler(compiler, this.compilerOptions, inputFileName, execOptions); + const compilerResult = await super.runCompiler(compiler, this.compilerOptions, inputFilename, execOptions); if (compilerResult.code !== 0) { return compilerResult; @@ -194,10 +200,8 @@ class DotNetCompiler extends BaseCompiler { '--compilebubblegenerics', ].concat(options); - const result = await this.exec(compiler, crossgen2Options, execOptions); - result.inputFilename = dllPath; - const transformedInput = result.filenameTransform(dllPath); - this.parseCompilationOutput(result, transformedInput); + const compilerExecResult = await this.exec(compiler, crossgen2Options, execOptions); + const result = this.transformToCompilationResult(compilerExecResult, dllPath); await fs.writeFile( outputPath, diff --git a/lib/compilers/pony.ts b/lib/compilers/pony.ts index 7909064ee..004f41cc7 100644 --- a/lib/compilers/pony.ts +++ b/lib/compilers/pony.ts @@ -94,10 +94,7 @@ export class PonyCompiler extends BaseCompiler { // So we must set the input to the directory rather than a file. options = _.map(options, arg => (arg.includes(inputFilename) ? path.dirname(arg) : arg)); - const result = await this.exec(compiler, options, execOptions); - result.inputFilename = inputFilename; - const transformedInput = result.filenameTransform(inputFilename); - this.parseCompilationOutput(result, transformedInput); - return result; + const compilerExecResult = await this.exec(compiler, options, execOptions); + return this.transformToCompilationResult(compilerExecResult, inputFilename); } } diff --git a/lib/compilers/rga.ts b/lib/compilers/rga.ts index aec9d2084..36ffcc206 100644 --- a/lib/compilers/rga.ts +++ b/lib/compilers/rga.ts @@ -116,10 +116,7 @@ Please supply an ASIC from the following options:`, } const result = await this.execDXCandRGA(compiler, options, execOptions); - result.inputFilename = inputFilename; - const transformedInput = result.filenameTransform(inputFilename); - this.parseCompilationOutput(result, transformedInput); - return result; + return this.transformToCompilationResult(result, inputFilename); } async execDXCandRGA(filepath: string, args: string[], execOptions: ExecutionOptions): Promise { @@ -182,7 +179,7 @@ Please supply an ASIC from the following options:`, '-s', 'vk-spv-txt-offline', '-c', - asicSelection.asic, + asicSelection.asic || '', '--isa', outputFile, '--livereg', diff --git a/lib/compilers/rust.ts b/lib/compilers/rust.ts index f1d0d3a89..a9fc71d5a 100644 --- a/lib/compilers/rust.ts +++ b/lib/compilers/rust.ts @@ -26,9 +26,9 @@ import path from 'path'; import _ from 'underscore'; +import {BasicExecutionResult, UnprocessedExecResult} from '../../types/execution/execution.interfaces'; import {BaseCompiler} from '../base-compiler'; import {BuildEnvDownloadInfo} from '../buildenvsetup/buildenv.interfaces'; -import {logger} from '../logger'; import {parseRustOutput} from '../utils'; import {RustParser} from './argument-parsers'; @@ -160,8 +160,11 @@ export class RustCompiler extends BaseCompiler { return true; } - override parseCompilationOutput(result, inputFilename) { - result.stdout = parseRustOutput(result.stdout, inputFilename); - result.stderr = parseRustOutput(result.stderr, inputFilename); + override processExecutionResult(input: UnprocessedExecResult, inputFilename?: string): BasicExecutionResult { + return { + ...input, + stdout: parseRustOutput(input.stdout, inputFilename), + stderr: parseRustOutput(input.stderr, inputFilename), + }; } } diff --git a/lib/exec.js b/lib/exec.ts similarity index 91% rename from lib/exec.js rename to lib/exec.ts index 2bd37f2e0..7fb8fca0b 100644 --- a/lib/exec.js +++ b/lib/exec.ts @@ -30,9 +30,18 @@ import Graceful from 'node-graceful'; import treeKill from 'tree-kill'; import _ from 'underscore'; +import {ExecutionOptions} from '../types/compilation/compilation.interfaces'; +import {FilenameTransformFunc, UnprocessedExecResult} from '../types/execution/execution.interfaces'; + import {logger} from './logger'; import {propsFor} from './properties'; +type NsJailOptions = { + args: string[]; + options: ExecutionOptions; + filenameTransform: FilenameTransformFunc; +}; + const execProps = propsFor('execution'); function setupOnError(stream, name) { @@ -42,17 +51,19 @@ function setupOnError(stream, name) { }); } -export function executeDirect(command, args, options, filenameTransform) { - // filename transform is expected to have been pre-applied by the caller. - // it is passed through here only so clients can see it in the result. - filenameTransform = filenameTransform || (x => x); +export async function executeDirect( + command: string, + args: string[], + options: ExecutionOptions, + filenameTransform?: FilenameTransformFunc, +): Promise { options = options || {}; const maxOutput = options.maxOutput || 1024 * 1024; const timeoutMs = options.timeoutMs || 0; const env = {...process.env, ...options.env}; if (options.ldPath) { - env.LD_LIBRARY_PATH = options.ldPath; + env.LD_LIBRARY_PATH = options.ldPath.join(path.delimiter); } if (options.wrapper) { @@ -85,7 +96,7 @@ export function executeDirect(command, args, options, filenameTransform) { const kill = options.killChild || (() => { - if (running) treeKill(child.pid); + if (running && child && child.pid) treeKill(child.pid); }); const streams = { @@ -138,11 +149,11 @@ export function executeDirect(command, args, options, filenameTransform) { if (code === null) code = -1; if (timeout !== undefined) clearTimeout(timeout); const endTime = process.hrtime.bigint(); - const result = { + const result: UnprocessedExecResult = { code, okToCache, timedOut, - filenameTransform, + filenameTransform: filenameTransform || (x => x), stdout: streams.stdout, stderr: streams.stderr, execTime: ((endTime - startTime) / BigInt(1000000)).toString(), @@ -157,7 +168,7 @@ export function executeDirect(command, args, options, filenameTransform) { }); } -export function getNsJailCfgFilePath(configName) { +export function getNsJailCfgFilePath(configName: string): string { const propKey = `nsjail.config.${configName}`; const configPath = execProps(propKey); if (configPath === undefined) { @@ -167,7 +178,7 @@ export function getNsJailCfgFilePath(configName) { return configPath; } -export function getFirejailProfileFilePath(profileName) { +export function getFirejailProfileFilePath(profileName: string): string { const propKey = `firejail.profile.${profileName}`; const profilePath = execProps(propKey); if (profilePath === undefined) { @@ -177,7 +188,12 @@ export function getFirejailProfileFilePath(profileName) { return profilePath; } -export function getNsJailOptions(configName, command, args, options) { +export function getNsJailOptions( + configName: string, + command: string, + args: string[], + options: ExecutionOptions, +): NsJailOptions { options = {...options}; const jailingOptions = ['--config', getNsJailCfgFilePath(configName)]; @@ -222,7 +238,7 @@ export function getNsJailOptions(configName, command, args, options) { }; } -export function getSandboxNsjailOptions(command, args, options) { +export function getSandboxNsjailOptions(command: string, args: string[], options: ExecutionOptions): NsJailOptions { // If we already had a custom cwd, use that. if (options.customCwd) { let relativeCommand = command; @@ -251,7 +267,7 @@ function executeNsjail(command, args, options) { return executeDirect(execProps('nsjail'), nsOpts.args, nsOpts.options, nsOpts.filenameTransform); } -function withFirejailTimeout(args, options) { +function withFirejailTimeout(args: string[], options?) { if (options && options.timeoutMs) { // const ExtraWallClockLeewayMs = 1000; const ExtraCpuLeewayMs = 1500; @@ -260,7 +276,7 @@ function withFirejailTimeout(args, options) { return args; } -function sandboxFirejail(command, args, options) { +function sandboxFirejail(command: string, args: string[], options) { logger.info('Sandbox execution via firejail', {command, args}); const execPath = path.dirname(command); const execName = path.basename(command); @@ -298,7 +314,11 @@ const sandboxDispatchTable = { firejail: sandboxFirejail, }; -export async function sandbox(command, args, options) { +export async function sandbox( + command: string, + args: string[], + options: ExecutionOptions, +): Promise { const type = execProps('sandboxType', 'firejail'); const dispatchEntry = sandboxDispatchTable[type]; if (!dispatchEntry) throw new Error(`Bad sandbox type ${type}`); @@ -309,7 +329,7 @@ const wineSandboxName = 'ce-wineserver'; // WINE takes a while to initialise and very often we don't need to run it at // all during startup. So, we do just the bare minimum at startup and then make // a promise that all subsequent WINE calls wait on. -let wineInitPromise = null; +let wineInitPromise: Promise | null; export function startWineInit() { const wine = execProps('wine'); @@ -327,7 +347,7 @@ export function startWineInit() { logger.info(`Initialising WINE in ${prefix}`); - const asyncSetup = async () => { + const asyncSetup = async (): Promise => { if (!(await fs.pathExists(prefix))) { logger.info(`Creating directory ${prefix}`); await fs.mkdir(prefix); @@ -374,9 +394,9 @@ export function startWineInit() { }); Graceful.on('exit', () => { - const waitingPromises = []; + const waitingPromises: Promise[] = []; - function waitForExit(process, name) { + function waitForExit(process, name): Promise { return new Promise(resolve => { process.on('close', () => { logger.info(`Process '${name}' closed`); @@ -507,7 +527,11 @@ const executeDispatchTable = { needsWine(command) ? executeFirejail(command, args, options) : executeNsjail(command, args, options), }; -export async function execute(command, args, options) { +export async function execute( + command: string, + args: string[], + options: ExecutionOptions, +): Promise { const type = execProps('executionType', 'none'); const dispatchEntry = executeDispatchTable[type]; if (!dispatchEntry) throw new Error(`Bad sandbox type ${type}`); diff --git a/test/base-compiler-tests.js b/test/base-compiler-tests.js index abb79d285..61d9bd858 100644 --- a/test/base-compiler-tests.js +++ b/test/base-compiler-tests.js @@ -302,7 +302,17 @@ describe('Compiler execution', function () { stubOutCallToExec(execStub, compiler, 'This is the output file', fakeExecResults); const source = 'Some cacheable source'; const options = 'Some cacheable options'; - ceMock.expects('cachePut').withArgs(match({source, options}), match(fakeExecResults)).resolves(); + ceMock + .expects('cachePut') + .withArgs( + match({source, options}), + match({ + ...fakeExecResults, + stdout: [{text: 'stdout'}], + stderr: [{text: 'stderr'}], + }), + ) + .resolves(); const uncachedResult = await compiler.compile(source, options, {}, {}, false, [], {}, []); uncachedResult.code.should.equal(0); ceMock.verify(); diff --git a/types/compilation/compilation.interfaces.ts b/types/compilation/compilation.interfaces.ts index 71c14de28..3f1703b0f 100644 --- a/types/compilation/compilation.interfaces.ts +++ b/types/compilation/compilation.interfaces.ts @@ -80,6 +80,10 @@ export type CompilationResult = { hasHaskellCmmOutput?: boolean; haskellCmmOutput?: any; + + forceBinaryView?: boolean; + bbcdiskimage?: string; + hints?: string[]; }; export type ExecutionOptions = { @@ -92,6 +96,7 @@ export type ExecutionOptions = { appHome?: string; customCwd?: string; input?: any; + killChild?: () => void; }; export type BuildResult = { diff --git a/types/execution/execution.interfaces.ts b/types/execution/execution.interfaces.ts index be849c988..4422e4875 100644 --- a/types/execution/execution.interfaces.ts +++ b/types/execution/execution.interfaces.ts @@ -1,3 +1,5 @@ +import {ResultLine} from '../resultline/resultline.interfaces'; + export type FilenameTransformFunc = (filename: string) => string; export type UnprocessedExecResult = { @@ -7,6 +9,7 @@ export type UnprocessedExecResult = { stdout: string; stderr: string; execTime: string; + timedOut: boolean; }; export type TypicalExecutionFunc = ( @@ -14,3 +17,13 @@ export type TypicalExecutionFunc = ( args: string[], execOptions: object, ) => Promise; + +export type BasicExecutionResult = { + code: number; + okToCache: boolean; + filenameTransform: FilenameTransformFunc; + stdout: ResultLine[]; + stderr: ResultLine[]; + execTime: string; + timedOut: boolean; +};