Files
baiyue-firstleg/scripts/deploy-built-service-rollback.test.mjs
T

203 lines
8.9 KiB
JavaScript
Raw Normal View History

2026-08-22 18:26:47 +08:00
import assert from 'node:assert/strict'
import { chmod, mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
import { existsSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { delimiter, join, resolve } from 'node:path'
import { spawnSync } from 'node:child_process'
import test from 'node:test'
const repositoryRoot = resolve(import.meta.dirname, '..')
const deployScript = resolve(repositoryRoot, 'deploy/scripts/deploy-built-service.sh')
const shell = process.platform === 'win32'
? 'C:/Program Files/Git/bin/bash.exe'
: '/bin/sh'
const mockDocker = `#!/usr/bin/env sh
set -eu
printf '%s\\n' "$*" >> "$MOCK_LOG"
command="$1"
shift
case "$command" in
login|logout|pull)
exit 0
;;
compose)
action=''
for argument in "$@"; do
case "$argument" in
ps|up) action="$argument" ;;
esac
done
case "$action" in
ps)
echo mock-container
;;
up)
service=''
for argument in "$@"; do service="$argument"; done
if [ "$IMAGE_TAG" = "\${MOCK_FAIL_UP_TAG:-never}" ]; then
exit 3
fi
printf '%s\\n' "$IMAGE_REPOSITORY/$service:$IMAGE_TAG" > "$MOCK_CURRENT_IMAGE"
if [ "$IMAGE_TAG" = "\${MOCK_FAIL_TAG:-never}" ]; then
printf '%s\\n' unhealthy > "$MOCK_HEALTH_STATE"
elif [ "$IMAGE_TAG" = "\${MOCK_RESTART_TAG:-never}" ]; then
printf '%s\\n' starting > "$MOCK_HEALTH_STATE"
printf '%s\\n' restarting > "$MOCK_RUNTIME_STATE"
2026-08-22 18:26:47 +08:00
else
2026-09-29 18:47:37 +08:00
printf '%s\\n' "\${MOCK_HEALTH_SUCCESS:-healthy}" > "$MOCK_HEALTH_STATE"
printf '%s\\n' running > "$MOCK_RUNTIME_STATE"
2026-08-22 18:26:47 +08:00
fi
;;
esac
;;
inspect)
case "$2" in
*Config.Image*) cat "$MOCK_CURRENT_IMAGE" ;;
*State.Health*) cat "$MOCK_HEALTH_STATE" ;;
*State.Status*) cat "$MOCK_RUNTIME_STATE" ;;
2026-08-22 18:26:47 +08:00
*) exit 2 ;;
esac
;;
logs)
echo 'mock startup failure'
;;
2026-08-22 18:26:47 +08:00
*)
echo "unexpected docker command: $command $*" >&2
exit 2
;;
esac
`
2026-09-29 18:47:37 +08:00
async function runDeployment({ imageTag, failingTag, failingStartTag, restartingTag, allowRollback = true, environment = 'test', service = 'audit-service', missingHealth = false }) {
2026-08-22 18:26:47 +08:00
const temporaryDirectory = await mkdtemp(join(tmpdir(), 'firstleg-rollback-'))
const mockBin = join(temporaryDirectory, 'bin')
const dockerPath = join(mockBin, 'docker')
const envFile = join(temporaryDirectory, 'deployment.env')
const logFile = join(temporaryDirectory, 'docker.log')
const currentImageFile = join(temporaryDirectory, 'current-image')
const healthStateFile = join(temporaryDirectory, 'health-state')
const runtimeStateFile = join(temporaryDirectory, 'runtime-state')
2026-08-22 18:26:47 +08:00
await mkdir(mockBin)
await writeFile(dockerPath, mockDocker, 'utf8')
await chmod(dockerPath, 0o755)
2026-09-29 18:47:37 +08:00
await writeFile(envFile, ['NACOS_SERVER_ADDR=nacos:8848','NACOS_NAMESPACE=test-id','NACOS_USERNAME=fixture','NACOS_PASSWORD=fixture','REDIS_HOST=redis','REDIS_PORT=6379','REDIS_DATABASE=0','REDIS_TOKEN_KEY_PREFIX=baiyue:auth','INTERNAL_SERVICE_TOKEN=fixture','JWT_RSA_JWK_SET=fixture','JWT_CURRENT_KID=fixture','ROCKETMQ_NAME_SERVER=namesrv:9876','MQ_TOPIC_PREFIX=test-','AUDIT_DB_URL=jdbc:mysql://mysql/audit','AUDIT_DB_USERNAME=fixture','AUDIT_DB_PASSWORD=fixture',''].join('\n'), 'utf8')
2026-08-22 18:26:47 +08:00
await writeFile(logFile, '', 'utf8')
await writeFile(currentImageFile, 'registry.local/group/firstleg/audit-service:oldgood\n', 'utf8')
await writeFile(healthStateFile, 'healthy\n', 'utf8')
await writeFile(runtimeStateFile, 'running\n', 'utf8')
2026-08-22 18:26:47 +08:00
const result = spawnSync(shell, [
deployScript.replaceAll('\\', '/'),
2026-09-29 18:47:37 +08:00
environment,
2026-08-22 18:26:47 +08:00
'registry.local/group/firstleg',
imageTag,
2026-09-29 18:47:37 +08:00
service,
2026-08-22 18:26:47 +08:00
envFile.replaceAll('\\', '/')
], {
cwd: repositoryRoot,
encoding: 'utf8',
env: {
...process.env,
PATH: `${mockBin}${delimiter}${process.env.PATH ?? ''}`,
TARGET_IS_LOCAL: 'true',
2026-09-29 18:47:37 +08:00
ALLOW_SAME_CONTRACT_ROLLBACK: String(allowRollback),
2026-08-22 18:26:47 +08:00
REGISTRY_USER: 'ci-user',
REGISTRY_PASSWORD: 'ci-password',
DEPLOY_HEALTH_TIMEOUT_SECONDS: '2',
DEPLOY_HEALTH_POLL_SECONDS: '1',
2026-09-29 18:47:37 +08:00
MOCK_HEALTH_SUCCESS: missingHealth ? 'no-health:running' : 'healthy',
2026-08-22 18:26:47 +08:00
MOCK_LOG: logFile,
MOCK_CURRENT_IMAGE: currentImageFile,
MOCK_HEALTH_STATE: healthStateFile,
MOCK_FAIL_TAG: failingTag ?? 'never',
MOCK_FAIL_UP_TAG: failingStartTag ?? 'never',
MOCK_RESTART_TAG: restartingTag ?? 'never',
MOCK_RUNTIME_STATE: runtimeStateFile
2026-08-22 18:26:47 +08:00
}
})
const dockerLog = await readFile(logFile, 'utf8')
const currentImage = (await readFile(currentImageFile, 'utf8')).trim()
await rm(temporaryDirectory, { recursive: true, force: true })
return { ...result, dockerLog, currentImage }
}
test('successful deployment keeps the new healthy image', async (context) => {
if (!existsSync(shell)) context.skip(`shell unavailable: ${shell}`)
const result = await runDeployment({ imageTag: 'newgood' })
assert.equal(result.status, 0, result.stderr)
assert.match(result.stdout, /部署前运行镜像: registry\.local\/group\/firstleg\/audit-service:oldgood/)
assert.match(result.stdout, /新镜像健康检查通过: registry\.local\/group\/firstleg\/audit-service:newgood/)
assert.equal(result.currentImage, 'registry.local/group/firstleg/audit-service:newgood')
})
test('unhealthy deployment restores the previous healthy image and still fails the job', async (context) => {
if (!existsSync(shell)) context.skip(`shell unavailable: ${shell}`)
const result = await runDeployment({ imageTag: 'newbad', failingTag: 'newbad' })
const output = `${result.stdout}\n${result.stderr}`
assert.equal(result.status, 1, output)
assert.match(output, /新镜像健康检查失败: registry\.local\/group\/firstleg\/audit-service:newbad/)
assert.match(output, /新镜像容器最近日志(最多 200 行):/)
assert.match(output, /mock startup failure/)
assert.match(result.dockerLog, /logs --tail 200 mock-container/)
2026-08-22 18:26:47 +08:00
assert.match(output, /开始自动回滚到: registry\.local\/group\/firstleg\/audit-service:oldgood/)
assert.match(output, /自动回滚成功: registry\.local\/group\/firstleg\/audit-service:oldgood/)
assert.match(result.dockerLog, /pull registry\.local\/group\/firstleg\/audit-service:oldgood/)
assert.equal(result.currentImage, 'registry.local/group/firstleg/audit-service:oldgood')
})
test('failed compose start also restores the previous healthy image', async (context) => {
if (!existsSync(shell)) context.skip(`shell unavailable: ${shell}`)
const result = await runDeployment({ imageTag: 'newbroken', failingStartTag: 'newbroken' })
const output = `${result.stdout}\n${result.stderr}`
assert.equal(result.status, 1, output)
assert.match(output, /新镜像启动命令失败: registry\.local\/group\/firstleg\/audit-service:newbroken/)
assert.match(output, /自动回滚成功: registry\.local\/group\/firstleg\/audit-service:oldgood/)
assert.equal(result.currentImage, 'registry.local/group/firstleg/audit-service:oldgood')
})
test('restart loops fail fast and restore the previous image', async (context) => {
if (!existsSync(shell)) context.skip(`shell unavailable: ${shell}`)
const result = await runDeployment({ imageTag: 'restarting', restartingTag: 'restarting' })
const output = `${result.stdout}\n${result.stderr}`
assert.equal(result.status, 1, output)
assert.match(output, /容器未保持运行,立即停止等待: restarting/)
assert.match(output, /自动回滚成功: registry\.local\/group\/firstleg\/audit-service:oldgood/)
assert.equal(result.currentImage, 'registry.local/group/firstleg/audit-service:oldgood')
})
2026-09-29 18:47:37 +08:00
test('architecture switch failure does not roll back one old service', async () => {
const result = await runDeployment({imageTag:'newbad', failingTag:'newbad', allowRollback:false})
assert.equal(result.status,1)
assert.doesNotMatch(result.dockerLog,/pull .*:oldgood/)
assert.match(result.stderr,/Automatic rollback disabled/)
})
test('non TEST environments and retired services fail before Docker', async () => {
for(const options of [{environment:'production'},{environment:'development'},{service:'event-bridge-service'},{service:'gateway-overseas'}]){
const result=await runDeployment({imageTag:'newgood',...options})
assert.equal(result.status,2)
assert.equal(result.dockerLog,'')
}
})
test('running without HEALTHCHECK cannot be counted as deployed',async()=>{
const result=await runDeployment({imageTag:'newgood',missingHealth:true,allowRollback:false})
assert.equal(result.status,1)
assert.match(result.stderr,/Missing HEALTHCHECK/)
})
test('SQL initializer rejects absent authorization before any Docker call',()=>{
const result=spawnSync(shell,[resolve(repositoryRoot,'deploy/scripts/initialize-test-databases.sh').replaceAll('\\','/')],{encoding:'utf8',env:{...process.env,ALLOW_TEST_SCHEMA_INITIALIZATION:'false'}})
assert.equal(result.status,2)
assert.match(result.stderr,/Explicit TEST SQL authorization required/)
})