Files
caprover/dev-scripts/test-compose-command-entrypoint-docker.js
T
Kasra Bigdeli 2e3fa37343 Support standard Docker Compose command/entrypoint semantics and One-Click v5 catalog (#2561)
* Support standard Docker Compose command/entrypoint semantics and One-Click v5 catalog

* Address PR review: simplify helpers/tests, reject NUL args, validate template response

* Address follow-up PR comments and wire Docker Swarm test into CI
2026-11-30 22:33:18 -08:00

406 lines
14 KiB
JavaScript

// Requires `npm ci`, `npm run build`, and a local Docker daemon with Swarm active
// (or pass `--ephemeral-swarm` on an isolated runner to init/leave Swarm automatically).
const assert = require('node:assert/strict')
const { execFileSync } = require('node:child_process')
const { mkdir, mkdtemp, rm, writeFile } = require('node:fs/promises')
const { tmpdir } = require('node:os')
const { join } = require('node:path')
const Docker = require('dockerode')
const yaml = require('yaml')
const DockerComposeToServiceOverride =
require('../built/utils/DockerComposeToServiceOverride').default
const Utils = require('../built/utils/Utils').default
const BASE_IMAGE = 'node:24-alpine'
const RUN_ID = `caprover-cmdtest-${Date.now().toString(36)}`
const ALLOW_EPHEMERAL_SWARM = process.argv.includes('--ephemeral-swarm')
const PROBE_SCRIPT = `#!/usr/bin/env node
console.log(JSON.stringify({ argv: process.argv.slice(2) }))
process.on('SIGTERM', () => process.exit(0))
process.on('SIGINT', () => process.exit(0))
setTimeout(() => process.exit(0), 60000)
`
const docker = new Docker()
const createdServices = new Set()
const createdImages = []
const dockerCli = (args) =>
execFileSync('docker', args, {
encoding: 'utf8',
stdio: ['ignore', 'pipe', 'pipe'],
timeout: 120000,
}).trim()
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
const serviceNameFor = (suffix) =>
`${RUN_ID}-${suffix}`.slice(0, 60).replace(/-+$/, '')
const escapeDollar = (val) => {
if (typeof val === 'string') return val.replace(/\$/g, () => '$$')
if (Array.isArray(val)) return val.map(escapeDollar)
if (val && typeof val === 'object') {
return Object.fromEntries(
Object.entries(val).map(([k, v]) => [k, escapeDollar(v)])
)
}
return val
}
async function buildProbeImage(rootDir, name, instructions) {
const tag = `${name}:${RUN_ID}`
const dir = join(rootDir, name)
await mkdir(dir, { recursive: true })
await writeFile(join(dir, 'probe.js'), PROBE_SCRIPT, { mode: 0o755 })
await writeFile(
join(dir, 'Dockerfile'),
[
`FROM ${BASE_IMAGE}`,
'COPY probe.js /usr/local/bin/probe',
'RUN chmod +x /usr/local/bin/probe',
...instructions,
'',
].join('\n')
)
dockerCli(['build', '-q', '-t', tag, dir])
createdImages.push(tag)
return tag
}
function inspectProbe(containerId, logs) {
const jsonLine = logs
.split(/\r?\n/)
.map((line) => line.trim())
.find((line) => line.startsWith('{'))
assert.ok(jsonLine, `Missing probe JSON in logs: ${JSON.stringify(logs)}`)
const inspected = JSON.parse(dockerCli(['inspect', containerId]))[0]
return {
path: inspected.Path,
args: inspected.Args,
argv: JSON.parse(jsonLine).argv,
}
}
async function runCompose(rootDir, name, service) {
const dir = join(rootDir, `compose-${name}`)
await mkdir(dir, { recursive: true })
const composeFile = join(dir, 'compose.yml')
const project = `${RUN_ID}-${name}`.replace(/[^a-z0-9_-]/g, '')
await writeFile(
composeFile,
yaml.stringify({
services: {
app: {
...escapeDollar(service),
environment: { TEST_VAR: 'from-container-env' },
},
},
})
)
const baseArgs = ['compose', '-f', composeFile, '-p', project]
try {
dockerCli([...baseArgs, 'up', '-d'])
const containerId = dockerCli([...baseArgs, 'ps', '-q', 'app'])
assert.ok(containerId, `No compose container started for ${name}`)
let logs = ''
for (let i = 0; i < 40; i++) {
logs = dockerCli(['logs', containerId])
if (logs.includes('"argv"')) break
await sleep(250)
}
return inspectProbe(containerId, logs)
} finally {
try {
dockerCli([
...baseArgs,
'down',
'-v',
'--remove-orphans',
'-t',
'1',
])
} catch {
// best effort
}
}
}
async function waitForSwarmTask(serviceName, envMarker) {
const deadline = Date.now() + 45000
let lastTask
while (Date.now() < deadline) {
const tasks = (
await docker.listTasks({ filters: { service: [serviceName] } })
)
.filter((t) =>
(t.Spec?.ContainerSpec?.Env || []).includes(envMarker)
)
.sort((a, b) => (b.Version?.Index || 0) - (a.Version?.Index || 0))
for (const task of tasks) {
lastTask = task
const state = task.Status?.State
const containerId = task.Status?.ContainerStatus?.ContainerID
if (containerId && (state === 'running' || state === 'complete')) {
const logs = dockerCli(['logs', containerId])
if (logs.includes('"argv"')) {
return inspectProbe(containerId, logs)
}
}
if (state === 'failed' || state === 'rejected') {
return {
failed: true,
error: task.Status?.Err || task.Status?.Message || state,
}
}
}
await sleep(300)
}
throw new Error(
`Timed out waiting for ${serviceName}; state=${lastTask?.Status?.State} err=${lastTask?.Status?.Err}`
)
}
async function removeService(name) {
try {
await docker.getService(name).remove()
createdServices.delete(name)
} catch (err) {
if (err?.statusCode === 404) createdServices.delete(name)
}
}
async function runSwarm(name, image, overrideYaml, verifyRedeploy = false) {
const env = ['TEST_VAR=from-container-env']
const override = Utils.convertYamlOrJsonToObject(overrideYaml)
await docker.createService(
Utils.mergeObjects(
{
Name: name,
TaskTemplate: {
ContainerSpec: { Image: image, Env: env },
RestartPolicy: { Condition: 'none' },
},
Mode: { Replicated: { Replicas: 1 } },
},
override
)
)
createdServices.add(name)
try {
const initial = await waitForSwarmTask(name, env[0])
if (!verifyRedeploy || initial.failed) return { initial }
const service = docker.getService(name)
const inspected = JSON.parse(JSON.stringify(await service.inspect()))
const updatedSpec = inspected.Spec
updatedSpec.version = parseInt(inspected.Version.Index, 10)
updatedSpec.TaskTemplate.ContainerSpec.Env = [...env, 'REDEPLOY_GEN=2']
updatedSpec.TaskTemplate.ForceUpdate =
(updatedSpec.TaskTemplate.ForceUpdate || 0) + 1
await service.update(Utils.mergeObjects(updatedSpec, override))
const redeployed = await waitForSwarmTask(name, 'REDEPLOY_GEN=2')
return { initial, redeployed }
} finally {
await removeService(name)
}
}
async function main() {
const swarmState = dockerCli([
'info',
'--format',
'{{.Swarm.LocalNodeState}}',
])
let initSwarm = false
if (swarmState !== 'active') {
if (!ALLOW_EPHEMERAL_SWARM) {
throw new Error(
`Swarm is "${swarmState}". Pass --ephemeral-swarm on an isolated runner.`
)
}
dockerCli(['swarm', 'init', '--advertise-addr', '127.0.0.1'])
initSwarm = true
}
const rootDir = await mkdtemp(join(tmpdir(), 'caprover-compose-cmd-'))
try {
const imgBoth = await buildProbeImage(rootDir, 'img-both', [
'ENTRYPOINT ["/usr/local/bin/probe", "IMG_EP"]',
'CMD ["IMG_CMD_1", "IMG_CMD_2"]',
])
const imgCmdOnly = await buildProbeImage(rootDir, 'img-cmd-only', [
'ENTRYPOINT []',
'CMD ["/usr/local/bin/probe", "IMG_CMD_ONLY"]',
])
const imgEpOnly = await buildProbeImage(rootDir, 'img-ep-only', [
'ENTRYPOINT ["/usr/local/bin/probe", "IMG_EP_ONLY"]',
])
const composeEquivalenceCases = [
[
'defaults-both',
{ image: imgBoth },
['IMG_EP', 'IMG_CMD_1', 'IMG_CMD_2'],
],
['defaults-cmd-only', { image: imgCmdOnly }, ['IMG_CMD_ONLY']],
['defaults-ep-only', { image: imgEpOnly }, ['IMG_EP_ONLY']],
[
'cmd-array-quoting',
{
image: imgBoth,
command: ['arg one', '', '$TEST_VAR', 'a && b'],
},
['IMG_EP', 'arg one', '', '$TEST_VAR', 'a && b'],
],
[
'cmd-string-quoting',
{
image: imgBoth,
command: "plain \"two words\" '' foo\\ bar '$TEST_VAR'",
},
['IMG_EP', 'plain', 'two words', '', 'foo bar', '$TEST_VAR'],
],
[
'ep-suppresses-img-cmd',
{
image: imgBoth,
entrypoint: ['/usr/local/bin/probe', 'NEW_EP'],
},
['NEW_EP'],
],
[
'ep-and-empty-cmd',
{
image: imgBoth,
entrypoint: ['/usr/local/bin/probe', 'NEW_EP'],
command: [],
},
['NEW_EP'],
],
[
'ep-and-cmd-shell',
{
image: imgBoth,
entrypoint: ['/bin/sh', '-ec'],
command: [
'exec /usr/local/bin/probe "hello $TEST_VAR" "" "a && b"',
],
},
['hello from-container-env', '', 'a && b'],
],
[
'clear-ep-with-cmd',
{
image: imgBoth,
entrypoint: [],
command: ['/usr/local/bin/probe', 'DIRECT_EXEC', 'arg2'],
},
['DIRECT_EXEC', 'arg2'],
],
]
for (const [name, service, expectedArgv] of composeEquivalenceCases) {
const composeRes = await runCompose(rootDir, name, service)
const overrideYaml =
DockerComposeToServiceOverride.convertUnconsumedComposeParametersToServiceOverride(
service,
'standard',
`services.${name}`
)
const { initial: swarmRes, redeployed } = await runSwarm(
serviceNameFor(name),
service.image,
overrideYaml,
name === 'ep-and-cmd-shell'
)
assert.ok(
!swarmRes.failed,
`Swarm failed for ${name}: ${swarmRes.error}`
)
assert.deepEqual(composeRes.argv, expectedArgv)
assert.deepEqual(swarmRes.argv, composeRes.argv)
assert.equal(swarmRes.path, composeRes.path)
assert.deepEqual(swarmRes.args, composeRes.args)
if (redeployed) {
assert.ok(
!redeployed.failed,
`Redeploy failed: ${redeployed.error}`
)
assert.deepEqual(redeployed.argv, expectedArgv)
}
console.log(`PASS [compose == swarm]: ${name}`)
}
// Representative legacy v4 runtime check: command replaces image ENTRYPOINT, entrypoint ignored.
const legacyOverride =
DockerComposeToServiceOverride.convertUnconsumedComposeParametersToServiceOverride(
{
image: imgBoth,
entrypoint: ['/bin/ignored'],
command: '/usr/local/bin/probe "LEGACY V4"',
},
'legacy',
'services.legacy'
)
const legacyRes = (
await runSwarm(serviceNameFor('legacy-v4'), imgBoth, legacyOverride)
).initial
assert.ok(!legacyRes.failed, `Legacy Swarm failed: ${legacyRes.error}`)
assert.deepEqual(legacyRes.argv, ['LEGACY V4'])
console.log('PASS [legacy v4 runtime]')
// Empirical Swarm limitation probes:
const emptyArgs = (
await runSwarm(
serviceNameFor('probe-empty-args'),
imgBoth,
yaml.stringify({
TaskTemplate: { ContainerSpec: { Args: [] } },
})
)
).initial
assert.deepEqual(emptyArgs.argv, ['IMG_EP', 'IMG_CMD_1', 'IMG_CMD_2'])
const emptyEp = (
await runSwarm(
serviceNameFor('probe-empty-ep'),
imgBoth,
yaml.stringify({
TaskTemplate: { ContainerSpec: { Command: [''] } },
})
)
).initial
assert.equal(emptyEp.failed, true)
assert.match(String(emptyEp.error), /no command specified/i)
console.log('PASS [Swarm empty-field limitation probes]')
} finally {
for (const svcName of Array.from(createdServices)) {
await removeService(svcName)
}
for (const tag of createdImages) {
try {
dockerCli(['rmi', '-f', tag])
} catch {
// best effort
}
}
if (initSwarm) {
try {
dockerCli(['swarm', 'leave', '--force'])
} catch {
// best effort
}
}
await rm(rootDir, { recursive: true, force: true })
}
}
main().catch((error) => {
console.error(error)
process.exitCode = 1
})