From f55a3212ceb2f6868283dc250bd8c4b4b2a1231c Mon Sep 17 00:00:00 2001 From: cdcxd Date: Thu, 26 Nov 2026 00:12:10 -0800 Subject: [PATCH] Fall back to polling when a container start event is missing Podman can lose a start event during log rotation, leaving devcontainer up waiting even though the container is running. Poll for the container if no matching event arrives within three seconds. For compose, also count stopped containers once `up -d` succeeded. Preserve equals signs in ID label values. --- src/spec-node/dockerCompose.ts | 10 +- src/spec-node/singleContainer.ts | 5 +- src/spec-node/utils.ts | 88 ++++++----- src/test/cli.up.test.ts | 43 +++++ .../.devcontainer/devcontainer.json | 5 + .../.devcontainer/docker-compose.yml | 5 + src/test/fixtures/drop-events.js | 13 ++ src/test/utils.test.ts | 149 +++++++++++++++++- 8 files changed, 277 insertions(+), 41 deletions(-) create mode 100644 src/test/configs/compose-exiting/.devcontainer/devcontainer.json create mode 100644 src/test/configs/compose-exiting/.devcontainer/docker-compose.yml create mode 100644 src/test/fixtures/drop-events.js diff --git a/src/spec-node/dockerCompose.ts b/src/spec-node/dockerCompose.ts index 410f7636d..becacefb1 100644 --- a/src/spec-node/dockerCompose.ts +++ b/src/spec-node/dockerCompose.ts @@ -356,7 +356,12 @@ async function startContainer(params: DockerResolverParameters, buildParams: Doc let cancel: () => void; const canceled = new Promise((_, reject) => cancel = reject); - const { started } = await startEventSeen(params, { [projectLabel]: projectName, [serviceLabel]: config.service }, canceled, common.output, common.getLogLevel() === LogLevel.Trace); // await getEvents, but only assign started. + // Defer polling until we run `compose up -d` after the build. + let issueStart!: () => void; + const startIssued = new Promise(resolve => { issueStart = resolve; }); + let finishStart!: () => void; + const startFinished = new Promise(resolve => { finishStart = resolve; }); + const { started } = await startEventSeen(params, { [projectLabel]: projectName, [serviceLabel]: config.service }, canceled, common.output, common.getLogLevel() === LogLevel.Trace, startIssued, startFinished); const service = composeConfig.services[config.service]; const originalImageName = service.image || getDefaultImageName(await buildParams.dockerComposeCLI(), projectName, config.service); @@ -428,6 +433,7 @@ async function startContainer(params: DockerResolverParameters, buildParams: Doc args.push(config.service); } } + issueStart(); try { if (params.isTTY) { await dockerComposePtyCLI({ ...buildParams, output: infoOutput }, ...args); @@ -444,6 +450,8 @@ async function startContainer(params: DockerResolverParameters, buildParams: Doc throw new ContainerError({ description, originalError: err, data: { fileWithError: composeFiles[0] } }); } + // Include stopped containers after `compose up -d` succeeds so an immediate exit surfaces as a setup error. + finishStart(); await started; return { diff --git a/src/spec-node/singleContainer.ts b/src/spec-node/singleContainer.ts index 362559c2e..94b1dda74 100644 --- a/src/spec-node/singleContainer.ts +++ b/src/spec-node/singleContainer.ts @@ -485,8 +485,9 @@ function getLabels(labels: string[]): string[] { function getLabelsAsRecord(labels: string[]): Record { let result: Record = {}; labels.forEach(each => { - let pair = each.split('='); - result[pair[0]] = pair[1]; + // The value may contain '='. + const i = each.indexOf('='); + result[each.slice(0, i)] = each.slice(i + 1); }); return result; } diff --git a/src/spec-node/utils.ts b/src/spec-node/utils.ts index 90b0c9868..499e1cec2 100644 --- a/src/spec-node/utils.ts +++ b/src/spec-node/utils.ts @@ -180,20 +180,35 @@ export function addSubstitution, canceled: Promise, output: Log, trace: boolean) { - if (params.cliVariant === CLIVariant.Wslc) { - return startEventSeenPolling(params, labels, canceled, output, trace); - } - const eventsProcess = await getEvents(params, { event: ['start'] }); +// The `start` event can be missed, e.g. when Podman rotates its event log. +// Wait this long for it before polling. +const startEventPollingIntervalMs = 3000; + +export async function startEventSeen(params: DockerResolverParameters, labels: Record, canceled: Promise, output: Log, trace: boolean, commandStarted: Promise = Promise.resolve(), commandFinished?: Promise) { + const labelFilters = Object.entries(labels).map(([k, v]) => `${k}=${v}`); + // wslc does not support `events` and is only detected by polling. + const useEvents = params.cliVariant !== CLIVariant.Wslc; + const eventsProcess = useEvents ? await getEvents(params, { event: ['start'] }) : undefined; return { started: new Promise((resolve, reject) => { + let stopped = false; + let finished = false; + commandFinished?.then(() => { finished = true; }); + const stop = () => { + stopped = true; + eventsProcess?.terminate(); + }; + const finish = () => { + stop(); + resolve(); + }; canceled.catch(err => { - eventsProcess.terminate(); + stop(); reject(err); }); const decoder = new StringDecoder('utf8'); let startPart = ''; - eventsProcess.stdout.on('data', async chunk => { + eventsProcess?.stdout.on('data', async chunk => { if (chunk) { const part = decoder.write(chunk); if (trace) { @@ -207,8 +222,7 @@ export async function startEventSeen(params: DockerResolverParameters, labels: R const info = JSON.parse(line); // Docker uses 'status', Podman 'Status'. Docker v29.0.0 onwards use 'Action' as 'status' is deprecated. if ((info.status || info.Status || info.Action) === 'start' && await hasLabels(params, info, labels)) { - eventsProcess.terminate(); - resolve(); + finish(); } } catch (e) { // Ignore invalid JSON. @@ -219,40 +233,40 @@ export async function startEventSeen(params: DockerResolverParameters, labels: R } } }); - }) - }; -} - -// Polling-based fallback for runtimes that don't support `events` (e.g., wslc). -function startEventSeenPolling(params: DockerResolverParameters, labels: Record, canceled: Promise, output: Log, trace: boolean) { - let stopped = false; - canceled.catch(() => { stopped = true; }); - const labelFilters = Object.entries(labels).map(([k, v]) => `${k}=${v}`); - return { - started: new Promise((resolve, reject) => { - canceled.catch(reject); - const poll = async () => { - while (!stopped) { - try { - const containers = await listContainers(params, false, labelFilters); - if (trace) { - output.write(`Log: startEventSeenPolling found ${containers.length} container(s)\r\n`); - } - if (containers.length > 0) { - resolve(); - return; - } - } catch (e) { - // Ignore transient errors during polling. + const [initialDelayMs, intervalMs] = useEvents ? [startEventPollingIntervalMs, startEventPollingIntervalMs] : [0, 500]; + pollForContainer(params, labelFilters, () => stopped, () => finished, output, trace, initialDelayMs, intervalMs, commandStarted).then(found => { + if (found) { + if (useEvents) { + output.write('Detected the container by polling.', LogLevel.Info); } - await delay(500); + finish(); } - }; - poll(); + }); }) }; } +// Poll for a matching container once the start command is issued and the initial delay has elapsed. +async function pollForContainer(params: DockerResolverParameters, labelFilters: string[], stopped: () => boolean, includeStopped: () => boolean, output: Log, trace: boolean, initialDelayMs: number, intervalMs: number, commandStarted: Promise) { + await commandStarted; + await delay(initialDelayMs); + while (!stopped()) { + try { + const containers = await listContainers(params, includeStopped(), labelFilters); + if (trace) { + output.write(`Log: startEventSeen#poll found ${containers.length} container(s)\r\n`); + } + if (containers.length > 0) { + return !stopped(); + } + } catch (e) { + // Ignore transient errors during polling. + } + await delay(intervalMs); + } + return false; +} + async function hasLabels(params: DockerResolverParameters, info: any, expectedLabels: Record) { const actualLabels = info.Actor?.Attributes // Docker uses 'id', Podman 'ID'. diff --git a/src/test/cli.up.test.ts b/src/test/cli.up.test.ts index 5fda4584f..63a3da2bc 100644 --- a/src/test/cli.up.test.ts +++ b/src/test/cli.up.test.ts @@ -56,6 +56,18 @@ describe('Dev Containers CLI', function () { await shellExec(`docker rm -f ${containerId}`); }); + it('should recover a missing start event for an ID label value containing "="', async function () { + this.timeout(60 * 1000); + const dropEvents = path.join(__dirname, 'fixtures', 'drop-events.js'); + const res = await shellExec(`${cli} up --workspace-folder ${__dirname}/configs/image --remove-existing-container --id-label demo.id=branch=topic --docker-path "${process.execPath}" --docker-arg="${dropEvents}"`); + const response = JSON.parse(res.stdout); + assert.ok(res.stderr.includes('Detected the container by polling'), 'The container was not detected by polling.'); + assert.equal(response.outcome, 'success'); + const containerId: string = response.containerId; + assert.ok(containerId, 'Container id not found.'); + await shellExec(`docker rm -f ${containerId}`); + }); + it('should fail with "not found" error when config is not found', async () => { let success = false; try { @@ -177,6 +189,37 @@ describe('Dev Containers CLI', function () { }); }); + describe('for docker-compose without a start event', () => { + let upResult: UpResult | null = null; + const testFolder = `${__dirname}/configs/compose-without-name`; + // Also removes what a hung `up` leaves behind. + after(async () => await devContainerDown({ composeProjectName: upResult?.composeProjectName || 'compose-without-name_devcontainer' })); + it('should execute successfully when the runtime reports no start event', async function () { + this.timeout(60 * 1000); + const dropEvents = path.join(__dirname, 'fixtures', 'drop-events.js'); + upResult = await devContainerUp(cli, testFolder, { extraArgs: `--remove-existing-container --docker-path "${process.execPath}" --docker-arg="${dropEvents}"` }); + assert.ok(upResult.stderr.includes('Detected the container by polling'), 'The container was not detected by polling.'); + }); + }); + + describe('for docker-compose without a start event and an exiting container', () => { + const testFolder = `${__dirname}/configs/compose-exiting`; + after(async () => await devContainerDown({ composeProjectName: 'compose-exiting_devcontainer' })); + it('should fail instead of hanging', async function () { + this.timeout(60 * 1000); + const dropEvents = path.join(__dirname, 'fixtures', 'drop-events.js'); + let success = false; + try { + await shellExec(`${cli} up --workspace-folder ${testFolder} --docker-path "${process.execPath}" --docker-arg="${dropEvents}"`); + success = true; + } catch (error) { + assert.equal(JSON.parse(error.stdout).outcome, 'error'); + assert.ok(error.stderr.includes('Detected the container by polling'), 'The container was not detected by polling.'); + } + assert.equal(success, false, 'expect non-successful call'); + }); + }); + // Additional tests to verify the handling of persisted files describe('for docker-compose with Dockerfile with features', () => { describe('with existing container and persisted override files', () => { diff --git a/src/test/configs/compose-exiting/.devcontainer/devcontainer.json b/src/test/configs/compose-exiting/.devcontainer/devcontainer.json new file mode 100644 index 000000000..cf4d80673 --- /dev/null +++ b/src/test/configs/compose-exiting/.devcontainer/devcontainer.json @@ -0,0 +1,5 @@ +{ + "dockerComposeFile": "docker-compose.yml", + "service": "app", + "workspaceFolder": "/workspace" +} diff --git a/src/test/configs/compose-exiting/.devcontainer/docker-compose.yml b/src/test/configs/compose-exiting/.devcontainer/docker-compose.yml new file mode 100644 index 000000000..a187f7da8 --- /dev/null +++ b/src/test/configs/compose-exiting/.devcontainer/docker-compose.yml @@ -0,0 +1,5 @@ +services: + app: + image: ubuntu:latest + # Exits right after it started. + command: "true" diff --git a/src/test/fixtures/drop-events.js b/src/test/fixtures/drop-events.js new file mode 100644 index 000000000..0d03de581 --- /dev/null +++ b/src/test/fixtures/drop-events.js @@ -0,0 +1,13 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// Stands in for the Docker CLI (used with `--docker-path --docker-arg=`): every command but `events` +// is passed on to Docker, while `events` never reports anything, as happens when Podman loses an event in a log rotation. +const cp = require('child_process'); + +const [command, ...args] = process.argv.slice(2); +if (command !== 'events') { + process.exit(cp.spawnSync('docker', [command, ...args], { stdio: 'inherit' }).status ?? 1); +} +setInterval(() => {}, 60000); diff --git a/src/test/utils.test.ts b/src/test/utils.test.ts index b266b9d2a..24a47b72e 100644 --- a/src/test/utils.test.ts +++ b/src/test/utils.test.ts @@ -3,8 +3,13 @@ *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; +import { PassThrough } from 'stream'; -import { isBuildxCacheToInline } from '../spec-node/utils'; +import { delay } from '../spec-common/async'; +import { CLIHost, Exec, ExecFunction, ExecParameters } from '../spec-common/commonUtils'; +import { DockerResolverParameters, isBuildxCacheToInline, startEventSeen } from '../spec-node/utils'; +import { CLIVariant } from '../spec-shutdown/dockerUtils'; +import { nullLog } from '../spec-utils/log'; describe('Utils', function () { describe('isBuildxCacheToInline', function () { @@ -27,3 +32,145 @@ describe('Utils', function () { }); }); }); + +describe('startEventSeen', function () { + this.timeout(20 * 1000); + + const labels = { 'devcontainer.local_folder': '/workspaces/demo' }; + const eventsArgs = ['events', '--format', '{{json .}}', '--filter', 'event=start']; + const psArgs = ['ps', '-q', '--filter', 'label=devcontainer.local_folder=/workspaces/demo']; + const psAllArgs = ['ps', '-q', '-a', '--filter', 'label=devcontainer.local_folder=/workspaces/demo']; + + // Stands in for the container runtime: `events` only reports what a test writes to its stdout, `ps` lists `running()`, + // and `ps -a` also `stopped`. + function runtime(cliVariant: CLIVariant, running: () => string[], stopped: string[] = []) { + const calls: ExecParameters[] = []; + const eventStdout: PassThrough[] = []; + const terminated: string[] = []; + const exec: ExecFunction = async params => { + calls.push(params); + const isEvents = params.args?.[0] === 'events'; + const stdout = new PassThrough(); + const stderr = new PassThrough(); + let exitWith!: (code: number | null, signal: string | null) => void; + const proc: Exec = { + stdin: new PassThrough(), stdout, stderr, + exit: new Promise(resolve => { exitWith = (code, signal) => resolve({ code, signal }); }), + async terminate() { + terminated.push(params.args![0]); + stdout.end(); + stderr.end(); + exitWith(null, 'SIGKILL'); + }, + }; + if (isEvents) { + eventStdout.push(stdout); + } else { + setImmediate(() => { + const all = params.args!.includes('-a'); + stdout.end(Buffer.from([...running(), ...(all ? stopped : [])].join('\n'))); + stderr.end(); + exitWith(0, null); + }); + } + return proc; + }; + const params = { + dockerCLI: 'docker', cliVariant, dockerEnv: {}, + dockerComposeCLI: async () => ({ version: '2.0.0', cmd: 'docker', args: [] }), + common: { cliHost: { exec } as CLIHost, output: nullLog }, + } as unknown as DockerResolverParameters; + return { params, eventStdout, terminated, commands: () => calls.map(call => call.args) }; + } + + // The callers reject `canceled` when starting the container fails (for `docker run`, once it exits). + function cancelable() { + let cancel!: (reason: unknown) => void; + const canceled = new Promise((_, reject) => { cancel = reject; }); + return { canceled, cancel }; + } + + it('resolves on the start event without polling', async () => { + const { params, eventStdout, terminated, commands } = runtime(CLIVariant.Docker, () => []); + const { started } = await startEventSeen(params, labels, cancelable().canceled, nullLog, false); + eventStdout[0].write(`${JSON.stringify({ status: 'start', Actor: { Attributes: labels } })}\n`); + await started; + assert.deepStrictEqual(terminated, ['events']); + // Polling is held back to give the event time to arrive. + await delay(4000); + assert.deepStrictEqual(commands(), [eventsArgs]); + }); + + it('resolves on the running container when the start event is never delivered', async () => { + const { params, terminated, commands } = runtime(CLIVariant.Docker, () => ['container']); + const { started } = await startEventSeen(params, labels, cancelable().canceled, nullLog, false); + await started; + assert.deepStrictEqual(terminated, ['events']); + assert.deepStrictEqual(commands(), [eventsArgs, psArgs]); + }); + + it('rejects when canceled without polling', async () => { + const { params, terminated, commands } = runtime(CLIVariant.Docker, () => ['container']); + const { canceled, cancel } = cancelable(); + const { started } = await startEventSeen(params, labels, canceled, nullLog, false); + const reason = new Error('docker run exited'); + cancel(reason); + await assert.rejects(started, (err: unknown) => err === reason); + assert.deepStrictEqual(terminated, ['events']); + // Polling is held back to give the event time to arrive. + await delay(4000); + assert.deepStrictEqual(commands(), [eventsArgs]); + }); + + it('polls right away for wslc, which has no `events` command', async () => { + const { params, commands } = runtime(CLIVariant.Wslc, () => ['container']); + const { started } = await startEventSeen(params, labels, cancelable().canceled, nullLog, false); + await Promise.race([started, delay(2000).then(() => { throw new Error('Polling did not start right away.'); })]); + assert.deepStrictEqual(commands(), [psArgs]); + }); + + it('stops polling when canceled', async () => { + const { params, commands } = runtime(CLIVariant.Wslc, () => []); + const { canceled, cancel } = cancelable(); + const { started } = await startEventSeen(params, labels, canceled, nullLog, false); + while (commands().length < 2) { + await delay(50); + } + const reason = new Error('wslc run exited'); + cancel(reason); + await assert.rejects(started, (err: unknown) => err === reason); + // Several polling intervals. + await delay(1500); + assert.deepStrictEqual(commands(), [psArgs, psArgs]); + }); + + it('resolves on a stopped container once the command finished', async () => { + const { params, commands } = runtime(CLIVariant.Docker, () => [], ['container']); + let finishCommand!: () => void; + const commandFinished = new Promise(resolve => { finishCommand = resolve; }); + const { started } = await startEventSeen(params, labels, cancelable().canceled, nullLog, false, Promise.resolve(), commandFinished); + // Only running containers count while the command runs. + while (commands().length < 2) { + await delay(50); + } + finishCommand(); + await started; + assert.deepStrictEqual(commands(), [eventsArgs, psArgs, psAllArgs]); + }); + + it('does not poll before the command that starts the container was issued', async () => { + const { params, commands } = runtime(CLIVariant.Docker, () => ['container']); + let issueCommand!: () => void; + const commandStarted = new Promise(resolve => { issueCommand = resolve; }); + const { started } = await startEventSeen(params, labels, cancelable().canceled, nullLog, false, commandStarted); + // Longer than the interval the event gets: polling would have started if it did not wait for the command. + await delay(4000); + assert.deepStrictEqual(commands(), [eventsArgs]); + issueCommand(); + // The event now gets its time to arrive. + await delay(1500); + assert.deepStrictEqual(commands(), [eventsArgs]); + await started; + assert.deepStrictEqual(commands(), [eventsArgs, psArgs]); + }); +});