@basaltkit/deploy 0.4.1 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +276 -23
- package/dist/answers.d.ts +70 -0
- package/dist/answers.js +196 -0
- package/dist/apache.js +11 -2
- package/dist/audit.d.ts +20 -0
- package/dist/audit.js +26 -0
- package/dist/backup.d.ts +17 -1
- package/dist/backup.js +49 -1
- package/dist/bin.js +9 -1
- package/dist/bootstrap.d.ts +68 -18
- package/dist/bootstrap.js +177 -45
- package/dist/caddy.js +2 -1
- package/dist/check.js +18 -5
- package/dist/checks.js +1 -1
- package/dist/cli.d.ts +22 -1
- package/dist/cli.js +498 -57
- package/dist/compose.d.ts +1 -1
- package/dist/compose.js +6 -1
- package/dist/config.d.ts +25 -2
- package/dist/config.js +65 -3
- package/dist/context.d.ts +43 -13
- package/dist/context.js +50 -7
- package/dist/detach.d.ts +23 -0
- package/dist/detach.js +105 -0
- package/dist/env-step.d.ts +16 -1
- package/dist/env-step.js +58 -5
- package/dist/events.d.ts +168 -0
- package/dist/events.js +477 -0
- package/dist/host.d.ts +171 -7
- package/dist/host.js +302 -41
- package/dist/index.d.ts +10 -5
- package/dist/index.js +7 -3
- package/dist/init.d.ts +2 -0
- package/dist/init.js +2 -1
- package/dist/install-plan.d.ts +40 -0
- package/dist/install-plan.js +433 -0
- package/dist/json-host.d.ts +32 -0
- package/dist/json-host.js +106 -0
- package/dist/lock.d.ts +45 -0
- package/dist/lock.js +128 -0
- package/dist/pipeline.d.ts +51 -3
- package/dist/pipeline.js +339 -173
- package/dist/protocol.d.ts +364 -0
- package/dist/protocol.js +134 -0
- package/dist/runs.d.ts +75 -0
- package/dist/runs.js +287 -0
- package/dist/state.d.ts +26 -13
- package/dist/state.js +68 -4
- package/dist/trust.d.ts +63 -0
- package/dist/trust.js +159 -0
- package/dist/version.d.ts +2 -0
- package/dist/version.js +10 -0
- package/package.json +5 -1
package/dist/pipeline.js
CHANGED
|
@@ -1,19 +1,28 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import { backupDatabase, restoreCommand } from './backup.js';
|
|
1
|
+
import { apachePreflight } from './apache.js';
|
|
2
|
+
import { caddyPreflight } from './caddy.js';
|
|
3
|
+
import { backupDatabase, backupDir, backupPlaceFindings, restoreCommand } from './backup.js';
|
|
5
4
|
import { lockfileFindings, tlsFindings, toolingFindings } from './checks.js';
|
|
6
5
|
import { composeBuild, composeEnv, composeHealthy, composeOf, composePreflight, composeRelease, composeStatus, logFindings, pruneImages } from './compose.js';
|
|
7
|
-
import { definedEntries, processName } from './config.js';
|
|
8
|
-
import { DeployError, errors,
|
|
6
|
+
import { definedEntries, isBranchName, processName, REMOTE_NAME } from './config.js';
|
|
7
|
+
import { DeployAbortedError, DeployError, errors, report, throwIfAborted } from './context.js';
|
|
9
8
|
import { checkSchema, coercionFindings, policyFindings } from './env-check.js';
|
|
10
|
-
import { answerQuestions, describeEnv, envFile,
|
|
9
|
+
import { answerQuestions, describeEnv, envFile, envModeFindings, mirrorFindings, planEnv, readEnv, secureEnvModes, syntaxFindings, writeEnv } from './env-step.js';
|
|
11
10
|
import { envValues } from './dotenv.js';
|
|
12
11
|
import { applyInfra, describeInfra, dockerPostgres, maintainServices, planInfra } from './infra.js';
|
|
13
12
|
import { appRoleOf, describeServices, dumpContainer, dumpUrlKey, externalOf, externalPostgres, grantTenantSchemas } from './services.js';
|
|
14
13
|
import { pm2List, pm2Preflight, pm2Release, resolvePort } from './pm2.js';
|
|
15
|
-
import { lastGood, migrationNames, readReleases, recordRelease } from './state.js';
|
|
14
|
+
import { clearHold, deployedOver, lastGood, migrationNames, readHold, readReleases, recordRelease, writeHold } from './state.js';
|
|
15
|
+
import { acquireLock, describeHolder, readLock } from './lock.js';
|
|
16
|
+
import { auditOf } from './audit.js';
|
|
17
|
+
import { questionDescriptors } from './env-step.js';
|
|
18
|
+
import { activeRun, lastRun } from './runs.js';
|
|
16
19
|
export const SKIPPABLE = ['fetch', 'backup', 'tls'];
|
|
20
|
+
/** run, env and rollback are the app user's (RFC 0006 §11.4): never root unless asked. */
|
|
21
|
+
export function refuseRoot(host, command, allowRoot = false) {
|
|
22
|
+
if (host.uid() !== 0 || allowRoot)
|
|
23
|
+
return;
|
|
24
|
+
throw new DeployError(`${command} runs as the app user, not root: it builds and runs the app's code. Run it as that user (sudo -u <user> -H …), or pass --allow-root if this server really has no other`, [], 'refused-root');
|
|
25
|
+
}
|
|
17
26
|
/**
|
|
18
27
|
* Never a credential prompt: one in the middle of a deploy hangs cron and CI,
|
|
19
28
|
* and interrupts a person half-way. With nobody to answer, git fails instead.
|
|
@@ -25,9 +34,90 @@ async function git(ctx, args, options = {}) {
|
|
|
25
34
|
throw new DeployError(`git ${args[0]} failed: ${result.stderr.trim()}`);
|
|
26
35
|
return result.stdout.trim();
|
|
27
36
|
}
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
37
|
+
/**
|
|
38
|
+
* The remote and branch a deploy fetches, checked again here (a config built
|
|
39
|
+
* in code may skip validateConfig): each reaches git as an argument, and a
|
|
40
|
+
* name starting with `-` would be an option (`--upload-pack=<cmd>`). The
|
|
41
|
+
* fetch names both refs in full, after `--`.
|
|
42
|
+
*/
|
|
43
|
+
export function gitTarget(ctx) {
|
|
44
|
+
const remote = ctx.config.remote ?? 'origin';
|
|
45
|
+
const branch = ctx.config.branch ?? 'main';
|
|
46
|
+
if (!REMOTE_NAME.test(remote))
|
|
47
|
+
throw new DeployError(`remote "${remote}" is not a git remote name`);
|
|
48
|
+
if (!isBranchName(branch))
|
|
49
|
+
throw new DeployError(`branch "${branch}" is not a plain git branch name`);
|
|
50
|
+
return { remote, branch, head: `refs/heads/${branch}`, tracking: `refs/remotes/${remote}/${branch}` };
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* The fetch: both refs in full, after `--`, and forced (`+`) — like the
|
|
54
|
+
* remote's default refspec. A branch rewritten upstream (the usual fix after
|
|
55
|
+
* a rollback) must still reach the tracking ref; the `merge --ff-only` that
|
|
56
|
+
* follows is what refuses history rewritten under the checkout.
|
|
57
|
+
*/
|
|
58
|
+
export const fetchArgs = (target) => ['fetch', '--quiet', '--', target.remote, `+${target.head}:${target.tracking}`];
|
|
59
|
+
async function step(ctx, id, run, title = id) {
|
|
60
|
+
throwIfAborted(ctx);
|
|
61
|
+
return stepped(ctx, id, run, title);
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* A step as the operator sees it (its title) and as a program does: its id
|
|
65
|
+
* and, through an output that takes it, how and when it ended (RFC 0008 §5.1).
|
|
66
|
+
* Not a stop point: `restore` runs after a signal too.
|
|
67
|
+
*/
|
|
68
|
+
async function stepped(ctx, id, run, title = id) {
|
|
69
|
+
const { out } = ctx.host;
|
|
70
|
+
out.step(title, id);
|
|
71
|
+
if (!out.stepEnd)
|
|
72
|
+
return run();
|
|
73
|
+
const started = ctx.host.now().getTime();
|
|
74
|
+
let status = 'failed';
|
|
75
|
+
try {
|
|
76
|
+
const value = await run();
|
|
77
|
+
status = 'ok';
|
|
78
|
+
return value;
|
|
79
|
+
}
|
|
80
|
+
catch (error) {
|
|
81
|
+
if (error instanceof DeployAbortedError)
|
|
82
|
+
status = 'aborted';
|
|
83
|
+
throw error;
|
|
84
|
+
}
|
|
85
|
+
finally {
|
|
86
|
+
out.stepEnd(id, status, ctx.host.now().getTime() - started);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* The deploy lock around a command that changes the server, and its signal
|
|
91
|
+
* handling: the first SIGINT/SIGTERM/SIGHUP stops an `abortable` command at
|
|
92
|
+
* the next step boundary (the command puts back what it changed); one that
|
|
93
|
+
* is not finishes first. The lock is released in every case.
|
|
94
|
+
*/
|
|
95
|
+
async function locked(ctx, command, options, abortable, body) {
|
|
96
|
+
refuseRoot(ctx.host, command, options.allowRoot);
|
|
97
|
+
const audit = auditOf(ctx.host, options.actor, options.via);
|
|
98
|
+
await options.protocol?.beforeLock?.();
|
|
99
|
+
const take = () => acquireLock(ctx.host, ctx.stateDir, command, audit.actor, options.protocol?.runId);
|
|
100
|
+
// A program sees the wait for the lock as a step; the terminal's text is unchanged.
|
|
101
|
+
const release = ctx.host.out.stepEnd ? await stepped(ctx, 'lock', take) : await take();
|
|
102
|
+
ctx.audit = audit;
|
|
103
|
+
const abort = { deferred: !abortable };
|
|
104
|
+
ctx.abort = abort;
|
|
105
|
+
const off = ctx.host.onSignal((signal) => {
|
|
106
|
+
abort.signal = signal;
|
|
107
|
+
ctx.host.out.warn(abort.deferred
|
|
108
|
+
? `${signal}: ${command} cannot stop safely at this point — it finishes, then exits (a second ${signal} stops it at once)`
|
|
109
|
+
: `${signal}: stopping after this step; what the deploy changed is put back (a second ${signal} stops it at once)`);
|
|
110
|
+
});
|
|
111
|
+
try {
|
|
112
|
+
await options.protocol?.afterLock?.();
|
|
113
|
+
return await body();
|
|
114
|
+
}
|
|
115
|
+
finally {
|
|
116
|
+
off();
|
|
117
|
+
delete ctx.abort;
|
|
118
|
+
delete ctx.audit;
|
|
119
|
+
await release();
|
|
120
|
+
}
|
|
31
121
|
}
|
|
32
122
|
// ── the runtime: PM2 on the host, or a compose project ────────────────────
|
|
33
123
|
const isCompose = (ctx) => ctx.config.runtime.kind === 'compose';
|
|
@@ -72,6 +162,7 @@ export async function preflight(ctx, options = {}) {
|
|
|
72
162
|
const document = await readEnv(ctx);
|
|
73
163
|
const values = envValues(document);
|
|
74
164
|
findings.push(...syntaxFindings(document, ctx.config.env.file ?? '.env'));
|
|
165
|
+
findings.push(...await envModeFindings(ctx));
|
|
75
166
|
const port = await resolvePort(ctx, values);
|
|
76
167
|
findings.push(...await toolingFindings(ctx));
|
|
77
168
|
findings.push(...await lockfileFindings(ctx));
|
|
@@ -90,13 +181,15 @@ export async function preflight(ctx, options = {}) {
|
|
|
90
181
|
/** The dump's container running — found now, not after the build, minutes later. */
|
|
91
182
|
async function backupFindings(ctx, values, options) {
|
|
92
183
|
const container = ctx.config.backup?.container;
|
|
184
|
+
const runs = backupDecision(ctx.config, values, options.skip ?? []).run;
|
|
185
|
+
const place = runs ? await backupPlaceFindings(ctx) : [];
|
|
93
186
|
// An external infra.postgres is checked with the rest of the infra.
|
|
94
|
-
if (!container || !
|
|
95
|
-
return
|
|
187
|
+
if (!container || !runs)
|
|
188
|
+
return place;
|
|
96
189
|
const running = await ctx.host.exec('docker', ['inspect', '--format', '{{.State.Running}}', container]);
|
|
97
190
|
if (running.stdout.trim() === 'true')
|
|
98
|
-
return
|
|
99
|
-
return [{
|
|
191
|
+
return place;
|
|
192
|
+
return [...place, {
|
|
100
193
|
id: 'backup',
|
|
101
194
|
level: 'error',
|
|
102
195
|
message: running.code === 0 ? `backup.container ${container} is not running` : `backup.container ${container} does not exist (or docker is not available to this user)`,
|
|
@@ -105,6 +198,19 @@ async function backupFindings(ctx, values, options) {
|
|
|
105
198
|
}
|
|
106
199
|
const LOCKFILES = ['pnpm-lock.yaml', 'package-lock.json', 'yarn.lock', 'bun.lock'];
|
|
107
200
|
async function gitFindings(ctx, options) {
|
|
201
|
+
const findings = await dirtyFindings(ctx);
|
|
202
|
+
if (findings.some((f) => f.message.endsWith('is not a git checkout')))
|
|
203
|
+
return findings;
|
|
204
|
+
const branch = (await ctx.host.exec('git', ['rev-parse', '--abbrev-ref', 'HEAD'], { cwd: ctx.dir })).stdout.trim();
|
|
205
|
+
const wanted = ctx.config.branch ?? 'main';
|
|
206
|
+
if (branch !== wanted)
|
|
207
|
+
findings.push({ id: 'git', level: 'error', message: `the checkout is on "${branch}", the deploy tracks "${wanted}"`, fix: `git checkout ${wanted}` });
|
|
208
|
+
if (!options.skip?.includes('fetch'))
|
|
209
|
+
findings.push(...await remoteFindings(ctx));
|
|
210
|
+
return findings;
|
|
211
|
+
}
|
|
212
|
+
/** Tracked files modified on the server: a deploy (or a rollback's reset) would discard them. */
|
|
213
|
+
async function dirtyFindings(ctx) {
|
|
108
214
|
const findings = [];
|
|
109
215
|
const dirty = await ctx.host.exec('git', ['status', '--porcelain', '--untracked-files=no'], { cwd: ctx.dir });
|
|
110
216
|
if (dirty.code !== 0)
|
|
@@ -121,20 +227,13 @@ async function gitFindings(ctx, options) {
|
|
|
121
227
|
: 'git stash (or commit them where they belong); a deploy builds what is committed',
|
|
122
228
|
});
|
|
123
229
|
}
|
|
124
|
-
const branch = (await ctx.host.exec('git', ['rev-parse', '--abbrev-ref', 'HEAD'], { cwd: ctx.dir })).stdout.trim();
|
|
125
|
-
const wanted = ctx.config.branch ?? 'main';
|
|
126
|
-
if (branch !== wanted)
|
|
127
|
-
findings.push({ id: 'git', level: 'error', message: `the checkout is on "${branch}", the deploy tracks "${wanted}"`, fix: `git checkout ${wanted}` });
|
|
128
|
-
if (!options.skip?.includes('fetch'))
|
|
129
|
-
findings.push(...await remoteFindings(ctx));
|
|
130
230
|
return findings;
|
|
131
231
|
}
|
|
132
232
|
const CREDENTIALS = /terminal prompts disabled|could not read (Username|Password)|Authentication failed|Permission denied \(publickey|Host key verification failed|Invalid username or (password|token)/i;
|
|
133
233
|
/** Can the fetch reach the branch without asking anyone for anything? */
|
|
134
234
|
async function remoteFindings(ctx) {
|
|
135
|
-
const remote = ctx
|
|
136
|
-
const
|
|
137
|
-
const probe = await ctx.host.exec('git', ['ls-remote', '--exit-code', remote, `refs/heads/${branch}`], { cwd: ctx.dir, env: NO_PROMPT });
|
|
235
|
+
const { remote, branch, head } = gitTarget(ctx);
|
|
236
|
+
const probe = await ctx.host.exec('git', ['ls-remote', '--exit-code', '--', remote, head], { cwd: ctx.dir, env: NO_PROMPT });
|
|
138
237
|
if (probe.code === 0)
|
|
139
238
|
return [];
|
|
140
239
|
if (probe.code === 2)
|
|
@@ -152,7 +251,11 @@ function stopOnErrors(ctx, findings, what) {
|
|
|
152
251
|
report(ctx.host, findings);
|
|
153
252
|
const blocking = errors(findings);
|
|
154
253
|
if (blocking.length > 0)
|
|
155
|
-
throw new DeployError(`${what}: ${blocking.length} problem(s) above — nothing was changed`, blocking);
|
|
254
|
+
throw new DeployError(`${what}: ${blocking.length} problem(s) above — nothing was changed`, blocking, 'preflight');
|
|
255
|
+
}
|
|
256
|
+
/** The questions nobody answered: the command stops before anything is written. */
|
|
257
|
+
function missingAnswers(missing, protocol) {
|
|
258
|
+
return new DeployError(`no answer for ${missing.join(', ')} (no terminal to ask): set them in the environment of this command`, [], 'answer-missing', protocol ? 'pass them with --answers=stdin (plan --json lists them), or in the environment of the command' : undefined);
|
|
156
259
|
}
|
|
157
260
|
// ── what runs by default ───────────────────────────────────────────────────
|
|
158
261
|
/** `prisma migrate deploy` runs when asked to, or — unsaid — when the app generates a Prisma client. */
|
|
@@ -359,10 +462,11 @@ async function publicHealthy(ctx) {
|
|
|
359
462
|
}
|
|
360
463
|
/** Puts the code on disk back to `sha` and rebuilds it. Does not restart anything. */
|
|
361
464
|
async function restoreCode(ctx, sha, values) {
|
|
362
|
-
ctx
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
465
|
+
await stepped(ctx, 'restore', async () => {
|
|
466
|
+
await git(ctx, ['reset', '--hard', sha]);
|
|
467
|
+
await build(ctx, values, sha);
|
|
468
|
+
await settleLockfile(ctx);
|
|
469
|
+
}, `restoring the code to ${sha.slice(0, 7)}`);
|
|
366
470
|
}
|
|
367
471
|
/** The env step's summary: what changed, or that nothing did. */
|
|
368
472
|
function reportEnv(ctx, plan) {
|
|
@@ -372,6 +476,12 @@ function reportEnv(ctx, plan) {
|
|
|
372
476
|
for (const line of lines)
|
|
373
477
|
ctx.host.out.info(line);
|
|
374
478
|
}
|
|
479
|
+
/** Writes the `.env` and puts its mode (and its mirrors') back to 0600. */
|
|
480
|
+
async function writeEnvSecure(ctx, plan) {
|
|
481
|
+
await writeEnv(ctx, plan);
|
|
482
|
+
for (const file of await secureEnvModes(ctx))
|
|
483
|
+
ctx.host.out.ok(`${file} is 0600 again (other users could read it)`);
|
|
484
|
+
}
|
|
375
485
|
async function infraStep(ctx, infra, values) {
|
|
376
486
|
stopOnErrors(ctx, await applyInfra(ctx, infra), 'infra');
|
|
377
487
|
const external = externalOf(ctx.config);
|
|
@@ -406,9 +516,25 @@ export async function plan(ctx, options = {}) {
|
|
|
406
516
|
const { env, infra } = await prepareEnv(ctx, checked.port);
|
|
407
517
|
report(ctx.host, infra.findings);
|
|
408
518
|
const { host, config, pm } = ctx;
|
|
409
|
-
|
|
519
|
+
const blocking = errors([...checked.findings, ...infra.findings]).length > 0;
|
|
520
|
+
const lines = await stepped(ctx, 'plan', async () => planLines(ctx, options, checked, env, infra), 'plan — nothing below has run');
|
|
521
|
+
host.out.result?.('plan', {
|
|
522
|
+
findings: [...checked.findings, ...infra.findings],
|
|
523
|
+
lines: lines.map((line) => {
|
|
524
|
+
const at = line.indexOf(': ');
|
|
525
|
+
return at === -1 ? { step: '', text: line } : { step: line.slice(0, at), text: line.slice(at + 2) };
|
|
526
|
+
}),
|
|
527
|
+
// What env/run would ask now — the deploy's own environment answers first, as it does there.
|
|
528
|
+
questions: questionDescriptors(config, env.questions.filter((key) => host.env[key] === undefined)),
|
|
529
|
+
blocking,
|
|
530
|
+
});
|
|
531
|
+
return blocking ? 1 : 0;
|
|
532
|
+
}
|
|
533
|
+
/** What `plan` prints, one line per thing a run would do. */
|
|
534
|
+
function planLines(ctx, options, checked, env, infra) {
|
|
535
|
+
const { host, config, pm } = ctx;
|
|
410
536
|
const lines = [
|
|
411
|
-
options.skip?.includes('fetch') ? 'fetch: skipped' : `fetch: git
|
|
537
|
+
options.skip?.includes('fetch') ? 'fetch: skipped' : ((t) => `fetch: git ${fetchArgs(t).filter((a) => a !== '--quiet').join(' ')} && git merge --ff-only ${t.tracking}`)(gitTarget(ctx)),
|
|
412
538
|
...describeEnv(env).map((l) => `env: ${l}`),
|
|
413
539
|
...describeInfra(infra).map((l) => `infra: ${l}`),
|
|
414
540
|
...describeServices(config).map((l) => `infra: ${l}`),
|
|
@@ -416,7 +542,7 @@ export async function plan(ctx, options = {}) {
|
|
|
416
542
|
...(config.hooks?.infra ?? []).map((h) => `infra hook: ${h.join(' ')}`),
|
|
417
543
|
`validate: ${config.env.schema ?? '(no schema configured)'} against the new .env`,
|
|
418
544
|
((decision) => decision.run
|
|
419
|
-
? `backup: pg_dump${dumpContainer(config) ? ` inside ${dumpContainer(config)}` : ''} → ${
|
|
545
|
+
? `backup: pg_dump${dumpContainer(config) ? ` inside ${dumpContainer(config)}` : ''} → ${backupDir(ctx)} (keep ${config.backup?.keep ?? 10})`
|
|
420
546
|
: `backup: skipped (${decision.why})`)(backupDecision(config, checked.values, options.skip ?? [])),
|
|
421
547
|
`migrate: ${[config.migrate?.command?.join(' ') ?? '', migratesCentral(config) ? 'prisma migrate deploy' : '', config.migrate?.tenants ? 'tenant:migrate' : ''].filter(Boolean).join(' + ') || 'nothing configured'}`,
|
|
422
548
|
...(isCompose(ctx) && composeOf(ctx).attach ? [`attach: ${Object.entries(composeOf(ctx).attach ?? {}).map(([c, n]) => `${c} → ${n.join(', ')}`).join('; ')}`] : []),
|
|
@@ -432,58 +558,82 @@ export async function plan(ctx, options = {}) {
|
|
|
432
558
|
lines.push(`verify: ${check.path} answers ${check.expect ?? 200}`);
|
|
433
559
|
for (const line of lines)
|
|
434
560
|
host.out.info(line);
|
|
435
|
-
return
|
|
561
|
+
return lines;
|
|
436
562
|
}
|
|
437
563
|
/** `basalt-deploy env` — the .env and the infra only (first setup, before `install`). */
|
|
438
|
-
export async function envCommand(ctx) {
|
|
564
|
+
export async function envCommand(ctx, options = {}) {
|
|
565
|
+
return locked(ctx, 'env', options, true, () => envLocked(ctx, options));
|
|
566
|
+
}
|
|
567
|
+
/**
|
|
568
|
+
* The env step: plan the `.env`, ask what is missing, write it (0600). The
|
|
569
|
+
* questions are asked inside the step, before anything is written.
|
|
570
|
+
*/
|
|
571
|
+
async function envStep(ctx, port, options) {
|
|
572
|
+
const prepared = await prepareEnv(ctx, port);
|
|
573
|
+
stopOnErrors(ctx, prepared.infra.findings, 'infra');
|
|
574
|
+
const protocol = options.protocol !== undefined;
|
|
575
|
+
const missing = await answerQuestions(ctx, prepared.env, { secretsNeverDefault: protocol });
|
|
576
|
+
options.protocol?.afterAnswers?.();
|
|
577
|
+
if (missing.length > 0)
|
|
578
|
+
throw missingAnswers(missing, protocol);
|
|
579
|
+
reportEnv(ctx, prepared.env);
|
|
580
|
+
const changes = prepared.env.changes.map((c) => ({ kind: c.kind, key: c.key, reason: c.reason }));
|
|
581
|
+
await writeEnvSecure(ctx, prepared.env);
|
|
582
|
+
return { ...prepared, changes };
|
|
583
|
+
}
|
|
584
|
+
async function envLocked(ctx, options) {
|
|
439
585
|
const document = await readEnv(ctx);
|
|
440
|
-
stopOnErrors(ctx, syntaxFindings(document, ctx.config.env.file ?? '.env'), '.env');
|
|
586
|
+
stopOnErrors(ctx, [...syntaxFindings(document, ctx.config.env.file ?? '.env'), ...await envModeFindings(ctx)], '.env');
|
|
441
587
|
const port = await resolvePort(ctx, envValues(document));
|
|
442
|
-
const { env, infra } = await step(ctx, 'env', () =>
|
|
443
|
-
stopOnErrors(ctx, infra.findings, 'infra');
|
|
444
|
-
const missing = await answerQuestions(ctx, env);
|
|
445
|
-
if (missing.length > 0)
|
|
446
|
-
throw new DeployError(`no answer for ${missing.join(', ')} (no terminal to ask): set them in the environment of this command`);
|
|
447
|
-
reportEnv(ctx, env);
|
|
448
|
-
await writeEnv(ctx, env);
|
|
588
|
+
const { env, infra, changes } = await step(ctx, 'env', () => envStep(ctx, port, options));
|
|
449
589
|
await step(ctx, 'infra', () => infraStep(ctx, infra, env.values));
|
|
450
590
|
await step(ctx, 'validate', () => validateStep(ctx, env.values));
|
|
451
591
|
ctx.host.out.ok(isCompose(ctx) ? `${envFile(ctx)} ready` : `.env ready (PORT=${port})`);
|
|
592
|
+
ctx.host.out.result?.('env', { file: envFile(ctx), changes, ...(isCompose(ctx) ? {} : { port }) });
|
|
452
593
|
return 0;
|
|
453
594
|
}
|
|
454
595
|
export async function run(ctx, options = {}) {
|
|
596
|
+
return locked(ctx, 'run', options, true, () => runLocked(ctx, options));
|
|
597
|
+
}
|
|
598
|
+
async function runLocked(ctx, options) {
|
|
455
599
|
const { host, config } = ctx;
|
|
456
600
|
const skip = new Set(options.skip ?? []);
|
|
457
|
-
const checked = await step(ctx, 'preflight', () =>
|
|
458
|
-
|
|
601
|
+
const checked = await step(ctx, 'preflight', async () => {
|
|
602
|
+
const found = await preflight(ctx, options);
|
|
603
|
+
stopOnErrors(ctx, found.findings, 'preflight');
|
|
604
|
+
return found;
|
|
605
|
+
});
|
|
459
606
|
const { port } = checked;
|
|
460
607
|
const previous = await git(ctx, ['rev-parse', 'HEAD']);
|
|
608
|
+
let heldOverride = false;
|
|
461
609
|
if (!skip.has('fetch')) {
|
|
610
|
+
const target = gitTarget(ctx);
|
|
462
611
|
await step(ctx, 'fetch', async () => {
|
|
463
|
-
await git(ctx,
|
|
464
|
-
await git(ctx, ['
|
|
612
|
+
await git(ctx, fetchArgs(target), { noPrompt: !host.interactive() });
|
|
613
|
+
heldOverride = await refuseHeld(ctx, await git(ctx, ['rev-parse', '--verify', '--end-of-options', `${target.tracking}^{commit}`]), options);
|
|
614
|
+
await git(ctx, ['merge', '--ff-only', target.tracking]);
|
|
465
615
|
});
|
|
466
616
|
}
|
|
617
|
+
else {
|
|
618
|
+
heldOverride = await refuseHeld(ctx, previous, options);
|
|
619
|
+
}
|
|
467
620
|
const sha = await git(ctx, ['rev-parse', 'HEAD']);
|
|
468
621
|
host.out.info(sha === previous ? `already at ${sha.slice(0, 7)}` : `${previous.slice(0, 7)} → ${sha.slice(0, 7)}`);
|
|
469
622
|
const applied = sha === previous ? [] : migrationNames((await git(ctx, ['diff', '--name-only', previous, sha])).split('\n'));
|
|
470
623
|
const record = { sha, previous, at: host.now().toISOString(), user: host.env['USER'] ?? String(host.uid()), status: 'failed', migrations: applied };
|
|
624
|
+
/** The payload, once the release is recorded (RFC 0008 §4.3). */
|
|
625
|
+
const result = (url) => host.out.result?.('run', runResult(record, heldOverride, url));
|
|
471
626
|
// From here a failure puts the code on disk back before it is reported.
|
|
472
627
|
const lockfileSaid = { warned: false };
|
|
473
628
|
let values = checked.values;
|
|
474
629
|
let infra = { services: [], env: [], findings: [], secrets: {} };
|
|
630
|
+
let migrating = false;
|
|
475
631
|
try {
|
|
476
632
|
// Again on the code the fetch brought: preflight saw the commit before it.
|
|
477
633
|
if (sha !== previous)
|
|
478
634
|
stopOnErrors(ctx, await lockfileFindings(ctx), `the incoming commit ${sha.slice(0, 7)}`);
|
|
479
|
-
const prepared = await step(ctx, 'env', () =>
|
|
635
|
+
const prepared = await step(ctx, 'env', () => envStep(ctx, port, options));
|
|
480
636
|
infra = prepared.infra;
|
|
481
|
-
stopOnErrors(ctx, infra.findings, 'infra');
|
|
482
|
-
const missing = await answerQuestions(ctx, prepared.env);
|
|
483
|
-
if (missing.length > 0)
|
|
484
|
-
throw new DeployError(`no answer for ${missing.join(', ')} (no terminal to ask): set them in the environment of this command`);
|
|
485
|
-
reportEnv(ctx, prepared.env);
|
|
486
|
-
await writeEnv(ctx, prepared.env);
|
|
487
637
|
values = prepared.env.values;
|
|
488
638
|
await step(ctx, 'infra', async () => { await infraStep(ctx, infra, values); await runHooks(ctx, 'infra', values, sha); });
|
|
489
639
|
await step(ctx, 'build', async () => { await build(ctx, values, sha); await settleLockfile(ctx, lockfileSaid); });
|
|
@@ -494,16 +644,40 @@ export async function run(ctx, options = {}) {
|
|
|
494
644
|
host.out.ok(record.backup);
|
|
495
645
|
}
|
|
496
646
|
else {
|
|
497
|
-
host.out.step('backup');
|
|
647
|
+
host.out.step('backup', 'backup');
|
|
498
648
|
host.out.info(`skipped: ${backup.why}`);
|
|
649
|
+
host.out.stepEnd?.('backup', 'skipped', 0);
|
|
499
650
|
}
|
|
651
|
+
// The last point where a signal stops the deploy. Once a migration has
|
|
652
|
+
// started, the old code may not run on the schema it leaves: the deploy
|
|
653
|
+
// finishes (release, health, rollback rules) instead of putting it back.
|
|
654
|
+
throwIfAborted(ctx);
|
|
655
|
+
if (ctx.abort)
|
|
656
|
+
ctx.abort.deferred = true;
|
|
657
|
+
migrating = true;
|
|
500
658
|
await step(ctx, 'migrate', async () => { await migrate(ctx, values); await tenantGrants(ctx, infra, values); await settleLockfile(ctx, lockfileSaid); });
|
|
501
659
|
}
|
|
502
660
|
catch (error) {
|
|
503
661
|
if (sha !== previous)
|
|
504
662
|
await restoreCode(ctx, previous, values).catch((e) => host.out.error(`could not restore the code: ${e.message}`));
|
|
505
663
|
record.note = error.message;
|
|
664
|
+
const signal = ctx.abort?.signal;
|
|
665
|
+
if (migrating) {
|
|
666
|
+
// The code is back; the database may not be — a migration does not undo itself.
|
|
667
|
+
record.status = 'failed-migration';
|
|
668
|
+
host.out.error(`the migration failed: the database may be part-way migrated, and the code is back on ${previous.slice(0, 7)}`);
|
|
669
|
+
if (record.backup)
|
|
670
|
+
host.out.info(`to put the database back as it was before this deploy: ${restoreCommand(ctx, infra, record.backup, values)}`);
|
|
671
|
+
else
|
|
672
|
+
host.out.warn('no dump was taken before this migration (backup skipped): restore from your own backups if needed');
|
|
673
|
+
}
|
|
674
|
+
else if (signal)
|
|
675
|
+
record.status = 'aborted';
|
|
506
676
|
await recordRelease(ctx, record).catch(() => undefined);
|
|
677
|
+
result();
|
|
678
|
+
// A terminal's SIGINT reaches the child too: its failure is the signal's.
|
|
679
|
+
if (signal && !(error instanceof DeployAbortedError))
|
|
680
|
+
throw new DeployAbortedError(signal, error.message);
|
|
507
681
|
throw error;
|
|
508
682
|
}
|
|
509
683
|
const destructive = applied.filter((name) => config.destructive?.includes(name));
|
|
@@ -516,12 +690,18 @@ export async function run(ctx, options = {}) {
|
|
|
516
690
|
host.out.info(`database before this release: ${restoreCommand(ctx, infra, record.backup, values)}`);
|
|
517
691
|
record.note = why;
|
|
518
692
|
await recordRelease(ctx, record);
|
|
693
|
+
result();
|
|
519
694
|
return 1;
|
|
520
695
|
}
|
|
521
|
-
await rollbackTo(ctx, previous, values, port);
|
|
696
|
+
const back = await rollbackTo(ctx, previous, values, port);
|
|
522
697
|
record.status = 'rolled-back';
|
|
523
698
|
record.note = why;
|
|
524
699
|
await recordRelease(ctx, record);
|
|
700
|
+
if (!back.ok) {
|
|
701
|
+
// The previous commit does not answer either: never a rollback target again.
|
|
702
|
+
await recordRelease(ctx, { ...record, sha: previous, previous: sha, at: host.now().toISOString(), status: 'rollback-unhealthy', migrations: [], note: back.why });
|
|
703
|
+
}
|
|
704
|
+
result();
|
|
525
705
|
return 1;
|
|
526
706
|
};
|
|
527
707
|
const releasedAt = host.now();
|
|
@@ -550,6 +730,8 @@ export async function run(ctx, options = {}) {
|
|
|
550
730
|
}
|
|
551
731
|
}
|
|
552
732
|
record.status = publicProblem ? 'public-unreachable' : 'ok';
|
|
733
|
+
// A healthy release on purpose: whatever a rollback held is behind us.
|
|
734
|
+
await clearHold(ctx);
|
|
553
735
|
// `pnpm run start`, launched by PM2 in the checkout, may rewrite it too.
|
|
554
736
|
await settleLockfile(ctx, lockfileSaid);
|
|
555
737
|
await step(ctx, 'record', () => recordRelease(ctx, record));
|
|
@@ -557,8 +739,11 @@ export async function run(ctx, options = {}) {
|
|
|
557
739
|
await retainImages(ctx);
|
|
558
740
|
if (publicProblem) {
|
|
559
741
|
report(host, [publicProblem]);
|
|
742
|
+
record.note = publicProblem.message;
|
|
743
|
+
result();
|
|
560
744
|
return 1;
|
|
561
745
|
}
|
|
746
|
+
result(`https://${config.domain}`);
|
|
562
747
|
host.out.ok(`${config.app} ${sha.slice(0, 7)} is live at https://${config.domain}`);
|
|
563
748
|
return 0;
|
|
564
749
|
}
|
|
@@ -571,25 +756,61 @@ async function retainImages(ctx) {
|
|
|
571
756
|
if (removed.length > 0)
|
|
572
757
|
ctx.host.out.info(`removed ${removed.length} image(s) of releases older than the last ${keep}: ${removed.join(', ')}`);
|
|
573
758
|
}
|
|
759
|
+
function runResult(record, heldOverride, url) {
|
|
760
|
+
return {
|
|
761
|
+
sha: record.sha, previous: record.previous ?? '', status: record.status, migrations: record.migrations,
|
|
762
|
+
...(record.backup ? { backup: record.backup } : {}),
|
|
763
|
+
...(url ? { url } : {}),
|
|
764
|
+
...(heldOverride ? { heldOverride: true } : {}),
|
|
765
|
+
...(record.note ? { note: record.note } : {}),
|
|
766
|
+
};
|
|
767
|
+
}
|
|
768
|
+
/** `run` will not redeploy the commit a manual rollback left, unless asked to (`--unhold`). True when it was held and deployed anyway. */
|
|
769
|
+
async function refuseHeld(ctx, incoming, options) {
|
|
770
|
+
const hold = await readHold(ctx);
|
|
771
|
+
if (!hold || hold.sha !== incoming)
|
|
772
|
+
return false;
|
|
773
|
+
if (options.unhold) {
|
|
774
|
+
ctx.host.out.warn(`deploying ${incoming.slice(0, 7)} although a rollback held it (--unhold)`);
|
|
775
|
+
return true;
|
|
776
|
+
}
|
|
777
|
+
throw new DeployError(`${incoming.slice(0, 7)} is held: ${hold.note} by ${hold.actor || 'someone'} at ${hold.at} — nothing was changed. Push a fix (the hold ends when the branch moves on), or deploy it anyway with --unhold`, [], 'held');
|
|
778
|
+
}
|
|
574
779
|
async function rollbackTo(ctx, sha, values, port) {
|
|
575
780
|
// Compose: the images of `sha` exist (kept by retention), so the rebuild
|
|
576
781
|
// inside restoreCode skips them — a rollback is not a new build.
|
|
577
782
|
await restoreCode(ctx, sha, values);
|
|
578
|
-
ctx
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
783
|
+
return stepped(ctx, 'release', async () => {
|
|
784
|
+
ctx.host.out.ok(await release(ctx, values, sha));
|
|
785
|
+
const health = await healthCheck(ctx, port, sha);
|
|
786
|
+
if (health.ok)
|
|
787
|
+
ctx.host.out.ok(`back on ${sha.slice(0, 7)}`);
|
|
788
|
+
else
|
|
789
|
+
ctx.host.out.error(`${sha.slice(0, 7)} does not answer either (${health.why}) — ${logsHint(ctx)}`);
|
|
790
|
+
return health;
|
|
791
|
+
}, `release ${sha.slice(0, 7)}`);
|
|
585
792
|
}
|
|
586
793
|
/** `basalt-deploy rollback [--to=<sha>]` — code only; the database stays as it is. */
|
|
587
|
-
export async function rollback(ctx, to) {
|
|
794
|
+
export async function rollback(ctx, to, options = {}) {
|
|
795
|
+
return locked(ctx, 'rollback', options, false, () => rollbackLocked(ctx, to, options));
|
|
796
|
+
}
|
|
797
|
+
async function rollbackLocked(ctx, to, options) {
|
|
798
|
+
// The reset below would discard edits on the server, as a deploy would.
|
|
799
|
+
stopOnErrors(ctx, await dirtyFindings(ctx), 'rollback');
|
|
588
800
|
const current = await git(ctx, ['rev-parse', 'HEAD']);
|
|
589
801
|
const releases = await readReleases(ctx);
|
|
802
|
+
let wanted;
|
|
803
|
+
if (to !== undefined) {
|
|
804
|
+
if (!/^[0-9a-f]{7,40}$/.test(to))
|
|
805
|
+
throw new DeployError(`--to=${to}: a commit sha (7 to 40 hex digits)`);
|
|
806
|
+
const resolved = await ctx.host.exec('git', ['rev-parse', '--verify', '--quiet', '--end-of-options', `${to}^{commit}`], { cwd: ctx.dir });
|
|
807
|
+
if (resolved.code !== 0)
|
|
808
|
+
throw new DeployError(`--to=${to} is not a commit in this checkout`);
|
|
809
|
+
wanted = resolved.stdout.trim();
|
|
810
|
+
}
|
|
590
811
|
// The last healthy release before this one; on the first recorded deploy,
|
|
591
812
|
// the commit it was deployed over.
|
|
592
|
-
const target =
|
|
813
|
+
const target = wanted ?? lastGood(releases, current)?.sha ?? deployedOver(releases, current);
|
|
593
814
|
if (!target || target === current)
|
|
594
815
|
throw new DeployError('no earlier release to go back to; pass --to=<sha>');
|
|
595
816
|
const document = await readEnv(ctx);
|
|
@@ -602,127 +823,72 @@ export async function rollback(ctx, to) {
|
|
|
602
823
|
if (destructive.length > 0)
|
|
603
824
|
throw new DeployError(`refused: ${destructive.join(', ')} marked destructive — ${target.slice(0, 7)} cannot run on this schema`);
|
|
604
825
|
}
|
|
605
|
-
await rollbackTo(ctx, target, values, port);
|
|
606
|
-
|
|
826
|
+
const back = await rollbackTo(ctx, target, values, port);
|
|
827
|
+
const at = ctx.host.now().toISOString();
|
|
828
|
+
const note = `manual rollback from ${current.slice(0, 7)}`;
|
|
829
|
+
await recordRelease(ctx, {
|
|
830
|
+
sha: target, previous: current, at, user: ctx.host.env['USER'] ?? '', migrations: [],
|
|
831
|
+
status: back.ok ? 'ok' : 'rollback-unhealthy',
|
|
832
|
+
note: back.ok ? note : `${note}; ${target.slice(0, 7)} does not answer either: ${back.why}`,
|
|
833
|
+
});
|
|
834
|
+
// Whatever the outcome, the commit rolled away from is not redeployed by the next scheduled run.
|
|
835
|
+
await writeHold(ctx, { sha: current, at, actor: ctx.audit?.actor ?? '', note: `rolled back to ${target.slice(0, 7)}` });
|
|
836
|
+
ctx.host.out.info(`${current.slice(0, 7)} is held: \`run\` will not deploy it again until the branch moves on (or --unhold)`);
|
|
837
|
+
ctx.host.out.result?.('rollback', { from: current, to: target, status: back.ok ? 'ok' : 'rollback-unhealthy', held: current });
|
|
838
|
+
if (!back.ok) {
|
|
839
|
+
ctx.host.out.error(`the rollback did not bring a healthy release: ${target.slice(0, 7)} is recorded as rollback-unhealthy — try another with --to=<sha>`);
|
|
840
|
+
return 1;
|
|
841
|
+
}
|
|
607
842
|
return 0;
|
|
608
843
|
}
|
|
609
844
|
export async function status(ctx) {
|
|
610
845
|
const { host } = ctx;
|
|
611
846
|
const releases = (await readReleases(ctx)).slice(-10).reverse();
|
|
612
847
|
host.out.step(`${ctx.config.app} — last ${releases.length} release(s)`);
|
|
848
|
+
const lock = await readLock(host, ctx.stateDir);
|
|
849
|
+
if (!lock)
|
|
850
|
+
host.out.info('no deploy running');
|
|
851
|
+
else if (lock.corrupt)
|
|
852
|
+
host.out.warn(`${lock.path} is not a deploy lock (empty or unreadable): deploys are refused until it is removed`);
|
|
853
|
+
else if (lock.stale)
|
|
854
|
+
host.out.warn(`stale lock: ${describeHolder(lock.holder)} — that process is gone; the next deploy takes it over`);
|
|
855
|
+
else
|
|
856
|
+
host.out.info(`deploy running: ${describeHolder(lock.holder)}`);
|
|
857
|
+
const hold = await readHold(ctx);
|
|
858
|
+
if (hold)
|
|
859
|
+
host.out.warn(`held: ${hold.sha.slice(0, 7)} (${hold.note}, by ${hold.actor || 'someone'} at ${hold.at}) — run will not deploy it again; --unhold to override`);
|
|
613
860
|
for (const r of releases)
|
|
614
|
-
host.out.info(`${r.at} ${r.sha.slice(0, 7)} ${r.status.padEnd(18)} ${r.user}${r.migrations.length ? ` +${r.migrations.length} migration(s)` : ''}${r.note ? ` — ${r.note}` : ''}`);
|
|
861
|
+
host.out.info(`${r.at} ${r.sha.slice(0, 7)} ${r.status.padEnd(18)} ${r.actor && r.actor !== r.user ? `${r.actor} (${r.user})` : r.user}${r.client ? ` from ${r.client}` : ''}${r.migrations.length ? ` +${r.migrations.length} migration(s)` : ''}${r.note ? ` — ${r.note}` : ''}`);
|
|
862
|
+
let running;
|
|
615
863
|
if (isCompose(ctx)) {
|
|
616
864
|
const head = (await ctx.host.exec('git', ['rev-parse', 'HEAD'], { cwd: ctx.dir })).stdout.trim();
|
|
617
|
-
|
|
865
|
+
const lines = await composeStatus(ctx, head);
|
|
866
|
+
for (const line of lines)
|
|
618
867
|
host.out.info(line);
|
|
619
|
-
|
|
868
|
+
running = { kind: 'compose', lines };
|
|
620
869
|
}
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
* `docker` group (root-equivalent); with dedicated infra it needs rootless
|
|
630
|
-
* Docker, and this says so.
|
|
631
|
-
*/
|
|
632
|
-
/**
|
|
633
|
-
* An env file outside the checkout (`/etc/<app>/api.env`) was root's while
|
|
634
|
-
* deploys ran under sudo. Deploys run as the app user (§11.4, §13.5), so it
|
|
635
|
-
* takes over the files — and their directory, where the atomic write and the
|
|
636
|
-
* backups are created, but only a directory that is plainly the app's own
|
|
637
|
-
* (its name contains the app's). Never /etc, never a shared directory.
|
|
638
|
-
*/
|
|
639
|
-
async function envOwnership(ctx, user) {
|
|
640
|
-
const files = [envFile(ctx), ...envMirrors(ctx)].filter((f) => !f.startsWith(`${ctx.dir}/`));
|
|
641
|
-
if (files.length === 0)
|
|
642
|
-
return;
|
|
643
|
-
await step(ctx, 'env files outside the checkout', async () => {
|
|
644
|
-
const { host } = ctx;
|
|
645
|
-
for (const file of files) {
|
|
646
|
-
if (!(await host.exists(file))) {
|
|
647
|
-
host.out.warn(`${file} does not exist yet — the first deploy creates it`);
|
|
648
|
-
continue;
|
|
649
|
-
}
|
|
650
|
-
const chown = await host.exec('chown', [`${user}:`, file]);
|
|
651
|
-
if (chown.code !== 0)
|
|
652
|
-
throw new DeployError(`chown ${user} ${file}: ${chown.stderr.trim()}`);
|
|
653
|
-
await host.exec('chmod', ['600', file]);
|
|
654
|
-
}
|
|
655
|
-
for (const dir of [...new Set(files.map((f) => dirname(f)))]) {
|
|
656
|
-
if (basename(dir).includes(ctx.config.app) && dir !== '/' && dir !== '/etc') {
|
|
657
|
-
const chown = await host.exec('chown', [`${user}:`, dir]);
|
|
658
|
-
if (chown.code !== 0)
|
|
659
|
-
throw new DeployError(`chown ${user} ${dir}: ${chown.stderr.trim()}`);
|
|
660
|
-
await host.exec('chmod', ['700', dir]);
|
|
661
|
-
host.out.ok(`${dir} and its env files (${files.filter((f) => dirname(f) === dir).map((f) => basename(f)).join(', ')}) now owned by ${user}, 0700/0600`);
|
|
662
|
-
}
|
|
663
|
-
else {
|
|
664
|
-
host.out.warn(`${dir} is not ${ctx.config.app}'s own directory: the files are ${user}'s, but backups and atomic writes need ${user} to write in ${dir}`);
|
|
665
|
-
}
|
|
666
|
-
}
|
|
667
|
-
});
|
|
668
|
-
}
|
|
669
|
-
export async function install(ctx, user) {
|
|
670
|
-
const { host, config } = ctx;
|
|
671
|
-
if (host.uid() !== 0)
|
|
672
|
-
throw new DeployError(`install needs root: ${INSTALL_COMMAND}`);
|
|
673
|
-
if (!user || user === 'root')
|
|
674
|
-
throw new DeployError('install needs the unprivileged user the deploys run as: --user=<name> (never root)');
|
|
675
|
-
const port = isCompose(ctx) ? composeOf(ctx).upstream.port : Number(envValues(await readEnv(ctx)).get('PORT'));
|
|
676
|
-
if (!Number.isInteger(port) || port <= 0)
|
|
677
|
-
throw new DeployError(`no PORT in the .env yet: run \`${RUN_COMMAND.replace(/ run$/, ' env')}\` as the app user first`);
|
|
678
|
-
const stateDir = `/var/lib/basalt/${config.app}`;
|
|
679
|
-
await step(ctx, `state directory ${stateDir}`, async () => {
|
|
680
|
-
await host.mkdir(stateDir, 0o700);
|
|
681
|
-
await host.mkdir(join(stateDir, 'install-backups'), 0o700);
|
|
682
|
-
const local = await host.readFile(join(ctx.dir, '.basalt', 'releases.json'));
|
|
683
|
-
const target = join(stateDir, 'releases.json');
|
|
684
|
-
let history = 'no release history yet';
|
|
685
|
-
if (await host.exists(target)) {
|
|
686
|
-
history = 'release history kept as it was';
|
|
687
|
-
}
|
|
688
|
-
else if (local) {
|
|
689
|
-
await host.writeFile(target, local, 0o600);
|
|
690
|
-
const count = (() => { try {
|
|
691
|
-
const v = JSON.parse(local);
|
|
692
|
-
return Array.isArray(v) ? v.length : 0;
|
|
693
|
-
}
|
|
694
|
-
catch {
|
|
695
|
-
return 0;
|
|
696
|
-
} })();
|
|
697
|
-
history = `${count} release(s) copied from ${join(ctx.dir, '.basalt', 'releases.json')}`;
|
|
698
|
-
}
|
|
699
|
-
const chown = await host.exec('chown', ['-R', `${user}:`, stateDir]);
|
|
700
|
-
if (chown.code !== 0)
|
|
701
|
-
throw new DeployError(`chown ${user} ${stateDir}: ${chown.stderr.trim()}`);
|
|
702
|
-
host.out.ok(`${stateDir} (0700, owned by ${user}); ${history}`);
|
|
703
|
-
const overrides = `/etc/basalt/${config.app}.json`;
|
|
704
|
-
if (!(await host.exists(overrides))) {
|
|
705
|
-
await host.mkdir('/etc/basalt', 0o755);
|
|
706
|
-
await host.writeFile(overrides, '{}\n', 0o644);
|
|
707
|
-
host.out.ok(`${overrides} created (server-local overrides, no secrets)`);
|
|
708
|
-
}
|
|
709
|
-
});
|
|
710
|
-
await envOwnership(ctx, user);
|
|
711
|
-
if (config.proxy?.kind === 'apache' && config.proxy.managed !== false) {
|
|
712
|
-
await step(ctx, `Apache vhost ${vhostPaths(ctx).file}`, () => apacheInstall(ctx, port, join(stateDir, 'install-backups')));
|
|
870
|
+
else {
|
|
871
|
+
const process = (await pm2List(ctx))?.find((p) => p.name === processName(ctx.config));
|
|
872
|
+
host.out.info(process ? `pm2 ${process.name}: ${process.status} (pid ${process.pid}, ${process.cwd})` : `pm2 ${processName(ctx.config)}: not running`);
|
|
873
|
+
running = {
|
|
874
|
+
kind: 'pm2', name: processName(ctx.config), running: process?.status === 'online',
|
|
875
|
+
...(process?.status ? { status: process.status } : {}),
|
|
876
|
+
...(typeof process?.pid === 'number' ? { pid: process.pid } : {}),
|
|
877
|
+
};
|
|
713
878
|
}
|
|
714
|
-
if (
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
879
|
+
if (host.out.result) {
|
|
880
|
+
const active = activeRun(host, lock);
|
|
881
|
+
const last = await lastRun(host, ctx.stateDir);
|
|
882
|
+
host.out.result('status', {
|
|
883
|
+
app: ctx.config.app,
|
|
884
|
+
stateDir: ctx.stateDir,
|
|
885
|
+
lock: lock ? { ...(lock.holder ? { holder: lock.holder } : {}), stale: lock.stale, corrupt: lock.corrupt } : null,
|
|
886
|
+
...(active ? { activeRun: active } : {}),
|
|
887
|
+
...(last ? { lastRun: last } : {}),
|
|
888
|
+
hold: hold ?? null,
|
|
889
|
+
releases,
|
|
890
|
+
process: running,
|
|
891
|
+
});
|
|
725
892
|
}
|
|
726
|
-
host.out.ok(`installed — from now on, as ${user} (not root), in ${ctx.dir}: ${RUN_COMMAND}`);
|
|
727
893
|
return 0;
|
|
728
894
|
}
|