Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions packages/cli-ci/src/commands/plan.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down
10 changes: 1 addition & 9 deletions packages/cli-ci/src/core/plan.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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: [
Expand Down Expand Up @@ -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' }],
Expand Down
12 changes: 0 additions & 12 deletions packages/cli-ci/src/core/plan.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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[],
Expand Down
195 changes: 195 additions & 0 deletions packages/cli/src/commands/deploy.test.ts
Original file line number Diff line number Diff line change
@@ -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 <args>` with the environment given; what it wrote to stderr. */
async function plx(args: string[], env: Record<string, string> = {}): Promise<string> {
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/<owner>; 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<string>, 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 }));
82 changes: 70 additions & 12 deletions packages/cli/src/commands/deploy.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// plx deploy <host> <app>: launch a released artifact into an
// plx deploy [<host> <app>]: launch a released artifact into an
// execution environment (§ 6 PLX-Delivery), from a checkout of the app's
// source repo.
//
Expand All @@ -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/<owner of GITHUB_REPOSITORY>, 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 [email protected] website --image ghcr.io/org/website:<sha>
// plx deploy [email protected] beszel # third-party: image pinned in the file
// plx deploy [email protected] website -e staging --image … # the staging deployment, /opt/stacks/website-staging
// plx deploy [email protected] website --image … --display-version 1.4 --commit-sha <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';

Expand All @@ -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('<host>', 'ssh target, deploy@host')
.argument('<app>', 'the app, apps/<app> in the checkout')
.argument('[host]', 'ssh target, deploy@host; with no host and app, every app of the checkout')
.argument('[app]', 'the app, apps/<app> in the checkout')
.option('--image <ref>', 'the image ref to pin; absent for a third-party app whose compose.yaml pins its own')
.option(
'--display-version <string>',
Expand All @@ -48,16 +74,53 @@ export function register(program: Command): void {
.option('--retries <n>', 'looks at the app container’s health status, two seconds apart', '30')
.option(
'-e, --environment <name>',
'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 <path>',
'the app dir on the host (default: /opt/stacks/<app>, or <app>-<environment> outside production)',
)
.option('--source <path>', 'the app’s dir in the checkout (default: apps/<app>)')
.option('--inventory <dir>', 'with no host and app: the operations repo’s inventory, where each app’s target is')
.option(
'--commit <sha>',
'with no host and app: the commit whose images are deployed (default: the checkout’s HEAD)',
)
.option('-C, --dir <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,
Expand All @@ -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';
}
Loading
Loading