@hivemagnus/magnus 1.1.2 → 1.1.3
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 +13 -6
- package/dist/adopt.js +15 -3
- package/dist/cli.js +7 -0
- package/dist/database.d.ts +23 -2
- package/dist/database.js +167 -18
- package/dist/env-file.d.ts +5 -1
- package/dist/env-file.js +20 -5
- package/dist/health.d.ts +13 -0
- package/dist/health.js +36 -8
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/init.js +15 -7
- package/dist/install.d.ts +41 -3
- package/dist/install.js +112 -11
- package/dist/io.d.ts +10 -0
- package/dist/io.js +14 -2
- package/dist/main.d.ts +3 -1
- package/dist/main.js +32 -9
- package/dist/project.d.ts +77 -4
- package/dist/project.js +184 -17
- package/dist/release.d.ts +25 -3
- package/dist/release.js +70 -12
- package/dist/restore.d.ts +11 -0
- package/dist/restore.js +55 -0
- package/dist/rollback.d.ts +6 -0
- package/dist/rollback.js +79 -29
- package/dist/status.js +6 -2
- package/dist/supervisor.d.ts +21 -2
- package/dist/supervisor.js +74 -5
- package/dist/templates.d.ts +29 -3
- package/dist/templates.js +58 -7
- package/dist/upgrade.d.ts +33 -5
- package/dist/upgrade.js +415 -91
- package/package.json +46 -11
package/dist/upgrade.js
CHANGED
|
@@ -1,27 +1,45 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* `magnus upgrade`: install the target release next to the serving one,
|
|
3
|
-
* up, migrate,
|
|
4
|
-
* release that fails its health check is switched back automatically, and
|
|
2
|
+
* `magnus upgrade`: install the target release next to the serving one,
|
|
3
|
+
* check it, back up, migrate, switch `current`, restart and wait for health.
|
|
4
|
+
* A release that fails its health check is switched back automatically, and
|
|
5
5
|
* the restore command for the pre-migration dump is printed.
|
|
6
|
+
*
|
|
7
|
+
* From the backup on, magnus-project.json carries an in-progress journal, so
|
|
8
|
+
* an upgrade that was killed (or lost its terminal) is noticed by the next
|
|
9
|
+
* command, which offers `upgrade --resume` or `rollback`. SIGINT, SIGHUP and
|
|
10
|
+
* SIGTERM stop the upgrade at the next safe point; a running migration
|
|
11
|
+
* always finishes first.
|
|
6
12
|
*/
|
|
7
13
|
import { spawn } from 'node:child_process';
|
|
14
|
+
import { existsSync, statSync } from 'node:fs';
|
|
8
15
|
import { checkUpgradeAllowed, compareVersions, satisfiesRange, summarizeUpgradePath, } from '@hivemagnus/magnus-contracts';
|
|
9
|
-
import { backupDatabase } from './database.js';
|
|
16
|
+
import { backupDatabase, databaseBytes, pruneBackups, restoreCommandFor } from './database.js';
|
|
10
17
|
import { appendMissing, generateSecret, readEnvFile } from './env-file.js';
|
|
11
18
|
import { waitForHealthy } from './health.js';
|
|
12
|
-
import { installVersion,
|
|
13
|
-
import {
|
|
14
|
-
import {
|
|
15
|
-
import {
|
|
16
|
-
import {
|
|
19
|
+
import { installVersion, isInstalled, migrationReport, nodeVersionOf, npmFor, publishPins, pruneVersions, removeStaleStaging, serverCli, smokeTest, } from './install.js';
|
|
20
|
+
import { acquireLock, ownerOf, Project } from './project.js';
|
|
21
|
+
import { ENGINE_PROTOCOL, fetchRegistryCatalog, newerMajor, pickTarget, releaseFor, sourceCatalog, TooOldError } from './release.js';
|
|
22
|
+
import { checkSupervisor, manualRestartHint, refreshUnits, restartServices, stopServices } from './supervisor.js';
|
|
23
|
+
import { projectEnv } from './templates.js';
|
|
17
24
|
export class UpgradeError extends Error {
|
|
18
25
|
}
|
|
26
|
+
export class InterruptedError extends UpgradeError {
|
|
27
|
+
}
|
|
28
|
+
/** Free space an npm install of one release needs. */
|
|
29
|
+
export const INSTALL_BYTES = 1024 ** 3;
|
|
19
30
|
export async function loadCatalog(io, options) {
|
|
20
31
|
return options.source ? sourceCatalog(io, options.source, options.registry) : fetchRegistryCatalog(io, options.registry);
|
|
21
32
|
}
|
|
22
33
|
export function requirePrivileges(io, project) {
|
|
23
|
-
if (project.state.supervisor === 'systemd' && project.state.scope === 'system'
|
|
24
|
-
|
|
34
|
+
if (project.state.supervisor === 'systemd' && project.state.scope === 'system') {
|
|
35
|
+
if (!io.isRoot)
|
|
36
|
+
throw new UpgradeError(`This project runs system services; run the command as root (sudo magnus … --dir ${project.dir}).`);
|
|
37
|
+
return;
|
|
38
|
+
}
|
|
39
|
+
// User units belong to the account that owns the project; root (sudo) has no session bus for them and would leave root-owned files.
|
|
40
|
+
const owner = ownerOf(Project.file(project.dir));
|
|
41
|
+
if (io.uid !== null && owner !== null && io.uid !== owner) {
|
|
42
|
+
throw new UpgradeError(`${project.dir} belongs to uid ${owner}, but this is uid ${io.uid}. Run magnus as the account that owns the project (without sudo).`);
|
|
25
43
|
}
|
|
26
44
|
}
|
|
27
45
|
/** New required variables that the project's env files do not set yet. */
|
|
@@ -67,17 +85,119 @@ async function confirmAttention(io, migrations, yes) {
|
|
|
67
85
|
throw new UpgradeError('Stopped: slow or one-way migrations need confirmation. Re-run with --yes when you are ready (the database is backed up first).');
|
|
68
86
|
}
|
|
69
87
|
}
|
|
88
|
+
function logsHint(project) {
|
|
89
|
+
return project.state.supervisor === 'systemd'
|
|
90
|
+
? `journalctl ${project.state.scope === 'user' ? '--user ' : ''}-u ${project.state.units.server} -n 100`
|
|
91
|
+
: 'see your service manager';
|
|
92
|
+
}
|
|
93
|
+
/** What the next command says about an interrupted upgrade. */
|
|
94
|
+
export function journalMessage(project, journal) {
|
|
95
|
+
const dir = project.dir;
|
|
96
|
+
return [
|
|
97
|
+
`An upgrade ${journal.from} -> ${journal.to} was interrupted during "${journal.phase}" (started ${journal.startedAt} by pid ${journal.pid}); ./current points at ${project.linkedVersion() ?? 'nothing'}.`,
|
|
98
|
+
` magnus upgrade --resume --dir ${dir} finish it (runs the remaining steps again)`,
|
|
99
|
+
` magnus rollback --dir ${dir} go back to ${journal.from}${journal.backup ? ` (add --restore-db to restore ${journal.backup})` : ''}`,
|
|
100
|
+
].join('\n');
|
|
101
|
+
}
|
|
102
|
+
const SIGNALS = ['SIGINT', 'SIGHUP', 'SIGTERM'];
|
|
103
|
+
function trapSignals(io) {
|
|
104
|
+
let received = null;
|
|
105
|
+
let reverting = false;
|
|
106
|
+
const handler = (signal) => {
|
|
107
|
+
if (reverting) {
|
|
108
|
+
io.warn(` ${signal}: switching back, please wait`);
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
if (received)
|
|
112
|
+
return;
|
|
113
|
+
received = signal;
|
|
114
|
+
io.warn(` ${signal}: stopping at the next safe step (a running migration always finishes first)`);
|
|
115
|
+
};
|
|
116
|
+
// A closed terminal (SIGHUP) must not crash the upgrade through a failed write.
|
|
117
|
+
const ignore = () => undefined;
|
|
118
|
+
const handlers = SIGNALS.map((signal) => [signal, () => handler(signal)]);
|
|
119
|
+
for (const [signal, listener] of handlers)
|
|
120
|
+
process.on(signal, listener);
|
|
121
|
+
process.stdout.on('error', ignore);
|
|
122
|
+
process.stderr.on('error', ignore);
|
|
123
|
+
return {
|
|
124
|
+
get signal() { return received; },
|
|
125
|
+
checkpoint() { if (received)
|
|
126
|
+
throw new InterruptedError(`Interrupted (${received}).`); },
|
|
127
|
+
reverting() { reverting = true; },
|
|
128
|
+
dispose() {
|
|
129
|
+
for (const [signal, listener] of handlers)
|
|
130
|
+
process.off(signal, listener);
|
|
131
|
+
process.stdout.off('error', ignore);
|
|
132
|
+
process.stderr.off('error', ignore);
|
|
133
|
+
},
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
/** Same file system: one free-space budget. */
|
|
137
|
+
function sameDevice(a, b) {
|
|
138
|
+
try {
|
|
139
|
+
return statSync(a).dev === statSync(b).dev;
|
|
140
|
+
}
|
|
141
|
+
catch {
|
|
142
|
+
return false;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
function gib(bytes) {
|
|
146
|
+
return `${(bytes / 1024 ** 3).toFixed(1)} GiB`;
|
|
147
|
+
}
|
|
148
|
+
/** Free space for the npm install (and, when `dumpBytes` is given, the dump). Returns problems. */
|
|
149
|
+
export function diskProblems(io, project, needs) {
|
|
150
|
+
const problems = [];
|
|
151
|
+
const versions = existsSync(project.path('versions')) ? project.path('versions') : project.dir;
|
|
152
|
+
const backups = existsSync(project.path('backups')) ? project.path('backups') : project.dir;
|
|
153
|
+
const install = needs.install ? INSTALL_BYTES : 0;
|
|
154
|
+
const dump = needs.dumpBytes ?? 0;
|
|
155
|
+
const shared = sameDevice(versions, backups);
|
|
156
|
+
const checks = shared ? [{ path: versions, bytes: install + dump, what: 'the install and the database dump' }]
|
|
157
|
+
: [{ path: versions, bytes: install, what: 'the install' }, { path: backups, bytes: dump, what: 'the database dump' }];
|
|
158
|
+
for (const check of checks) {
|
|
159
|
+
if (check.bytes === 0)
|
|
160
|
+
continue;
|
|
161
|
+
const free = io.freeBytes(check.path);
|
|
162
|
+
if (free !== null && free < check.bytes) {
|
|
163
|
+
problems.push(`${check.path} has ${gib(free)} free; ${check.what} need about ${gib(check.bytes)}. Free some space (old dumps are in ${project.path('backups')}).`);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
return problems;
|
|
167
|
+
}
|
|
70
168
|
export async function upgrade(io, options) {
|
|
71
169
|
const project = Project.load(options.dir);
|
|
72
170
|
requirePrivileges(io, project);
|
|
73
|
-
let
|
|
171
|
+
let lock = acquireLock(project.path('run', 'upgrade.lock'), {
|
|
172
|
+
inheritToken: io.env['MAGNUS_LOCK_TOKEN'], breakLock: options.breakLock, command: 'magnus upgrade',
|
|
173
|
+
});
|
|
74
174
|
try {
|
|
175
|
+
const journal = project.state.inProgress;
|
|
176
|
+
if (journal) {
|
|
177
|
+
if (!options.resume)
|
|
178
|
+
throw new UpgradeError(journalMessage(project, journal));
|
|
179
|
+
if (options.to && options.to !== journal.to)
|
|
180
|
+
throw new UpgradeError(`The interrupted upgrade was to ${journal.to}, not ${options.to}.\n${journalMessage(project, journal)}`);
|
|
181
|
+
return await resumeJournal(io, project, journal, options);
|
|
182
|
+
}
|
|
75
183
|
const current = project.state.current;
|
|
76
184
|
if (!current)
|
|
77
185
|
throw new UpgradeError(`${project.dir} has no serving version; run \`magnus init\` again or \`magnus adopt\`.`);
|
|
186
|
+
if (options.nodePath) {
|
|
187
|
+
if (!existsSync(options.nodePath))
|
|
188
|
+
throw new UpgradeError(`--node ${options.nodePath} does not exist`);
|
|
189
|
+
project.state.nodePath = options.nodePath;
|
|
190
|
+
}
|
|
191
|
+
if (!options.dryRun) {
|
|
192
|
+
const stale = removeStaleStaging(project);
|
|
193
|
+
if (stale.length)
|
|
194
|
+
io.log(` removed unfinished installs: ${stale.join(', ')}`);
|
|
195
|
+
}
|
|
78
196
|
const catalog = await loadCatalog(io, options);
|
|
79
197
|
const target = pickTarget(catalog, current, options.to);
|
|
80
198
|
if (target === current) {
|
|
199
|
+
if (options.nodePath && !options.dryRun)
|
|
200
|
+
return await switchNode(io, project, current, options);
|
|
81
201
|
io.log(`Already on ${current}, the newest ${current.split('.')[0]}.x release.`);
|
|
82
202
|
const major = newerMajor(catalog, current);
|
|
83
203
|
if (major)
|
|
@@ -87,12 +207,24 @@ export async function upgrade(io, options) {
|
|
|
87
207
|
const decision = checkUpgradeAllowed(current, target, { allowMajor: options.allowMajor });
|
|
88
208
|
if (!decision.allowed)
|
|
89
209
|
throw new UpgradeError(decision.reason ?? 'upgrade not allowed');
|
|
90
|
-
|
|
210
|
+
let manifest;
|
|
211
|
+
try {
|
|
212
|
+
manifest = releaseFor(catalog, target);
|
|
213
|
+
}
|
|
214
|
+
catch (error) {
|
|
215
|
+
if (error instanceof TooOldError)
|
|
216
|
+
throw new UpgradeError(error.message);
|
|
217
|
+
throw error;
|
|
218
|
+
}
|
|
91
219
|
const path = summarizeUpgradePath(catalog.manifests.values(), current, target);
|
|
92
|
-
if (path.blockedBy)
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
220
|
+
if (path.blockedBy) {
|
|
221
|
+
const step = path.releases.find((release) => release.minUpgradeFrom && compareVersions(current, release.minUpgradeFrom) < 0)?.minUpgradeFrom;
|
|
222
|
+
throw new UpgradeError(`Cannot upgrade directly: ${path.blockedBy}.${step ? ` Upgrade in two steps: magnus upgrade --to ${step}, then magnus upgrade.` : ''}`);
|
|
223
|
+
}
|
|
224
|
+
const nodePath = project.nodePath();
|
|
225
|
+
const nodeVersion = await nodeVersionOf(io, nodePath).catch((error) => { throw new UpgradeError(error instanceof Error ? error.message : String(error)); });
|
|
226
|
+
if (!satisfiesRange(nodeVersion, manifest.engines.node)) {
|
|
227
|
+
throw new UpgradeError(`${target} needs Node.js ${manifest.engines.node}; the services run ${nodePath} (${nodeVersion}). Install a supported Node.js and pass --node <path>.`);
|
|
96
228
|
}
|
|
97
229
|
describePath(io, path, decision.kind);
|
|
98
230
|
const missing = missingEnv(project, path.newRequiredEnv);
|
|
@@ -106,120 +238,312 @@ export async function upgrade(io, options) {
|
|
|
106
238
|
].join('\n'));
|
|
107
239
|
}
|
|
108
240
|
}
|
|
241
|
+
const problems = [];
|
|
242
|
+
await checkSupervisor(io, project.state.supervisor, project.state.scope).catch((error) => {
|
|
243
|
+
problems.push(error instanceof Error ? error.message : String(error));
|
|
244
|
+
});
|
|
245
|
+
const installed = isInstalled(project, target);
|
|
246
|
+
problems.push(...diskProblems(io, project, { install: !installed, dumpBytes: options.dryRun ? await estimateDump(io, project, current) : null }));
|
|
109
247
|
if (options.dryRun) {
|
|
110
|
-
|
|
248
|
+
problems.push(...await dryRunChecks(io, project, current, nodePath));
|
|
249
|
+
if (problems.length) {
|
|
250
|
+
io.warn(['Dry run found problems to fix before upgrading:', ...problems.map((problem) => ` - ${problem}`)].join('\n'));
|
|
251
|
+
return 1;
|
|
252
|
+
}
|
|
253
|
+
io.log(`Dry run: would install ${target} into versions/${target}, check it, back up the database, migrate, switch ./current and restart. Prerequisites look fine; nothing changed.`);
|
|
111
254
|
return 0;
|
|
112
255
|
}
|
|
256
|
+
if (problems.length)
|
|
257
|
+
throw new UpgradeError(['Stopped before changing anything:', ...problems.map((problem) => ` - ${problem}`)].join('\n'));
|
|
113
258
|
for (const component of ['server', 'ui']) {
|
|
114
259
|
const names = appendMissing(project.envFile(component), missing.filter((env) => env.component === component)
|
|
115
260
|
.map((env) => ({ name: env.name, value: generateSecret(), comment: env.description })), `Added by magnus upgrade to ${target}`);
|
|
116
261
|
if (names.length)
|
|
117
262
|
io.log(` generated ${names.join(', ')} in ${project.envFile(component)}`);
|
|
118
263
|
}
|
|
264
|
+
const located = appendMissing(project.envFile('server'), projectEnv(project.dir, project.path('run', 'server-runtime.json')), `Added by magnus upgrade to ${target}`);
|
|
265
|
+
if (located.length)
|
|
266
|
+
io.log(` added ${located.join(', ')} to ${project.envFile('server')}`);
|
|
267
|
+
project.save();
|
|
119
268
|
await installVersion(io, project, manifest, catalog);
|
|
120
269
|
if (manifest.engineProtocol > ENGINE_PROTOCOL && !options.resume) {
|
|
121
270
|
io.log(` handing over to the ${target} upgrade engine`);
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
271
|
+
// The child takes this lock over (MAGNUS_LOCK_TOKEN); it is never free in between.
|
|
272
|
+
const token = lock.token;
|
|
273
|
+
lock = () => undefined;
|
|
274
|
+
return await handOver(project, target, options, token);
|
|
125
275
|
}
|
|
126
276
|
return await applyInstalled(io, project, current, target, options);
|
|
127
277
|
}
|
|
128
278
|
finally {
|
|
129
|
-
|
|
279
|
+
lock();
|
|
130
280
|
}
|
|
131
281
|
}
|
|
132
|
-
|
|
282
|
+
/** Upper bound of the pre-migration dump: the database size. */
|
|
283
|
+
async function estimateDump(io, project, current) {
|
|
284
|
+
if (project.state.database.kind === 'compose')
|
|
285
|
+
return databaseBytes(io, project);
|
|
286
|
+
return (await migrationReport(io, project, current).catch(() => null))?.databaseBytes ?? null;
|
|
287
|
+
}
|
|
288
|
+
/** pg_dump, npm and the services' Node.js, without changing anything. */
|
|
289
|
+
async function dryRunChecks(io, project, current, nodePath) {
|
|
290
|
+
const problems = [];
|
|
291
|
+
const npm = npmFor(nodePath);
|
|
292
|
+
const npmVersion = await io.run(npm.command, [...npm.prefix, '--version'], { capture: true }).catch(() => null);
|
|
293
|
+
if (!npmVersion || npmVersion.code !== 0)
|
|
294
|
+
problems.push(`npm cannot be run (${npm.command}); it installs the new release.`);
|
|
295
|
+
if (project.state.database.kind === 'external') {
|
|
296
|
+
const env = readEnvFile(project.envFile('server'));
|
|
297
|
+
const pgDump = env['MAGNUS_PG_DUMP'] ?? io.env['MAGNUS_PG_DUMP'] ?? 'pg_dump';
|
|
298
|
+
const result = await io.run(pgDump, ['--version'], { capture: true }).catch(() => null);
|
|
299
|
+
const major = Number(/(\d+)/.exec(result?.stdout ?? '')?.[1]);
|
|
300
|
+
if (!result || result.code !== 0 || !Number.isFinite(major)) {
|
|
301
|
+
problems.push(`${pgDump} is not installed; the pre-migration backup needs the PostgreSQL client tools (or MAGNUS_PG_DUMP in ${project.envFile('server')}).`);
|
|
302
|
+
}
|
|
303
|
+
else {
|
|
304
|
+
const server = (await migrationReport(io, project, current).catch(() => null))?.postgresMajor ?? null;
|
|
305
|
+
if (server !== null && major < server)
|
|
306
|
+
problems.push(`${pgDump} is PostgreSQL ${major} but the database runs PostgreSQL ${server}; install the ${server} client and set MAGNUS_PG_DUMP.`);
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
return problems;
|
|
310
|
+
}
|
|
311
|
+
function handOver(project, target, options, token) {
|
|
133
312
|
const args = [project.bin(target, 'magnus'), 'upgrade', '--resume', '--dir', project.dir, '--to', target,
|
|
134
313
|
'--registry', options.registry, '--health-timeout', String(Math.round(options.healthTimeoutMs / 1000))];
|
|
135
314
|
if (options.yes)
|
|
136
315
|
args.push('--yes');
|
|
137
316
|
if (options.allowMajor)
|
|
138
317
|
args.push('--allow-major');
|
|
318
|
+
if (options.force)
|
|
319
|
+
args.push('--force');
|
|
139
320
|
if (options.source)
|
|
140
321
|
args.push('--source', options.source);
|
|
141
322
|
return new Promise((resolve, reject) => {
|
|
142
|
-
const child = spawn(
|
|
143
|
-
child
|
|
144
|
-
|
|
323
|
+
const child = spawn(project.nodePath(), args, { stdio: 'inherit', env: { ...process.env, MAGNUS_LOCK_TOKEN: token } });
|
|
324
|
+
// The child handles signals itself (it shares the terminal); this process only waits.
|
|
325
|
+
const ignore = () => undefined;
|
|
326
|
+
for (const signal of SIGNALS)
|
|
327
|
+
process.on(signal, ignore);
|
|
328
|
+
const done = () => { for (const signal of SIGNALS)
|
|
329
|
+
process.off(signal, ignore); };
|
|
330
|
+
child.on('error', (error) => { done(); reject(error); });
|
|
331
|
+
child.on('close', (code) => { done(); resolve(code ?? 1); });
|
|
145
332
|
});
|
|
146
333
|
}
|
|
147
|
-
/**
|
|
148
|
-
|
|
149
|
-
const
|
|
334
|
+
/** `upgrade --node PATH` on the serving version: rewrite the units and restart. */
|
|
335
|
+
async function switchNode(io, project, current, options) {
|
|
336
|
+
const version = await nodeVersionOf(io, project.nodePath()).catch((error) => { throw new UpgradeError(error instanceof Error ? error.message : String(error)); });
|
|
337
|
+
const problems = await smokeTest(io, project, current);
|
|
338
|
+
if (problems.length)
|
|
339
|
+
throw new UpgradeError([`${current} does not start on ${project.nodePath()} (${version}); nothing changed:`, ...problems.map((p) => ` ${p}`)].join('\n'));
|
|
340
|
+
await checkSupervisor(io, project.state.supervisor, project.state.scope);
|
|
341
|
+
project.save();
|
|
342
|
+
for (const file of refreshUnits(io, project, project.state.nodePath))
|
|
343
|
+
io.log(` updated ${file}`);
|
|
344
|
+
const restartedAt = io.now();
|
|
345
|
+
await restartServices(io, project);
|
|
346
|
+
const health = await waitForHealthy(io, project, { version: current, startedAfter: restartedAt, timeoutMs: options.healthTimeoutMs });
|
|
347
|
+
if (!health.ok) {
|
|
348
|
+
io.warn(`${current} on ${project.nodePath()} is ${health.detail}. Logs: ${logsHint(project)}`);
|
|
349
|
+
return 1;
|
|
350
|
+
}
|
|
351
|
+
io.log(`Services now run Node.js ${version} (${project.nodePath()}): ${health.detail}.`);
|
|
352
|
+
return 0;
|
|
353
|
+
}
|
|
354
|
+
/** Finish an upgrade the journal says was interrupted: back to the "from serving" state, then the normal steps. */
|
|
355
|
+
async function resumeJournal(io, project, journal, options) {
|
|
356
|
+
io.log(`Resuming the interrupted upgrade ${journal.from} -> ${journal.to} (it stopped during "${journal.phase}")`);
|
|
357
|
+
if (!isInstalled(project, journal.to) || !isInstalled(project, journal.from)) {
|
|
358
|
+
throw new UpgradeError(`versions/${isInstalled(project, journal.to) ? journal.from : journal.to} is missing, so the upgrade cannot be resumed. Use \`magnus rollback --dir ${project.dir}\`.`);
|
|
359
|
+
}
|
|
360
|
+
if (project.linkedVersion() !== journal.from)
|
|
361
|
+
project.switchCurrent(journal.from);
|
|
362
|
+
project.state.current = journal.from;
|
|
363
|
+
project.state.previous = project.state.history.findLast((entry) => entry.to === journal.from && entry.result === 'ok')?.from ?? project.state.previous;
|
|
364
|
+
delete project.state.inProgress;
|
|
365
|
+
project.save();
|
|
366
|
+
return applyInstalled(io, project, journal.from, journal.to, options, journal.backup ? { backup: { file: journal.backup, restoreCommand: restoreCommandFor(project, journal.backup) }, oneWay: journal.oneWay, migrations: journal.migrations } : undefined);
|
|
367
|
+
}
|
|
368
|
+
/** Every migration history marks one-way (the impact the manifest gave when it was applied). */
|
|
369
|
+
export function knownOneWay(project) {
|
|
370
|
+
return new Set(project.state.history.flatMap((entry) => entry.oneWay ?? []));
|
|
371
|
+
}
|
|
372
|
+
/** Check, back up, migrate, switch, restart, verify; revert on failure. */
|
|
373
|
+
export async function applyInstalled(io, project, current, target, options, prior) {
|
|
374
|
+
const report = await migrationReport(io, project, target);
|
|
375
|
+
if (report.failed.length) {
|
|
376
|
+
throw new UpgradeError([
|
|
377
|
+
`Stopped before changing anything: migration(s) ${report.failed.join(', ')} failed earlier and are still marked failed in the database, which may be half-migrated.`,
|
|
378
|
+
`Restore the dump taken before that attempt (${prior ? restoreCommandFor(project, prior.backup.file) : `magnus restore <dump in ${project.path('backups')}> --dir ${project.dir}`}),`,
|
|
379
|
+
'or repair the schema and mark the migration with `npx prisma migrate resolve --rolled-back <name>` (or `--applied <name>`).',
|
|
380
|
+
].join('\n'));
|
|
381
|
+
}
|
|
382
|
+
const pending = report.pending;
|
|
150
383
|
await confirmAttention(io, pending, options.yes);
|
|
151
|
-
|
|
384
|
+
io.log(` checking ${target} before touching the database`);
|
|
385
|
+
const problems = await smokeTest(io, project, target);
|
|
386
|
+
if (problems.length) {
|
|
387
|
+
throw new UpgradeError([`${target} failed its checks; nothing changed and ${current} is still serving:`, ...problems.map((problem) => ` ${problem}`)].join('\n'));
|
|
388
|
+
}
|
|
389
|
+
try {
|
|
390
|
+
await checkSupervisor(io, project.state.supervisor, project.state.scope);
|
|
391
|
+
}
|
|
392
|
+
catch (error) {
|
|
393
|
+
throw new UpgradeError(`Stopped before changing anything: ${error instanceof Error ? error.message : String(error)}`);
|
|
394
|
+
}
|
|
152
395
|
if (pending.length > 0) {
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
396
|
+
const space = diskProblems(io, project, { install: false, dumpBytes: report.databaseBytes ?? await databaseBytes(io, project) });
|
|
397
|
+
if (space.length)
|
|
398
|
+
throw new UpgradeError(['Stopped before the backup:', ...space.map((problem) => ` ${problem}`)].join('\n'));
|
|
399
|
+
}
|
|
400
|
+
const migrations = [...new Set([...(prior?.migrations ?? []), ...pending.map((m) => m.name)])];
|
|
401
|
+
const oneWay = [...new Set([...(prior?.oneWay ?? []), ...pending.filter((m) => m.impact === 'one-way').map((m) => m.name)])];
|
|
402
|
+
const journal = { phase: 'backup', from: current, to: target, migrations, oneWay, startedAt: io.now().toISOString(), pid: process.pid,
|
|
403
|
+
...(prior ? { backup: prior.backup.file } : {}) };
|
|
404
|
+
const step = (phase) => {
|
|
405
|
+
journal.phase = phase;
|
|
406
|
+
project.state.inProgress = journal;
|
|
407
|
+
project.save();
|
|
408
|
+
};
|
|
409
|
+
const entry = (result, reason) => ({
|
|
410
|
+
action: 'upgrade', from: current, to: target, at: io.now().toISOString(), result, migrations,
|
|
411
|
+
...(backup ? { backup: backup.file, restoreCommand: backup.restoreCommand } : {}), ...(oneWay.length ? { oneWay } : {}), ...(reason ? { reason } : {}),
|
|
412
|
+
});
|
|
413
|
+
const finish = (record) => {
|
|
414
|
+
delete project.state.inProgress;
|
|
415
|
+
project.record(record);
|
|
416
|
+
project.save();
|
|
417
|
+
};
|
|
418
|
+
let backup = prior?.backup;
|
|
419
|
+
const trap = trapSignals(io);
|
|
420
|
+
let switched = false;
|
|
421
|
+
try {
|
|
422
|
+
step('backup');
|
|
423
|
+
if (pending.length > 0) {
|
|
424
|
+
trap.checkpoint();
|
|
425
|
+
backup = await backupDatabase(io, project, target, `pre-upgrade-${current}-to-${target}`).catch((error) => {
|
|
426
|
+
throw new UpgradeError(`Stopped before migrating: the database backup failed. ${error instanceof Error ? error.message : String(error)}`);
|
|
427
|
+
});
|
|
428
|
+
journal.backup = backup.file;
|
|
429
|
+
io.log(` backup: ${backup.file}`);
|
|
430
|
+
trap.checkpoint();
|
|
431
|
+
step('migrate');
|
|
432
|
+
io.log(` applying ${pending.length} migration(s) (${current} keeps serving meanwhile)`);
|
|
433
|
+
try {
|
|
434
|
+
// Its own process group: a Ctrl-C now waits for the migration instead of killing it halfway.
|
|
435
|
+
await serverCli(io, project, target, ['migrate'], { detached: true });
|
|
436
|
+
}
|
|
437
|
+
catch (error) {
|
|
438
|
+
throw new UpgradeError([
|
|
439
|
+
`Migration to ${target} failed; ${current} is still serving. ${error instanceof Error ? error.message : String(error)}`,
|
|
440
|
+
'If the database was left half-migrated, restore the backup (it stops and restarts the services):',
|
|
441
|
+
` ${backup.restoreCommand}`,
|
|
442
|
+
].join('\n'));
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
else {
|
|
446
|
+
io.log(' no database migrations');
|
|
447
|
+
}
|
|
448
|
+
trap.checkpoint();
|
|
449
|
+
step('switch');
|
|
450
|
+
project.state.previous = current;
|
|
451
|
+
project.state.current = target;
|
|
452
|
+
project.switchCurrent(target);
|
|
453
|
+
switched = true;
|
|
454
|
+
step('restart');
|
|
455
|
+
for (const file of refreshUnits(io, project, project.state.nodePath))
|
|
456
|
+
io.log(` updated ${file}`);
|
|
457
|
+
io.log(` switched ./current to ${target}; restarting`);
|
|
458
|
+
const restartedAt = io.now();
|
|
459
|
+
let health;
|
|
158
460
|
try {
|
|
159
|
-
await
|
|
461
|
+
await restartServices(io, project);
|
|
462
|
+
step('health');
|
|
463
|
+
health = await waitForHealthy(io, project, { version: target, startedAfter: restartedAt, timeoutMs: options.healthTimeoutMs, abort: () => trap.signal !== null });
|
|
160
464
|
}
|
|
161
465
|
catch (error) {
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
io.log('
|
|
174
|
-
|
|
175
|
-
const check = await serverCli(io, project, target, ['check', '--format', 'json'], { capture: true })
|
|
176
|
-
.then((result) => result.stdout)
|
|
177
|
-
.catch((error) => (error instanceof CommandError ? error.result?.stdout ?? '' : ''));
|
|
178
|
-
const failures = (JSON.parse(check || '{"results":[]}').results ?? [])
|
|
179
|
-
.filter((result) => result.status === 'fail');
|
|
180
|
-
if (failures.length > 0) {
|
|
181
|
-
throw new UpgradeError([
|
|
182
|
-
`${target} failed its configuration check; ${current} is still serving:`,
|
|
183
|
-
...failures.map((failure) => ` ${failure.name}: ${failure.message}`),
|
|
184
|
-
...(backup ? ['The database was migrated. If the old version misbehaves, restore with:', ` ${backup.restoreCommand}`] : []),
|
|
185
|
-
].join('\n'));
|
|
466
|
+
health = { ok: false, detail: `the restart failed: ${error instanceof Error ? error.message : String(error)}` };
|
|
467
|
+
}
|
|
468
|
+
if (trap.signal && !health.ok)
|
|
469
|
+
health = { ok: false, detail: `interrupted (${trap.signal}) before it became healthy` };
|
|
470
|
+
if (!health.ok)
|
|
471
|
+
return await revert(io, project, { current, target, backup, oneWay, reason: health.detail, options, trap, entry, finish });
|
|
472
|
+
publishPins(project, target);
|
|
473
|
+
const pruned = pruneVersions(project, project.state.keepVersions, compareVersions);
|
|
474
|
+
const dumps = pruneBackups(project.path('backups'), project.keepBackups(), backup ? [backup.file] : []);
|
|
475
|
+
finish(entry('ok'));
|
|
476
|
+
io.log(`Upgraded to ${target}: ${health.detail}.${pruned.length ? ` Removed old versions ${pruned.join(', ')}.` : ''}${dumps.length ? ` Removed ${dumps.length} old dump(s).` : ''}`);
|
|
477
|
+
io.log('Agents keep running their version until you upgrade them: `magnus-server agents upgrade` or the "Upgrade agents" button on the Nodes page.');
|
|
478
|
+
return 0;
|
|
186
479
|
}
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
480
|
+
catch (error) {
|
|
481
|
+
if (switched && project.state.inProgress) {
|
|
482
|
+
return await revert(io, project, { current, target, backup, oneWay, reason: error instanceof Error ? error.message : String(error), options, trap, entry, finish });
|
|
483
|
+
}
|
|
484
|
+
if (project.state.inProgress) {
|
|
485
|
+
const migrated = journal.phase !== 'backup';
|
|
486
|
+
const interrupted = error instanceof InterruptedError || trap.signal !== null;
|
|
487
|
+
finish(entry('failed', interrupted ? `interrupted (${trap.signal})` : (migrated ? 'migration failed' : 'stopped before migrating')));
|
|
488
|
+
if (interrupted) {
|
|
489
|
+
io.warn([
|
|
490
|
+
`Upgrade to ${target} stopped (${trap.signal}); ${current} is still serving.`,
|
|
491
|
+
...(migrated && backup ? [`The database was migrated. ${current} normally works with the newer schema; to undo it: ${backup.restoreCommand}`] : []),
|
|
492
|
+
].join('\n'));
|
|
493
|
+
return 130;
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
throw error;
|
|
497
|
+
}
|
|
498
|
+
finally {
|
|
499
|
+
trap.dispose();
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
/**
|
|
503
|
+
* Switch back to the version that served before. Over one-way migrations the
|
|
504
|
+
* old version is not started (unless --force): only the dump undoes them.
|
|
505
|
+
* The restore hint is printed whatever happens here.
|
|
506
|
+
*/
|
|
507
|
+
async function revert(io, project, context) {
|
|
508
|
+
const { current, target, backup, oneWay, options } = context;
|
|
509
|
+
context.trap.reverting();
|
|
510
|
+
io.warn(` ${target} is ${context.reason}; switching back to ${current}`);
|
|
511
|
+
let back = { ok: false, detail: 'not restarted' };
|
|
512
|
+
const blocked = oneWay.length > 0 && !options.force;
|
|
513
|
+
try {
|
|
514
|
+
project.state.inProgress = { ...project.state.inProgress, phase: 'revert' };
|
|
515
|
+
project.save();
|
|
198
516
|
project.switchCurrent(current);
|
|
199
517
|
project.state.current = current;
|
|
200
518
|
project.state.previous = project.state.history.findLast((entry) => entry.to === current && entry.result === 'ok')?.from ?? null;
|
|
201
|
-
project.record({ action: 'upgrade', from: current, to: target, at: io.now().toISOString(), result: 'reverted', migrations,
|
|
202
|
-
...(backup ? { backup: backup.file, restoreCommand: backup.restoreCommand } : {}), reason: health.detail });
|
|
203
519
|
project.save();
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
520
|
+
if (blocked) {
|
|
521
|
+
await stopServices(io, project, { timeoutMs: 60_000 }).catch((error) => {
|
|
522
|
+
io.warn(` could not stop the services: ${error instanceof Error ? error.message : String(error)}`);
|
|
523
|
+
});
|
|
524
|
+
back = { ok: false, detail: `not started: ${target} applied one-way migration(s) ${oneWay.join(', ')}, which ${current} cannot run on` };
|
|
525
|
+
}
|
|
526
|
+
else {
|
|
527
|
+
const revertedAt = io.now();
|
|
528
|
+
await restartServices(io, project);
|
|
529
|
+
back = await waitForHealthy(io, project, { version: current, startedAfter: revertedAt, timeoutMs: options.healthTimeoutMs });
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
catch (error) {
|
|
533
|
+
back = { ok: false, detail: `the restart failed: ${error instanceof Error ? error.message : String(error)}` };
|
|
534
|
+
}
|
|
535
|
+
finally {
|
|
536
|
+
context.finish(context.entry('reverted', context.reason));
|
|
207
537
|
io.warn([
|
|
208
|
-
`Upgrade to ${target} failed and was reverted; ${current} is ${back.ok ? 'serving again' : `NOT
|
|
209
|
-
...(backup ?
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
538
|
+
`Upgrade to ${target} failed and was reverted; ${current} is ${back.ok ? 'serving again' : `NOT serving (${back.detail})`}.`,
|
|
539
|
+
...(backup ? (blocked
|
|
540
|
+
? [`Restore the pre-upgrade dump; it starts ${current} afterwards:`, ` ${backup.restoreCommand}`,
|
|
541
|
+
`To start ${current} on the migrated database anyway: ${manualRestartHint(project)}`]
|
|
542
|
+
: [`${target} migrated the database. ${current} normally works with the newer schema; if it does not, restore the dump (it stops and restarts the services):`,
|
|
543
|
+
` ${backup.restoreCommand}`])
|
|
544
|
+
: []),
|
|
545
|
+
`Logs: ${logsHint(project)}`,
|
|
214
546
|
].join('\n'));
|
|
215
|
-
return 1;
|
|
216
547
|
}
|
|
217
|
-
|
|
218
|
-
...(backup ? { backup: backup.file, restoreCommand: backup.restoreCommand } : {}) });
|
|
219
|
-
publishPins(project, target);
|
|
220
|
-
const pruned = pruneVersions(project, project.state.keepVersions, compareVersions);
|
|
221
|
-
project.save();
|
|
222
|
-
io.log(`Upgraded to ${target}: ${health.detail}.${pruned.length ? ` Removed old versions ${pruned.join(', ')}.` : ''}`);
|
|
223
|
-
io.log('Agents keep running their version until you upgrade them: `magnus-server agents upgrade` or the "Upgrade agents" button on the Nodes page.');
|
|
224
|
-
return 0;
|
|
548
|
+
return 1;
|
|
225
549
|
}
|