Skip to content

Commit 115a2b2

Browse files
mchwangclaude
andcommitted
Sweep reports name their stage; a gone holder is not a failure; loaded daemon tested (#189)
Review round 37: removeLabelledObjects names the stage of each failed call and says nothing of a holder gone since the listing (Docker 27.4's No such container for it), still reporting any other failure; a test loads a fresh copy of the module with DOCKER_HOST and DOCKER_CONTEXT set and shows the sweep keeps them; unit tests cover both holder inspect answers. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent b1176fd commit 115a2b2

2 files changed

Lines changed: 52 additions & 8 deletions

File tree

‎test/docker-sweep.test.ts‎

Lines changed: 42 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { join } from 'node:path';
44
import { spawnSync } from 'node:child_process';
55
import { afterEach, expect, it, vi } from 'vitest';
66
import { removeByName, removeLabelledObjects, TEST_RUN_LABEL } from './fixtures/docker-sweep.ts';
7+
import type * as Sweep from './fixtures/docker-sweep.ts';
78

89
// The test sweep's and `removeByName`'s handling of answers they cannot use (#189), each test with its own fake
910
// `docker`, described beside it. The sweep reads only stdout, the exit status, whether a signal killed the call and
@@ -47,7 +48,7 @@ it('reads nothing from a docker call that was killed, whose output may be cut sh
4748
const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
4849
removeLabelledObjects(TEST_RUN_LABEL, 'x', 'test', join(root, 'docker'));
4950
expect(readFileSync(calls, 'utf8').split('\n').filter(line => /^(ps|network rm) /.test(line))).toEqual([]);
50-
expect(warn.mock.calls).toContainEqual(['test: docker network ls failed:', 'killed by SIGKILL']);
51+
expect(warn.mock.calls).toContainEqual(['test: listing networks: docker network ls failed:', 'killed by SIGKILL']);
5152
});
5253

5354
it('removes by name only an object of exactly that name, and reports failures other than no such object', () => {
@@ -114,3 +115,43 @@ it('talks to the daemon set when it loaded, though a test changed DOCKER_HOST or
114115
expect(lines.length).toBeGreaterThan(1);
115116
expect(new Set(lines)).toEqual(new Set([loaded]));
116117
});
118+
119+
it('takes the daemon set at load, not the default, when one was set', async () => {
120+
const root = mkdtempSync(join(tmpdir(), 'codeboost-sweep-')); roots.push(root);
121+
const seen = join(root, 'seen');
122+
writeFileSync(join(root, 'docker'), ['#!/bin/sh', `printf '%s|%s\\n' "\${DOCKER_HOST-unset}" "\${DOCKER_CONTEXT-unset}" >> '${seen}'`,
123+
'if [ "$2" = inspect ]; then echo; echo "Error response from daemon: No such container: x" >&2; exit 1; fi', 'exit 0'].join('\n'),
124+
{ mode: 0o755 });
125+
// A fresh copy of the module, loaded while a daemon is set, as on a machine with Colima or rootless Docker.
126+
vi.stubEnv('DOCKER_HOST', 'unix:///codeboost-loaded.sock');
127+
vi.stubEnv('DOCKER_CONTEXT', 'codeboost-loaded');
128+
vi.resetModules();
129+
const fresh = await import('./fixtures/docker-sweep.ts') as typeof Sweep;
130+
vi.stubEnv('DOCKER_HOST', 'unix:///codeboost-changed.sock');
131+
vi.stubEnv('DOCKER_CONTEXT', 'codeboost-changed');
132+
try {
133+
fresh.removeByName('container', 'x', 'test', join(root, 'docker'));
134+
fresh.removeLabelledObjects(TEST_RUN_LABEL, 'x', 'test', join(root, 'docker'));
135+
} finally { vi.unstubAllEnvs(); }
136+
expect(new Set(readFileSync(seen, 'utf8').split('\n').filter(Boolean))).toEqual(new Set(['unix:///codeboost-loaded.sock|codeboost-loaded']));
137+
});
138+
139+
it.each([
140+
['says nothing of a holder gone since the listing', 'Error response from daemon: No such container: b', []],
141+
['reports any other failure to read the holders', 'permission denied', [['test: reading holders: docker container inspect failed:', 'permission denied']]],
142+
])('%s, and still removes the holders it read', (_label, stderr, warnings) => {
143+
const root = mkdtempSync(join(tmpdir(), 'codeboost-sweep-')); roots.push(root);
144+
const calls = join(root, 'calls'), net = 'n'.repeat(64), a = 'a'.repeat(64), b = 'b'.repeat(64);
145+
// Answers as Docker 27.4 does for one swept network with two candidate holders, one gone before the inspect: the
146+
// inspect prints the other and exits 1. Every other call gets no output and exit 0, as for `ls` with no match.
147+
writeFileSync(join(root, 'docker'), ['#!/bin/sh', `printf '%s\\n' "$*" >> '${calls}'`,
148+
`if [ "$1 $2" = "network ls" ]; then printf '%s\\n' '{"ID":"${net}","Name":"swept"}'; exit 0; fi`,
149+
`if [ "$1" = ps ]; then printf '%s\\n' ${a} ${b}; exit 0; fi`,
150+
`if [ "$1 $2" = "container inspect" ]; then printf '%s\\n' '"${a}" {"swept":{}}'; echo '${stderr}' >&2; exit 1; fi`,
151+
'exit 0'].join('\n'),
152+
{ mode: 0o755 });
153+
const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
154+
removeLabelledObjects(TEST_RUN_LABEL, 'x', 'test', join(root, 'docker'));
155+
expect(warn.mock.calls.filter(call => String(call[0]).endsWith('failed:'))).toEqual(warnings);
156+
expect(readFileSync(calls, 'utf8').split('\n')).toContain(`rm --force ${a}`);
157+
});

‎test/fixtures/docker-sweep.ts‎

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -78,9 +78,12 @@ export function removeRunnerObjects(runnerOwner: string, when = 'afterAll'): voi
7878
* default (`REAL_DOCKER`).
7979
*/
8080
export function removeLabelledObjects(label: string, value: string, when: string, docker = REAL_DOCKER): void {
81-
const run = (args: string[]) => {
81+
const run = (stage: string, args: string[]) => {
8282
const result = spawnSync(docker, args, { encoding: 'utf8', timeout: 30_000, killSignal: 'SIGKILL', env: dockerEnv() });
83-
if (result.status !== 0) console.warn(`${when}: docker ${args.slice(0, 2).join(' ')} failed:`,
83+
// A holder gone since the listing is expected: Docker 27.4 answers "No such container" for it, and prints the rest.
84+
const holdersGone = stage === 'reading holders' && result.status === 1
85+
&& result.stderr.trim().split('\n').every(line => line.startsWith('Error response from daemon: No such container: '));
86+
if (result.status !== 0 && !holdersGone) console.warn(`${when}: ${stage}: docker ${args.slice(0, 2).join(' ')} failed:`,
8487
result.error?.message ?? (result.signal ? `killed by ${result.signal}` : result.stderr.trim()));
8588
// An inspect of several objects exits 1 if one is gone, yet prints the rest (Docker 27.4), so the output of a call
8689
// that exited by itself is read whatever its status. A killed call's output may be cut short, so it is not.
@@ -94,7 +97,7 @@ export function removeLabelledObjects(label: string, value: string, when: string
9497
// Networks with their names: `ps --filter network=` finds a created, never started container by the name only
9598
// (Docker 27.4). Each is removed by its full ID, which no other network's name can be mistaken for.
9699
// As JSON: a network's name may hold spaces. Only a container's name comes with a leading slash.
97-
const listed = run([kind, 'ls', ...(kind === 'container' ? ['--all'] : []), ...(kind === 'network'
100+
const listed = run(`listing ${kind}s`, [kind, 'ls', ...(kind === 'container' ? ['--all'] : []), ...(kind === 'network'
98101
? ['--no-trunc', '--format', '{{json .}}'] : kind === 'container' ? ['--quiet', '--no-trunc'] : ['--quiet']),
99102
'--filter', `label=${label}=${value}`])
100103
.flatMap(line => kind === 'network' ? parsed<{ ID?: unknown; Name?: unknown } | null>(line)
@@ -107,18 +110,18 @@ export function removeLabelledObjects(label: string, value: string, when: string
107110
// Filters with one key match any of their values. The network filter also matches the start of another network's
108111
// ID, so a container counts only if it is on one of these networks by name (Docker refuses a second local network
109112
// of one name). Containers go by full ID: Docker resolves a name before an ID prefix.
110-
const candidates = run(['ps', '--all', '--quiet', '--no-trunc',
113+
const candidates = run('finding holders', ['ps', '--all', '--quiet', '--no-trunc',
111114
...names.flatMap(name => ['--filter', `${kind}=${name}`])]);
112-
const holders = kind === 'volume' || !candidates.length ? candidates : run(['container', 'inspect', '--format',
115+
const holders = kind === 'volume' || !candidates.length ? candidates : run('reading holders', ['container', 'inspect', '--format',
113116
'{{json .Id}} {{json .NetworkSettings.Networks}}', ...candidates]).flatMap(line => {
114117
const at = line.indexOf(' '), id = parsed<string>(line.slice(0, at)), on = parsed<Record<string, unknown>>(line.slice(at + 1));
115118
return typeof id[0] === 'string' && typeof on[0] === 'object' ? [{ id: id[0], on: Object.keys(on[0] ?? {}) }] : [];
116119
}).filter(holder => holder.on.some(name => names.includes(name))).map(holder => holder.id);
117120
if (holders.length) {
118121
console.warn(`${when} removes the containers that hold them: ${holders.join(' ')}`);
119-
run(['rm', '--force', ...holders]);
122+
run('removing holders', ['rm', '--force', ...holders]);
120123
}
121124
}
122-
run([kind, 'rm', ...(kind === 'network' ? [] : ['--force']), ...ids]);
125+
run(`removing ${kind}s`, [kind, 'rm', ...(kind === 'network' ? [] : ['--force']), ...ids]);
123126
}
124127
}

0 commit comments

Comments
 (0)