Skip to content

Commit 58c8bda

Browse files
chrmartiCopilot
andcommitted
Include the end of the failed command's output in error results
The JSON result of up, set-up, build and run-user-commands only had the failed command line as message and a generic description, so the actual error, for example Docker's 'Error response from daemon: ...', was only in the log. The new errorOutput property carries the last lines of the failed command's terminal output or standard error, without terminal control sequences, so callers like the Dev Containers extension can report the cause. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
1 parent a190a3f commit 58c8bda

3 files changed

Lines changed: 99 additions & 1 deletion

File tree

‎src/spec-common/errors.ts‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,3 +61,27 @@ export class ContainerError extends Error implements ContainerErrorInfo {
6161
}
6262
}
6363
}
64+
65+
const maxErrorOutputLines = 20;
66+
const maxErrorOutputLength = 2000;
67+
68+
/**
69+
* Returns the end of the output of the failed command that caused an error, without terminal control sequences.
70+
* That is the combined output for commands run in a terminal and the standard error for other commands.
71+
*/
72+
export function getErrorOutput(err: any): string | undefined {
73+
for (let cause = err, depth = 0; cause && typeof cause === 'object' && depth < 10; cause = cause.originalError, depth++) {
74+
const output = typeof cause.cmdOutput === 'string' ? cause.cmdOutput : cause.stderr;
75+
if (output?.length) {
76+
const lines = String(output)
77+
.replace(/\x1b\[[0-?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[@-_]/g, '')
78+
.split(/\r?\n/)
79+
// Progress output rewrites the line after a carriage return.
80+
.map(line => line.replace(/\r+$/, '').split('\r').pop()!.trimEnd())
81+
.filter(line => line.trim());
82+
const text = lines.slice(-maxErrorOutputLines).join('\n');
83+
return text.length > maxErrorOutputLength ? text.substring(text.length - maxErrorOutputLength) : text || undefined;
84+
}
85+
}
86+
return undefined;
87+
}

‎src/spec-node/devContainersSpecCLI.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ import * as jsonc from 'jsonc-parser';
1212
import { createDockerParams, createLog, launch, ProvisionOptions } from './devContainers';
1313
import { SubstitutedConfig, createContainerProperties, envListToObj, inspectDockerImage, isDockerFileConfig, SubstituteConfig, addSubstitution, findContainerAndIdLabels, getCacheFolder, runAsyncHandler, dockerArgOption } from './utils';
1414
import { URI } from 'vscode-uri';
15-
import { ContainerError } from '../spec-common/errors';
15+
import { ContainerError, getErrorOutput } from '../spec-common/errors';
1616
import { Log, LogDimensions, LogLevel, makeLog, mapLogLevel } from '../spec-utils/log';
1717
import { probeRemoteEnv, runLifecycleHooks, runRemoteCommand, UserEnvProbe, setupInContainer } from '../spec-common/injectHeadless';
1818
import { extendImage } from './containerFeatures';
@@ -381,6 +381,7 @@ async function doProvision(options: ProvisionOptions, providedIdLabels: string[]
381381
outcome: 'error' as 'error',
382382
message: err.message,
383383
description: err.description,
384+
errorOutput: getErrorOutput(err),
384385
containerId: err.containerId,
385386
disallowedFeatureId: err.data.disallowedFeatureId,
386387
didStopContainer: err.data.didStopContainer,
@@ -561,6 +562,7 @@ async function doSetUp({
561562
outcome: 'error' as 'error',
562563
message: err.message,
563564
description: err.description,
565+
errorOutput: getErrorOutput(err),
564566
dispose,
565567
};
566568
}
@@ -832,6 +834,7 @@ async function doBuild({
832834
outcome: 'error' as 'error',
833835
message: err.message,
834836
description: err.description,
837+
errorOutput: getErrorOutput(err),
835838
dispose,
836839
};
837840
}
@@ -1041,6 +1044,7 @@ async function doRunUserCommands({
10411044
outcome: 'error' as 'error',
10421045
message: err.message,
10431046
description: err.description,
1047+
errorOutput: getErrorOutput(err),
10441048
dispose,
10451049
};
10461050
}

‎src/test/errors.test.ts‎

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
/*---------------------------------------------------------------------------------------------
2+
* Copyright (c) Microsoft Corporation. All rights reserved.
3+
* Licensed under the MIT License. See License.txt in the project root for license information.
4+
*--------------------------------------------------------------------------------------------*/
5+
6+
import * as assert from 'assert';
7+
import { PassThrough } from 'stream';
8+
import { ContainerError, getErrorOutput } from '../spec-common/errors';
9+
import { runCommand, runCommandNoPty } from '../spec-common/commonUtils';
10+
import { nullLog } from '../spec-utils/log';
11+
12+
describe('getErrorOutput', () => {
13+
14+
function failPty(output: string) {
15+
return runCommand({
16+
ptyExec: async () => ({
17+
onData: (cb: (data: string) => void) => {
18+
cb(output);
19+
return { dispose() { } };
20+
},
21+
resize() { },
22+
exit: Promise.resolve({ code: 125, signal: undefined }),
23+
terminate: async () => { },
24+
}),
25+
cmd: 'docker',
26+
args: ['run', 'image'],
27+
output: nullLog,
28+
print: 'off',
29+
}).then(() => assert.fail('Expected the command to fail.'), err => err);
30+
}
31+
32+
function fail(stdout: string, stderr: string) {
33+
return runCommandNoPty({
34+
exec: async () => {
35+
const stdoutStream = new PassThrough();
36+
const stderrStream = new PassThrough();
37+
return {
38+
stdin: new PassThrough(), stdout: stdoutStream, stderr: stderrStream,
39+
exit: new Promise(resolve => setImmediate(() => {
40+
stdoutStream.end(stdout);
41+
stderrStream.end(stderr);
42+
resolve({ code: 1, signal: null });
43+
})),
44+
terminate: async () => { },
45+
};
46+
},
47+
cmd: 'docker',
48+
args: ['compose', 'up'],
49+
output: nullLog,
50+
}).then(() => assert.fail('Expected the command to fail.'), err => err);
51+
}
52+
53+
it('returns the end of the output of the failed command', async () => {
54+
const lines = Array.from({ length: 18 }, (_, i) => `line ${i}`);
55+
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`);
56+
const err = await fail('stdout', 'Error response from daemon: Conflict.\n');
57+
const long = getErrorOutput(await fail('', `${'x'.repeat(3000)}END`));
58+
assert.deepStrictEqual({
59+
pty: getErrorOutput(new ContainerError({ description: 'An error occurred setting up the container.', originalError: ptyErr })),
60+
noPty: getErrorOutput(new ContainerError({ description: 'An error occurred starting Docker Compose up.', originalError: err })),
61+
long: long && { length: long.length, end: long.slice(-5) },
62+
noOutput: getErrorOutput(new ContainerError({ description: 'The expected container does not exist.' })),
63+
}, {
64+
pty: [...lines.slice(1), 'Pulling 100%', 'docker: Error response from daemon: invalid mount config.', `Run 'docker run --help' for more information`].join('\n'),
65+
noPty: 'Error response from daemon: Conflict.',
66+
long: { length: 2000, end: 'xxEND' },
67+
noOutput: undefined,
68+
});
69+
});
70+
});

0 commit comments

Comments
 (0)