Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions src/spec-common/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,3 +61,27 @@ export class ContainerError extends Error implements ContainerErrorInfo {
}
}
}

const maxErrorOutputLines = 20;
const maxErrorOutputLength = 2000;

/**
* Returns the end of the output of the failed command that caused an error, without terminal control sequences.
* That is the combined output for commands run in a terminal and the standard error for other commands.
*/
export function getErrorOutput(err: any): string | undefined {
for (let cause = err, depth = 0; cause && typeof cause === 'object' && depth < 10; cause = cause.originalError, depth++) {
const output = typeof cause.cmdOutput === 'string' ? cause.cmdOutput : cause.stderr;
if (output?.length) {
const lines = String(output)
.replace(/\x1b\[[0-?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[@-_]/g, '')
.split(/\r?\n/)
// Progress output rewrites the line after a carriage return.
.map(line => line.replace(/\r+$/, '').split('\r').pop()!.trimEnd())
.filter(line => line.trim());
const text = lines.slice(-maxErrorOutputLines).join('\n');
return text.length > maxErrorOutputLength ? text.substring(text.length - maxErrorOutputLength) : text || undefined;
}
}
return undefined;
}
6 changes: 5 additions & 1 deletion src/spec-node/devContainersSpecCLI.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import * as jsonc from 'jsonc-parser';
import { createDockerParams, createLog, launch, ProvisionOptions } from './devContainers';
import { SubstitutedConfig, createContainerProperties, envListToObj, inspectDockerImage, isDockerFileConfig, SubstituteConfig, addSubstitution, findContainerAndIdLabels, getCacheFolder, runAsyncHandler, dockerArgOption } from './utils';
import { URI } from 'vscode-uri';
import { ContainerError } from '../spec-common/errors';
import { ContainerError, getErrorOutput } from '../spec-common/errors';
import { Log, LogDimensions, LogLevel, makeLog, mapLogLevel } from '../spec-utils/log';
import { probeRemoteEnv, runLifecycleHooks, runRemoteCommand, UserEnvProbe, setupInContainer } from '../spec-common/injectHeadless';
import { extendImage } from './containerFeatures';
Expand Down Expand Up @@ -381,6 +381,7 @@ async function doProvision(options: ProvisionOptions, providedIdLabels: string[]
outcome: 'error' as 'error',
message: err.message,
description: err.description,
errorOutput: getErrorOutput(err),
containerId: err.containerId,
disallowedFeatureId: err.data.disallowedFeatureId,
didStopContainer: err.data.didStopContainer,
Expand Down Expand Up @@ -561,6 +562,7 @@ async function doSetUp({
outcome: 'error' as 'error',
message: err.message,
description: err.description,
errorOutput: getErrorOutput(err),
dispose,
};
}
Expand Down Expand Up @@ -832,6 +834,7 @@ async function doBuild({
outcome: 'error' as 'error',
message: err.message,
description: err.description,
errorOutput: getErrorOutput(err),
dispose,
};
}
Expand Down Expand Up @@ -1041,6 +1044,7 @@ async function doRunUserCommands({
outcome: 'error' as 'error',
message: err.message,
description: err.description,
errorOutput: getErrorOutput(err),
dispose,
};
}
Expand Down
70 changes: 70 additions & 0 deletions src/test/errors.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/

import * as assert from 'assert';
import { PassThrough } from 'stream';
import { ContainerError, getErrorOutput } from '../spec-common/errors';
import { runCommand, runCommandNoPty } from '../spec-common/commonUtils';
import { nullLog } from '../spec-utils/log';

describe('getErrorOutput', () => {

function failPty(output: string) {
return runCommand({
ptyExec: async () => ({
onData: (cb: (data: string) => void) => {
cb(output);
return { dispose() { } };
},
resize() { },
exit: Promise.resolve({ code: 125, signal: undefined }),
terminate: async () => { },
}),
cmd: 'docker',
args: ['run', 'image'],
output: nullLog,
print: 'off',
}).then(() => assert.fail('Expected the command to fail.'), err => err);
}

function fail(stdout: string, stderr: string) {
return runCommandNoPty({
exec: async () => {
const stdoutStream = new PassThrough();
const stderrStream = new PassThrough();
return {
stdin: new PassThrough(), stdout: stdoutStream, stderr: stderrStream,
exit: new Promise(resolve => setImmediate(() => {
stdoutStream.end(stdout);
stderrStream.end(stderr);
resolve({ code: 1, signal: null });
})),
terminate: async () => { },
};
},
cmd: 'docker',
args: ['compose', 'up'],
output: nullLog,
}).then(() => assert.fail('Expected the command to fail.'), err => err);
}

it('returns the end of the output of the failed command', async () => {
const lines = Array.from({ length: 18 }, (_, i) => `line ${i}`);
const ptyErr = await failPty(`${lines.join('\r\n')}\r\nPulling 10%\rPulling 100%\r\n\r\n\x1b[31mdocker: Error response from daemon: invalid mount config.\x1b[0m\r\n\x1b]0;title\x07Run 'docker run --help' for more information\r\n`);
const err = await fail('stdout', 'Error response from daemon: Conflict.\n');
const long = getErrorOutput(await fail('', `${'x'.repeat(3000)}END`));
assert.deepStrictEqual({
pty: getErrorOutput(new ContainerError({ description: 'An error occurred setting up the container.', originalError: ptyErr })),
noPty: getErrorOutput(new ContainerError({ description: 'An error occurred starting Docker Compose up.', originalError: err })),
long: long && { length: long.length, end: long.slice(-5) },
noOutput: getErrorOutput(new ContainerError({ description: 'The expected container does not exist.' })),
}, {
pty: [...lines.slice(1), 'Pulling 100%', 'docker: Error response from daemon: invalid mount config.', `Run 'docker run --help' for more information`].join('\n'),
noPty: 'Error response from daemon: Conflict.',
long: { length: 2000, end: 'xxEND' },
noOutput: undefined,
});
});
});
Loading