diff --git a/packages/cli-ci/src/commands/plan.ts b/packages/cli-ci/src/commands/plan.ts index 86f7384e..a6102802 100644 --- a/packages/cli-ci/src/commands/plan.ts +++ b/packages/cli-ci/src/commands/plan.ts @@ -22,9 +22,9 @@ // plx-ci plan --deploy --inventory operations/inventory import { appendFileSync } from 'node:fs'; import { resolve } from 'node:path'; -import { readDeployTargets, targetsIn } from '@plexus-ms/lib'; +import { environmentOf, readDeployTargets, targetsIn } from '@plexus-ms/lib'; import type { Command } from 'commander'; -import { appsOf, environmentOf, outputsOf, plan, readHashes } from '../core/plan.ts'; +import { appsOf, outputsOf, plan, readHashes } from '../core/plan.ts'; import { contextOf } from '../program.ts'; import { imagePrefix, need, settings, withStrategy } from './shared.ts'; diff --git a/packages/cli-ci/src/core/plan.test.ts b/packages/cli-ci/src/core/plan.test.ts index b3a64a3c..1a2414e5 100644 --- a/packages/cli-ci/src/core/plan.test.ts +++ b/packages/cli-ci/src/core/plan.test.ts @@ -4,7 +4,7 @@ import { test } from 'node:test'; import { Context } from '@plexus-ms/lib'; import { REPO } from '../testing/checkout.ts'; import { fakeIo, notThere, type Tree } from '../testing/fakeIo.ts'; -import { appsOf, deployLegsOf, environmentOf, hashesOf, imageContextOf, legsOf, plan, readHashes } from './plan.ts'; +import { appsOf, deployLegsOf, hashesOf, imageContextOf, legsOf, plan, readHashes } from './plan.ts'; const dryRun = JSON.stringify({ tasks: [ @@ -104,14 +104,6 @@ test('a leg names the runner of its e2e job from the strategy: the forge’s, a assert.throws(() => legsOf(['nope'], hashes, 'hybrid', run), /no build hash for nope/); }); -test('the environment follows the branch on a push or a run by hand, and a given one stands in', () => { - assert.equal(environmentOf('push', 'main'), 'production'); - assert.equal(environmentOf('workflow_dispatch', 'develop'), 'staging'); - assert.equal(environmentOf('push', 'feature'), ''); - assert.equal(environmentOf('pull_request', 'main'), ''); - assert.equal(environmentOf('pull_request', '12/merge', 'staging'), 'staging'); -}); - test('deployLegsOf: an app with a target deploys the commit’s image there, one without is named', () => { assert.deepEqual(deployLegsOf(['website', 'my-app'], { website: 'ssh://plexus@host-a' }, 'ghcr.io/Acme', 'abc'), { legs: [{ app: 'website', host: 'ssh://plexus@host-a', image: 'ghcr.io/acme/website:abc' }], diff --git a/packages/cli-ci/src/core/plan.ts b/packages/cli-ci/src/core/plan.ts index 815e3309..c236003c 100644 --- a/packages/cli-ci/src/core/plan.ts +++ b/packages/cli-ci/src/core/plan.ts @@ -308,18 +308,6 @@ export function legsOf( }); } -/** - * The environment a run deploys into (§ 3 PLX-Delivery): `given` when the - * caller stands in for an environment branch, else main is production and - * develop is staging, on a push or a run by hand; anything else, a pull - * request among it, deploys nowhere. - */ -export function environmentOf(event: string, ref: string, given = ''): string { - if (given) return given; - if (event !== 'push' && event !== 'workflow_dispatch') return ''; - return ref === 'main' ? 'production' : ref === 'develop' ? 'staging' : ''; -} - /** The deploy legs: one per planned app with a target in the environment; the rest have no deployment there. */ export function deployLegsOf( apps: string[], diff --git a/packages/cli/src/commands/deploy.test.ts b/packages/cli/src/commands/deploy.test.ts new file mode 100644 index 00000000..a760cb3b --- /dev/null +++ b/packages/cli/src/commands/deploy.test.ts @@ -0,0 +1,195 @@ +import assert from 'node:assert/strict'; +import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { afterEach, test } from 'node:test'; +import { UsageError } from '@plexus-ms/lib'; +import { buildProgram } from '../program.ts'; + +const SHA = 'c0ffee0123456789abcdef0123456789abcdef01'; +const COMPOSE = [ + 'services:', + ' web:', + ' image: ${PLEXUS_DEPLOYMENT_IMAGE:?set}', + ' healthcheck:', + ' test: [CMD, "true"]', + ' start_period: 60s', + ' start_interval: 1s', + '', +].join('\n'); +const record = (target: string | undefined, ...apps: string[]) => + `${target ? `plexus_deploy_target: ${target}\n` : ''}plexus_apps:\n${apps.map((a) => ` - name: ${a}\n environment: staging\n`).join('')}`; + +const scratch = realpathSync(mkdtempSync(join(tmpdir(), 'plx-deploy-cmd-'))); +afterEach(() => { + process.exitCode = undefined; +}); + +/** A checkout with the apps api, docs and web, and an inventory: web and api have a record, docs none, api no target. */ +function fixture(): string { + const root = mkdtempSync(join(scratch, 'case-')); + for (const app of ['api', 'docs', 'web']) { + mkdirSync(join(root, 'repo/apps', app, 'docker'), { recursive: true }); + writeFileSync(join(root, 'repo/apps', app, 'docker/compose.yaml'), COMPOSE); + } + mkdirSync(join(root, 'inv/host_vars'), { recursive: true }); + writeFileSync(join(root, 'inv/host_vars/a.yml'), record('ssh://deploy@a', 'web')); + writeFileSync(join(root, 'inv/host_vars/b.yml'), record(undefined, 'api')); + return root; +} + +/** What the last `plx` wrote, whether it ended or threw. */ +const wrote = { out: '', err: '' }; + +/** Run `plx ` with the environment given; what it wrote to stderr. */ +async function plx(args: string[], env: Record = {}): Promise { + wrote.out = ''; + wrote.err = ''; + const { write: writeOut } = process.stdout; + const { write: writeErr } = process.stderr; + const saved = { ...process.env }; + // The runner reports through stdout, so what is written there is kept and passed on. + process.stdout.write = ((chunk: string | Uint8Array, ...rest: never[]) => { + wrote.out += chunk; + return writeOut.call(process.stdout, chunk, ...rest); + }) as typeof process.stdout.write; + process.stderr.write = ((chunk: string | Uint8Array) => { + wrote.err += chunk; + return true; + }) as typeof process.stderr.write; + for (const name of ['IMAGE_PREFIX', 'GITHUB_REPOSITORY', 'GITHUB_EVENT_NAME', 'GITHUB_REF_NAME']) + delete process.env[name]; + Object.assign(process.env, { IMAGE_PREFIX: 'ghcr.io/acme', ...env }); + try { + await buildProgram().parseAsync(args, { from: 'user' }); + } finally { + process.stdout.write = writeOut; + process.stderr.write = writeErr; + for (const name of Object.keys(process.env)) if (!(name in saved)) delete process.env[name]; + Object.assign(process.env, saved); + } + return wrote.err; +} + +test('plx deploy --environment deploys every app of the checkout that has a record, the commit’s image, one block each', async () => { + const root = fixture(); + const err = await plx([ + '-n', + 'deploy', + '--environment', + 'staging', + '--inventory', + join(root, 'inv'), + '--commit', + SHA, + '-C', + join(root, 'repo'), + ]); + assert.match(err, /^── web → ssh:\/\/deploy@a ──$/m); + assert.match(err, new RegExp(`→ deploying ghcr.io/acme/web:${SHA}`)); + assert.match(err, /^docs has no record in staging; nothing to deploy$/m); + const last = err.trim().split('\n').slice(-2); + assert.match(last[0] ?? '', /^✗ api has a record in staging in .*b\.yml, which names no plexus_deploy_target$/); + assert.equal(last[1], `✓ web: ghcr.io/acme/web:${SHA}`); + assert.equal(process.exitCode, 1, 'one app failed'); +}); + +test('without --environment the environment follows the branch; where it follows none, the verb says so', async () => { + const root = fixture(); + const args = ['-n', 'deploy', '--inventory', join(root, 'inv'), '--commit', SHA, '-C', join(root, 'repo')]; + const err = await plx(args, { GITHUB_EVENT_NAME: 'push', GITHUB_REF_NAME: 'develop' }); + assert.match(err, /→ deploying ghcr.io\/acme\/web:/); + assert.match(err, /dir: {5}\/opt\/stacks\/web-staging$/m); + await assert.rejects(plx(args, { GITHUB_EVENT_NAME: 'pull_request', GITHUB_REF_NAME: '3/merge' }), UsageError); +}); + +test('the image prefix is IMAGE_PREFIX, else ghcr.io/; with neither the verb says so', async () => { + const root = fixture(); + const args = [ + '-n', + 'deploy', + '-e', + 'staging', + '--inventory', + join(root, 'inv'), + '--commit', + SHA, + '-C', + join(root, 'repo'), + ]; + assert.match(await plx(args, { IMAGE_PREFIX: '', GITHUB_REPOSITORY: 'Acme/shop' }), /deploying ghcr.io\/acme\/web:/); + await assert.rejects(plx(args, { IMAGE_PREFIX: '' }), UsageError); +}); + +/** The arguments of a repo-form run in the fixture, with more. */ +const everyApp = (root: string, ...more: string[]) => [ + '-n', + 'deploy', + '-e', + 'staging', + '--inventory', + join(root, 'inv'), + '-C', + join(root, 'repo'), + ...more, +]; +const refuses = (run: Promise, message: RegExp) => + assert.rejects(run, (e: unknown) => e instanceof UsageError && message.test(e.message)); + +test('a host without an app is a usage error that says both or neither, where the app exists', async () => { + const root = fixture(); + await refuses( + plx(['-n', 'deploy', 'deploy@h', '-e', 'staging', '--inventory', join(root, 'inv'), '-C', join(root, 'repo')]), + /both the host and the app, or neither/, + ); +}); + +test('every app needs an inventory', async () => { + const root = fixture(); + await refuses(plx(['-n', 'deploy', '-e', 'staging', '-C', join(root, 'repo')]), /needs --inventory/); +}); + +test('a flag of the one-app form given to the repo form is refused by the name it was typed with; an empty value is absent', async () => { + const root = fixture(); + for (const flag of ['--image', '--display-version', '--commit-sha', '--app-dir', '--source']) { + await refuses(plx(everyApp(root, flag, 'x')), new RegExp(`takes no ${flag}\\b`)); + assert.equal(wrote.err, '', 'nothing was deployed'); + } + await plx(everyApp(root, '--image', '', '--commit', SHA)); + assert.match(wrote.err, /^── web → /m); +}); + +test('a --commit that is not a full hash is one usage error naming it, before any app is deployed', async () => { + const root = fixture(); + await refuses(plx(everyApp(root, '--commit', 'abc1234')), /--commit.*full/); + assert.equal(wrote.err, ''); + await plx(everyApp(root, '--commit', SHA)); + assert.match(wrote.err, /^── web → /m); +}); + +test('--inventory and --commit belong to the form for a whole repo, and the form for one app refuses them', async () => { + const root = fixture(); + const one = ['-n', 'deploy', 'deploy@h', 'web', '--image', 'ghcr.io/acme/web:x', '-C', join(root, 'repo')]; + await refuses(plx([...one, '--inventory', join(root, 'inv')]), /--inventory.*whole repo/); + await refuses(plx([...one, '--commit', SHA]), /--commit.*whole repo/); + assert.equal(wrote.err, ''); +}); + +test('in the human mode the repo form prints no result on stdout, and with --json the result', async () => { + const root = fixture(); + await plx(everyApp(root, '--commit', SHA)); + assert.doesNotMatch(wrote.out, /"ok":/); + await plx(['--json', ...everyApp(root, '--commit', SHA)]); + assert.match(wrote.out, /"ok": true/); +}); + +test('the form for one app, host and app and image, behaves as before', async () => { + const root = fixture(); + const err = await plx(['-n', 'deploy', 'deploy@h', 'web', '--image', 'ghcr.io/acme/web:x', '-C', join(root, 'repo')]); + assert.match(err, /→ deploying ghcr.io\/acme\/web:x/); + assert.match(err, /dir: {5}\/opt\/stacks\/web$/m); + assert.doesNotMatch(err, /^── /m); + assert.equal(process.exitCode, undefined); +}); + +test.after(() => rmSync(scratch, { recursive: true, force: true })); diff --git a/packages/cli/src/commands/deploy.ts b/packages/cli/src/commands/deploy.ts index 38edaae0..126fc247 100644 --- a/packages/cli/src/commands/deploy.ts +++ b/packages/cli/src/commands/deploy.ts @@ -1,4 +1,4 @@ -// plx deploy : launch a released artifact into an +// plx deploy [ ]: launch a released artifact into an // execution environment (§ 6 PLX-Delivery), from a checkout of the app's // source repo. // @@ -7,13 +7,22 @@ // or not. An empty option value is the same as an absent one, so a mount can // always pass the flag. `-n` prints every ssh line the deploy would run. // +// With neither host nor app, every app of the checkout that has a record in +// the environment is deployed at once (lib's `deployEnvironment`, whose header +// says how): the environment is --environment, else follows from the branch of +// the forge's run (GITHUB_EVENT_NAME, GITHUB_REF_NAME), the images live at +// IMAGE_PREFIX, else ghcr.io/, and the commit is +// --commit, else the checkout's HEAD. Exit code 1 when any app failed. +// +// plx deploy --environment staging --inventory ../operations/inventory +// plx deploy --inventory ../operations/inventory # on a push to main or develop in a job of the forge // plx deploy deploy@1.2.3.4 website --image ghcr.io/org/website: // plx deploy deploy@1.2.3.4 beszel # third-party: image pinned in the file // plx deploy deploy@1.2.3.4 website -e staging --image … # the staging deployment, /opt/stacks/website-staging // plx deploy deploy@1.2.3.4 website --image … --display-version 1.4 --commit-sha // # the app shows them, where its file uses ${PLEXUS_DISPLAY_VERSION} and ${PLEXUS_COMMIT_SHA} import { resolve } from 'node:path'; -import { type Deploy, deploy } from '@plexus-ms/lib'; +import { deploy, deployEnvironment, describeDeploy, environmentOf, imagePrefix, UsageError } from '@plexus-ms/lib'; import type { Command } from 'commander'; import { contextOf } from '../program.ts'; @@ -25,17 +34,34 @@ interface Opts { environment?: string; appDir?: string; source?: string; + inventory?: string; + commit?: string; dir: string; } +/** The options of the form for one app only, by the key of the option and as typed. */ +const ONE_APP_FLAGS: [keyof Opts, string][] = [ + ['image', '--image'], + ['displayVersion', '--display-version'], + ['commitSha', '--commit-sha'], + ['appDir', '--app-dir'], + ['source', '--source'], +]; + +/** The options of the form for a whole repo only. */ +const REPO_FLAGS: [keyof Opts, string][] = [ + ['inventory', '--inventory'], + ['commit', '--commit'], +]; + export function register(program: Command): void { program .command('deploy') .description( 'render the app’s compose file with the image pinned, stage it on the host, pull, migrate, swap, up, wait for the healthcheck, roll back on failure', ) - .argument('', 'ssh target, deploy@host') - .argument('', 'the app, apps/ in the checkout') + .argument('[host]', 'ssh target, deploy@host; with no host and app, every app of the checkout') + .argument('[app]', 'the app, apps/ in the checkout') .option('--image ', 'the image ref to pin; absent for a third-party app whose compose.yaml pins its own') .option( '--display-version ', @@ -48,16 +74,53 @@ export function register(program: Command): void { .option('--retries ', 'looks at the app container’s health status, two seconds apart', '30') .option( '-e, --environment ', - 'the environment deployed into; decides the app dir’s slug (default: production)', + 'the environment deployed into; decides the app dir’s slug (default: production; for every app, from the branch)', ) .option( '--app-dir ', 'the app dir on the host (default: /opt/stacks/, or - outside production)', ) .option('--source ', 'the app’s dir in the checkout (default: apps/)') + .option('--inventory ', 'with no host and app: the operations repo’s inventory, where each app’s target is') + .option( + '--commit ', + 'with no host and app: the commit whose images are deployed (default: the checkout’s HEAD)', + ) .option('-C, --dir ', 'the checkout to read', '.') - .action(async (host: string, app: string, opts: Opts, command: Command) => { + .action(async (host: string | undefined, app: string | undefined, opts: Opts, command: Command) => { const ctx = contextOf(command); + if (host === undefined && app === undefined) { + // An empty value is an absent one, so a mount can always pass the flag. + const stray = ONE_APP_FLAGS.filter(([key]) => opts[key]); + if (stray.length > 0) + throw new UsageError( + `deploying every app takes no ${stray.map(([, flag]) => flag).join(', ')}: each app’s image follows from the commit`, + ); + if (!opts.inventory) throw new UsageError('deploying every app needs --inventory, the operations repo’s'); + if (opts.commit && !/^[0-9a-f]{40}$/.test(opts.commit)) + throw new UsageError(`--commit ${opts.commit}: a full commit hash, 40 hex digits in lower case`); + const env = process.env; + const environment = environmentOf(env.GITHUB_EVENT_NAME ?? '', env.GITHUB_REF_NAME ?? '', opts.environment); + if (!environment) + throw new UsageError('no environment: pass --environment, or run on a push to main or develop'); + const result = await deployEnvironment(ctx, { + environment, + inventory: resolve(opts.inventory), + prefix: imagePrefix(env), + commit: opts.commit, + retries: Number(opts.retries), + dir: resolve(opts.dir), + }); + ctx.result(result, () => ''); + if (!result.ok) process.exitCode = 1; + return; + } + if (host === undefined || app === undefined) throw new UsageError('give both the host and the app, or neither'); + const misplaced = REPO_FLAGS.filter(([key]) => opts[key]).map(([, flag]) => flag); + if (misplaced.length > 0) + throw new UsageError( + `${misplaced.join(', ')} belongs to the form for a whole repo, which takes no host and app (--commit-sha is the commit the one app shows)`, + ); const result = await deploy(ctx, { host, app, @@ -70,12 +133,7 @@ export function register(program: Command): void { source: opts.source, dir: resolve(opts.dir), }); - ctx.result(result, renderDeploy); + ctx.result(result, describeDeploy); if (!result.healthy) process.exitCode = 1; }); } - -export function renderDeploy(d: Deploy): string { - if (d.healthy) return d.live ?? ''; - return d.rolledBack ? `rolled back to ${d.live ?? 'the previous compose.yaml'}` : 'not healthy'; -} diff --git a/packages/lib/src/deploy.test.ts b/packages/lib/src/deploy.test.ts index 44c8cc14..a1826082 100644 --- a/packages/lib/src/deploy.test.ts +++ b/packages/lib/src/deploy.test.ts @@ -6,6 +6,7 @@ import { Context, type Options } from './context.ts'; import { defaultAppDir, deploy, + deployEnvironment, q, renderCommitSha, renderCompose, @@ -730,3 +731,205 @@ test('the default app dir keys on the deployment slug: bare in production, suffi assert.equal(defaultAppDir('website', 'production'), '/opt/stacks/website'); assert.equal(defaultAppDir('website', 'staging'), '/opt/stacks/website-staging'); }); + +// The form for a whole repo: every app of the checkout with a record in the environment. + +const SHA = 'c0ffee0123456789abcdef0123456789abcdef01'; +const APP_COMPOSE = (extra = '') => COMPOSE + extra + HEALTHCHECK; +const inventory = (files: Record): Tree => ({ inventory: { host_vars: files } }); +const record = (target: string | undefined, ...apps: string[]) => + `${target ? `plexus_deploy_target: ${target}\n` : ''}plexus_apps:\n${apps.map((a) => ` - name: ${a}\n environment: staging\n`).join('')}`; + +/** A repo with the apps api, docs and web, and an inventory: one host per app, docs with no record. */ +function fleetTree(files: Record, webExtra = ''): Tree { + return { + repo: { + apps: { + api: { docker: { 'compose.yaml': APP_COMPOSE() } }, + docs: { docker: { 'compose.yaml': APP_COMPOSE() } }, + web: { docker: { 'compose.yaml': APP_COMPOSE(webExtra) } }, + }, + }, + ops: inventory(files), + }; +} + +/** Several hosts, each answered by its own `Host`, told apart by the ssh destination; every command it was sent is kept. */ +function fleet(tree: Tree, hosts: Record, options: Options = {}) { + const sent: string[] = []; + const io = fakeIo(tree, (_cwd, args) => (args.includes('rev-parse') ? `${SHA}\n` : undefined), { + ssh: (_cwd, args, input) => { + if (args.includes('-O')) return ''; + const command = remoteOf(args); + const destination = args[args.indexOf('--') - 1] ?? ''; + sent.push(`${destination} ${command}`); + return hosts[destination]?.answer(command, input); + }, + }); + const stderr = new PassThrough(); + const chunks: string[] = []; + stderr.on('data', (c: Buffer) => chunks.push(String(c))); + io.stderr = stderr; + return { ctx: new Context(options, io), sent, chunks, err: () => chunks.join('') }; +} + +const REPO = { environment: 'staging', inventory: 'ops/inventory', prefix: 'ghcr.io/Acme', dir: '/repo', retries: 1 }; +const TWO = { + 'a.yml': record('ssh://deploy@a', 'web'), + 'b.yml': record('ssh://deploy@b', 'api'), +}; + +test('every app with a record deploys its commit’s image, in parallel, each output one block, and the last lines run in order', async () => { + const web = host('ghcr.io/acme/web:old'); + const api = host('ghcr.io/acme/api:old'); + const apiAnswer = api.answer.bind(api); + // The new api image never turns healthy; the old one does. + api.answer = (c, i) => (c.includes('.State.Health.Status') && api.live?.endsWith(SHA) ? undefined : apiAnswer(c, i)); + const { ctx, sent, err } = fleet(fleetTree(TWO), { 'ssh://deploy@a': web, 'ssh://deploy@b': api }); + const result = await deployEnvironment(ctx, { ...REPO, commit: SHA }); + + assert.match(web.staged ?? '', new RegExp(`image: ghcr.io/acme/web:${SHA}\\n`)); + assert.ok(sent.some((c) => c.startsWith('ssh://deploy@b ') && c.includes('/opt/stacks/api-staging'))); + assert.deepEqual( + result.apps.map(({ app, ok }) => [app, ok]), + [ + ['api', false], + ['web', true], + ], + ); + assert.equal(result.ok, false); + assert.equal(result.apps[0]?.deploy?.rolledBack, true); + + const lines = err().split('\n'); + // Each block starts at a line that names the app and its target, and holds that app's lines only. + const blocks = err() + .split(/^(?=── )/m) + .filter((b) => b.startsWith('── ')); + assert.equal(blocks.length, 2); + for (const [app, target] of [ + ['api', 'ssh://deploy@b'], + ['web', 'ssh://deploy@a'], + ] as const) { + const block = blocks.find((b) => b.startsWith(`── ${app} → ${target}`)); + assert.ok(block, `a block for ${app}`); + for (const dir of block.match(/dir: .*/g) ?? []) assert.match(dir, new RegExp(`/opt/stacks/${app}-staging$`)); + assert.match(block, /dir: /); + } + // The last lines: one per app, in the order of the names, whichever ended first. + assert.deepEqual(lines.filter(Boolean).slice(-2), [ + '✗ api: rolled back to ghcr.io/acme/api:old', + `✓ web: ghcr.io/acme/web:${SHA}`, + ]); + assert.match(err(), /docs has no record in staging; nothing to deploy/); +}); + +test('an app whose deploy throws fails alone: the others still deploy, and the error is its line', async () => { + const web = host('ghcr.io/acme/web:old'); + const api = host('ghcr.io/acme/api:old'); + const apiAnswer = api.answer.bind(api); + api.answer = (c, i) => (c.endsWith(' pull') ? undefined : apiAnswer(c, i)); + const { ctx, err } = fleet(fleetTree(TWO), { 'ssh://deploy@a': web, 'ssh://deploy@b': api }); + const result = await deployEnvironment(ctx, { ...REPO, commit: SHA }); + assert.deepEqual( + result.apps.map(({ app, ok }) => [app, ok]), + [ + ['api', false], + ['web', true], + ], + ); + assert.equal(result.apps[1]?.deploy?.live, `ghcr.io/acme/web:${SHA}`); + assert.match(err(), /^✗ api: .*fake ssh fails/m); +}); + +test('an app with a record whose file names no target fails, naming the app and the file; an app with no record is no failure', async () => { + const files = { 'a.yml': record('ssh://deploy@a', 'web'), 'b.yml': record(undefined, 'api') }; + const { ctx, err } = fleet(fleetTree(files), { 'ssh://deploy@a': host('ghcr.io/acme/web:old') }); + const result = await deployEnvironment(ctx, { ...REPO, commit: SHA }); + assert.deepEqual(result.without, ['docs']); + assert.deepEqual( + result.apps.map(({ app, ok }) => [app, ok]), + [ + ['api', false], + ['web', true], + ], + ); + assert.match( + err(), + /^✗ api has a record in staging in ops\/inventory\/host_vars\/b\.yml, which names no plexus_deploy_target$/m, + ); + assert.match(err(), /^docs has no record in staging; nothing to deploy$/m); + // Nothing without a failure: only the app without a record. + const clean = fleet(fleetTree({ 'a.yml': record('ssh://deploy@a', 'web', 'api') }), { + 'ssh://deploy@a': host('ghcr.io/acme/web:old'), + }); + assert.equal((await deployEnvironment(clean.ctx, { ...REPO, commit: SHA })).without.join(), 'docs'); +}); + +test('the commit is the checkout’s HEAD unless given, and the app is handed it where its file uses it', async () => { + const files = { 'a.yml': record('ssh://deploy@a', 'web') }; + const web = host('ghcr.io/acme/web:old'); + const extra = ' environment:\n PLEXUS_COMMIT_SHA: ${PLEXUS_COMMIT_SHA:-}\n'; + const { ctx } = fleet(fleetTree(files, extra), { 'ssh://deploy@a': web }); + const result = await deployEnvironment(ctx, REPO); + assert.equal(result.commit, SHA); + assert.match(web.staged ?? '', new RegExp(`image: ghcr.io/acme/web:${SHA}`)); + assert.match(web.staged ?? '', new RegExp(`PLEXUS_COMMIT_SHA: "${SHA}"`)); +}); + +test('a dry run reaches no host and prints each app’s lines in its own block', async () => { + const { ctx, sent, err } = fleet(fleetTree(TWO), {}, { dryRun: true }); + const result = await deployEnvironment(ctx, { ...REPO, commit: SHA }); + assert.deepEqual(sent, []); + assert.equal(result.ok, true); + const blocks = err() + .split(/^(?=── )/m) + .filter((b) => b.startsWith('── ')); + assert.equal(blocks.length, 2); + for (const block of blocks) + assert.match(block, /\[dry-run\] \$ ssh .* -- 'cd .*docker compose up -d --remove-orphans'/); +}); + +test('a checkout without apps/ is a usage error', async () => { + const { ctx } = fleet({ repo: {}, ops: inventory(TWO) }, {}); + await assert.rejects(deployEnvironment(ctx, REPO), UsageError); +}); + +test('inside a block -vv is held at -v: no subprocess output goes to the terminal or is echoed', async () => { + const { ctx } = fleet( + fleetTree(TWO), + { 'ssh://deploy@a': host('ghcr.io/acme/web:old'), 'ssh://deploy@b': host('ghcr.io/acme/api:old') }, + { verbose: 2 }, + ); + const exec = ctx.io.exec; + const options: { inherit?: boolean; echo?: boolean }[] = []; + ctx.io.exec = (command, args, o) => { + if (command === 'ssh') options.push({ inherit: o?.inherit, echo: o?.echo }); + return exec(command, args, o); + }; + await deployEnvironment(ctx, { ...REPO, commit: SHA }); + assert.ok(options.length > 0); + assert.deepEqual( + options.filter((o) => o.inherit || o.echo), + [], + ); +}); + +test('only the directories under apps/ are apps', async () => { + const tree = fleetTree({ 'a.yml': record('ssh://deploy@a', 'web') }); + (tree.repo as Tree).apps = { ...((tree.repo as Tree).apps as Tree), 'README.md': 'not an app' }; + const { ctx } = fleet(tree, { 'ssh://deploy@a': host('ghcr.io/acme/web:old') }); + const result = await deployEnvironment(ctx, { ...REPO, commit: SHA }); + assert.deepEqual(result.without, ['api', 'docs']); + assert.deepEqual( + result.apps.map((a) => a.app), + ['web'], + ); +}); + +test('the number of looks reaches each app’s deploy', async () => { + const { ctx, sent } = fleet(fleetTree({ 'a.yml': record('ssh://deploy@a', 'web') }), { + 'ssh://deploy@a': host('ghcr.io/acme/web:old'), + }); + await deployEnvironment(ctx, { ...REPO, commit: SHA, retries: 7 }); + assert.ok(sent.some((c) => c.includes('seq 1 7'))); +}); diff --git a/packages/lib/src/deploy.ts b/packages/lib/src/deploy.ts index 6239de27..20a4d736 100644 --- a/packages/lib/src/deploy.ts +++ b/packages/lib/src/deploy.ts @@ -47,12 +47,35 @@ // ones live keeps the file it serves, and with it the display version and the // commit sha it was last started with (PLX-Releases). // +// Two forms. One app, by hand or from the operations repo, as above: the host, +// the app and the image are given. A whole repo, in one environment, from the +// pipeline of an app repo (`deployEnvironment`): +// +// the environment: given, or from the branch (`environmentOf`) +// → the apps: the directories under apps/ of the checkout +// → each one's deploy target: the record of the app in that environment in +// the operations repo's inventory (deployTargets.ts); an app with no +// record is named in one line and is no failure; one whose record sits in +// a file without a target is a failure that names the app and the file +// → the commit: given, or the checkout's HEAD; each app's image is +// `/:` (PLX-App), the whole contract with `publish`: +// nothing else is passed in, and the app is handed the commit +// → every app deploys as above, all at once, each in a Context of its own: +// its narration is buffered and written as one block, under a line that +// names the app and its target, when its deploy ends; so no two apps' +// lines meet (-vv, whose subprocess output no buffer holds, is capped at -v) +// → the last lines, one per app in the order of the names: `✓` or `✗`, the +// app, and the image live or why not; the run fails if any app failed, +// and an app's failure, a throw among it, stops no other. +// // plx deploy deploy@1.2.3.4 website --image ghcr.io/org/website: // plx deploy deploy@1.2.3.4 website --environment staging --image … # into /opt/stacks/website-staging // plx -n deploy deploy@host beszel # the ssh lines it would run +// plx deploy --environment staging --inventory ../ops/inventory # every app of the checkout import { randomBytes } from 'node:crypto'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; +import { Writable } from 'node:stream'; import { parseDocument, visit } from 'yaml'; import { COMMIT_SHA_PLACEHOLDER, @@ -63,10 +86,19 @@ import { type Mapping, parseCompose, } from './compose.ts'; -import type { Context } from './context.ts'; -import { DEFAULT_ENVIRONMENT, deploymentSlug } from './deployTargets.ts'; +import { Context } from './context.ts'; +import { + DEFAULT_ENVIRONMENT, + deployLegs, + deploymentSlug, + readInventory, + recordsWithoutTarget, + selectDeployTargets, + targetsIn, + untargetedError, +} from './deployTargets.ts'; import { run } from './effects.ts'; -import { orAbsent } from './io.ts'; +import { detailOf, orAbsent } from './io.ts'; import { UsageError } from './version.ts'; export interface DeployOptions { @@ -648,3 +680,124 @@ async function rollback(s: Session, hadPrev: boolean | undefined, retries: numbe ctx.done('rollback also unhealthy; manual intervention needed', false); } } + +/** What a deploy ended as, in a few words: the image live, or that it was rolled back or is not healthy. */ +export function describeDeploy(d: Deploy): string { + if (d.healthy) return d.live ?? ''; + return d.rolledBack ? `rolled back to ${d.live ?? 'the previous compose.yaml'}` : 'not healthy'; +} + +/** The image the naming rule gives an app at a commit: `/:` (PLX-App). */ +export const imageRef = (prefix: string, app: string, commit: string): string => + `${prefix.toLowerCase().replace(/\/$/, '')}/${app}:${commit}`; + +/** Where the images live: IMAGE_PREFIX, else `ghcr.io/`. */ +export function imagePrefix(env: NodeJS.ProcessEnv = process.env): string { + if (env.IMAGE_PREFIX) return env.IMAGE_PREFIX; + const repo = env.GITHUB_REPOSITORY; + if (!repo) throw new UsageError('where the images live is not known: set IMAGE_PREFIX or GITHUB_REPOSITORY'); + return `ghcr.io/${repo.split('/')[0]}`; +} + +export interface EnvironmentOptions { + environment: string; + /** The operations repo's inventory directory, as the records are read from it. */ + inventory: string; + /** Where the images live, `/`. */ + prefix: string; + /** The commit whose images are deployed; default the checkout's HEAD. */ + commit?: string; + retries?: number; + /** The checkout; default the cwd. */ + dir?: string; +} + +/** How one app of the repo ended: the line it ends the run with, and its deploy where it got as far as one. */ +export interface AppOutcome { + app: string; + host?: string; + image?: string; + ok: boolean; + line: string; + deploy?: Deploy; +} + +export interface EnvironmentDeploy { + environment: string; + commit: string; + /** Every app with a record in the environment, in the order of the names. */ + apps: AppOutcome[]; + /** The apps of the repo with no record in the environment. */ + without: string[]; + ok: boolean; +} + +/** + * Deploy every app of the checkout that has a record in the environment, in + * parallel. Each app's deploy is `deploy` above with a Context of its own whose + * narration is buffered, written as one block when the app ends. Without + * -vv's inherited subprocess output, which no buffer holds, no two apps' + * lines meet. An app's failure, a throw included, is its own: it ends that + * app's block and line and no other. + */ +export async function deployEnvironment(ctx: Context, options: EnvironmentOptions): Promise { + const { environment, prefix } = options; + const dir = options.dir ?? '.'; + const files = await readInventory(ctx, options.inventory); + const entries = await ctx.readDir(join(dir, 'apps')).catch(() => { + throw new UsageError(`${dir} has no apps/: the apps of an app repo are the directories there`); + }); + const { legs, untargeted, without } = deployLegs( + targetsIn(selectDeployTargets(files), environment), + entries.filter((e) => e.directory).map((e) => e.name), + recordsWithoutTarget(files, environment), + ); + const commit = options.commit || (await ctx.read('git', ['-C', dir, 'rev-parse', 'HEAD'])).trim(); + for (const app of without) ctx.say(`${app} has no record in ${environment}; nothing to deploy`); + + const outcomes: AppOutcome[] = await Promise.all([ + ...legs.map(async ({ app, host }): Promise => { + const image = imageRef(prefix, app, commit); + let text = ''; + const buffer = new Writable({ + write(chunk, _encoding, done) { + text += chunk; + done(); + }, + }); + const own = new Context( + { dryRun: ctx.dryRun, verbose: Math.min(ctx.verbose, 1), quiet: ctx.quiet, yes: ctx.yes, json: ctx.json }, + { ...ctx.io, stderr: buffer }, + ); + let outcome: AppOutcome; + try { + const deployed = await deploy(own, { + host, + app, + image, + commitSha: commit, + retries: options.retries, + environment, + dir, + }); + outcome = { + app, + host, + image, + ok: deployed.healthy, + line: `${app}: ${describeDeploy(deployed)}`, + deploy: deployed, + }; + } catch (error) { + own.done(error instanceof Error ? error.message : String(error), false); + outcome = { app, host, image, ok: false, line: `${app}: ${detailOf(error)}` }; + } + ctx.io.stderr.write(`── ${app} → ${host} ──\n${text}`); + return outcome; + }), + ...untargeted.map((u): AppOutcome => ({ app: u.app, ok: false, line: untargetedError([u], environment).message })), + ]); + outcomes.sort((a, b) => a.app.localeCompare(b.app)); + for (const o of outcomes) ctx.done(o.line, o.ok); + return { environment, commit, apps: outcomes, without, ok: outcomes.every((o) => o.ok) }; +} diff --git a/packages/lib/src/deployTargets.test.ts b/packages/lib/src/deployTargets.test.ts index c97c824e..13ecfe0b 100644 --- a/packages/lib/src/deployTargets.test.ts +++ b/packages/lib/src/deployTargets.test.ts @@ -4,6 +4,7 @@ import { Context } from './context.ts'; import { deployLegs, deploymentSlug, + environmentOf, parseInventoryFile, readDeployTargets, readInventory, @@ -168,3 +169,11 @@ test('an app of the repo with a record and no target is neither a leg nor withou /^pocket-id has a record in production in \/inv\/host_vars\/vm103\.yml, which names no plexus_deploy_target$/, ); }); + +test('the environment follows the branch on a push or a run by hand, and a given one stands in', () => { + assert.equal(environmentOf('push', 'main'), 'production'); + assert.equal(environmentOf('workflow_dispatch', 'develop'), 'staging'); + assert.equal(environmentOf('push', 'feature'), ''); + assert.equal(environmentOf('pull_request', 'main'), ''); + assert.equal(environmentOf('pull_request', '12/merge', 'staging'), 'staging'); +}); diff --git a/packages/lib/src/deployTargets.ts b/packages/lib/src/deployTargets.ts index 1eb36978..61bdcc07 100644 --- a/packages/lib/src/deployTargets.ts +++ b/packages/lib/src/deployTargets.ts @@ -17,6 +17,9 @@ // the same app in the same environment declared in two files that both name // a target has no one place to deploy to, and that is an error, never a pick. // +// `environmentOf` is the one place that says which environment a branch deploys +// into, for `plx` and `plx-ci`. +// // plx deploy-targets [inventory] # {"app": {"production": "ssh://...", "staging": "ssh://..."}, ...} // plx deploy-targets --environment production [inventory] # {"app": "ssh://...", ...}, one environment, flat // plx deploy-targets --environment production --apps apps # [{"app": "...", "host": "ssh://..."}], the apps under apps/, for a matrix @@ -30,6 +33,19 @@ const VARS_DIRS = ['group_vars', 'host_vars']; /** The environment a record without one is in. */ export const DEFAULT_ENVIRONMENT = 'production'; +/** + * The environment a run deploys into (§ 3 PLX-Delivery): `given` when the + * caller stands in for an environment branch, else main is production and + * develop is staging, on a push or a run by hand; anything else, a pull + * request among it, deploys nowhere (the empty string). The one place the + * rule is written, for `plx` and `plx-ci`. + */ +export function environmentOf(event: string, ref: string, given = ''): string { + if (given) return given; + if (event !== 'push' && event !== 'workflow_dispatch') return ''; + return ref === 'main' ? DEFAULT_ENVIRONMENT : ref === 'develop' ? 'staging' : ''; +} + /** App name → environment → deploy target. */ export type DeployTargets = Record>; diff --git a/packages/lib/src/index.ts b/packages/lib/src/index.ts index 4293623c..c4335912 100644 --- a/packages/lib/src/index.ts +++ b/packages/lib/src/index.ts @@ -39,10 +39,17 @@ export { filesWithConflictMarkers, hasConflictMarkers, hasUnmergedEntries } from export { type Consumer, expectedBranch, findRepos } from './consumers.ts'; export { Context, type Options } from './context.ts'; export { + type AppOutcome, type Deploy, type DeployOptions, defaultAppDir, deploy, + deployEnvironment, + describeDeploy, + type EnvironmentDeploy, + type EnvironmentOptions, + imagePrefix, + imageRef, q as shellQuote, renderCommitSha, renderCompose, @@ -57,6 +64,7 @@ export { deployLegs, deploymentSlug, type EnvironmentTargets, + environmentOf, type InventoryFile, parseInventoryFile, readDeployTargets,