diff --git a/CHANGELOG.md b/CHANGELOG.md index 3c3d3e2..604209b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- **Upgrading from 1.9.0 no longer fails when another VS Code window is open.** Every window + running GemDB keeps a session on the database, even with no notebook open, so the upgrade could + not stop it and told you to close notebooks and GemDB Shells you did not have. It now asks, as + **Stop GemDB** does, whether to disconnect those sessions. And **Stop GemDB** stops a database the + previous engine started with that engine's tools: with the new engine's, it failed with "The Gem + and Stone versions are incompatible", and the only way out was reinstalling 1.9.0. - **`gemdb file.py` writes Python's `sys.stderr` to stderr.** Warnings, tracebacks printed from Python, logging and `print(..., file=sys.stderr)` went to stdout, so `2>` and pipes saw them in the wrong stream. diff --git a/docs/automation-boundary.md b/docs/automation-boundary.md index 1bfd0c8..0a1c334 100644 --- a/docs/automation-boundary.md +++ b/docs/automation-boundary.md @@ -237,6 +237,16 @@ unanswered, and the upgrade stops the database for minutes. Python support and the MCP server are then installed again without a second question: the upgrade removed their compiled methods, and the question already said so. +Stopping the previous engine's stone for the upgrade is Stop's own path +(`runStop`), question included: a stone other sessions are logged in to is +force-stopped only after **Stop Anyway**, as it would be by Stop. Those +sessions are usually other VS Code windows, each of which keeps one even with +no notebook open, and a window not reloaded since the update is still the +previous GemDB, so nothing closed in this window can release them. The stop +uses the engine that started each process (`engineThatStarted` in +`processes.ts`), since the new engine's `stopstone` cannot log in to the old +stone (4044). + **Choosing another root path when the default is on NFS — asked, once setup has refused.** The stone will not open a repository on an NFS mount, and on many shared Linux machines `~` is one (#69). Setup checks before downloading diff --git a/src/__integration__/engineUpgrade.test.ts b/src/__integration__/engineUpgrade.test.ts index 3a5d813..e380a56 100644 --- a/src/__integration__/engineUpgrade.test.ts +++ b/src/__integration__/engineUpgrade.test.ts @@ -1,13 +1,21 @@ import * as fs from 'fs'; import * as os from 'os'; import * as path from 'path'; -import { execFileSync } from 'child_process'; -import { afterAll, beforeAll, describe, expect, it } from 'vitest'; -import { PINNED_ENGINE_VERSION, STONE_NAME } from '../config'; +import { ChildProcess, execFileSync, spawn } from 'child_process'; +import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest'; +import * as vscode from 'vscode'; +import { NETLDI_NAME, PINNED_ENGINE_VERSION, STONE_NAME } from '../config'; import { REPOSITORY_LIMIT_MB, createDatabase, repositoryVersion } from '../database'; import { EngineUpgradeError, upgradeBackupPath, upgradeEngine } from '../engineUpgrade'; import { engineUpgradeWorld } from '../lifecycle'; -import { databaseConfPath, extentPath, grailStampPath, mcpStampPath } from '../paths'; +import { + databaseConfPath, + databaseLogPath, + expectedEnginePath, + extentPath, + grailStampPath, + mcpStampPath, +} from '../paths'; import { listProcesses } from '../processes'; import { Fixture, makeFixture } from './fixture'; @@ -106,10 +114,96 @@ function makeOldDatabase(): void { previousEngine('stopstone', [PREGROW_STONE, 'DataCurator', 'swordfish']); } +/** + * Start GemDB's own stone and listener on the old database with the previous + * engine, as the previous GemDB left them running: they outlive the editor, so + * this is what an extension update finds. + */ +function startPreviousDatabase(): void { + const running = listProcesses(); + if (!running.some((p) => p.type === 'stone' && p.name === STONE_NAME)) { + const conf = databaseConfPath(); + previousEngine('startstone', [ + '-z', + path.join(conf, 'system.conf'), + '-e', + path.join(conf, `${STONE_NAME}.conf`), + '-l', + path.join(databaseLogPath(), `${STONE_NAME}.log`), + STONE_NAME, + ]); + } + if (!running.some((p) => p.type === 'netldi' && p.name === NETLDI_NAME)) { + previousEngine('startnetldi', [ + '-a', + os.userInfo().username, + '-g', + '-l', + path.join(databaseLogPath(), `${NETLDI_NAME}.log`), + NETLDI_NAME, + ]); + } +} + +/** + * A session the previous engine's listener forked, standing for another window + * still running the previous GemDB: nothing this window logs out can end it, + * so a plain stopstone refuses while it is there. An RPC login, as a window's + * is, and not a linked topaz: a linked one holds the extent open itself until + * the process exits, which no window's session does. Settles once it is + * logged in. + */ +function holdPreviousSession(): Promise { + const gs = previous as string; + const port = listProcesses().find((p) => p.type === 'netldi' && p.name === NETLDI_NAME)?.port; + const topaz = spawn(path.join(gs, 'bin', 'topaz'), ['-q'], { + env: { + ...process.env, + GEMSTONE: gs, + GEMSTONE_GLOBAL_DIR: (fixture as Fixture).root, + PATH: `${path.join(gs, 'bin')}:/usr/bin:/bin`, + }, + }); + held.push(topaz); + return new Promise((resolve, reject) => { + let output = ''; + const timer = setTimeout(() => reject(new Error(`no login:\n${output}`)), 60_000); + const collect = (data: Buffer): void => { + output += data.toString(); + if (/successful login/i.test(output)) { + clearTimeout(timer); + resolve(topaz); + } + }; + topaz.stdout.on('data', collect); + topaz.stderr.on('data', collect); + topaz.on('exit', () => reject(new Error(`topaz exited:\n${output}`))); + topaz.stdin.write( + [ + 'set user DataCurator pass swordfish', + `set gemstone ${STONE_NAME}`, + `set gemnetid !tcp@localhost#netldi:${port}#task!gemnetobject`, + 'login', + '', + ].join('\n'), + ); + }); +} + +const held: ChildProcess[] = []; + +afterEach(() => { + vi.restoreAllMocks(); + for (const topaz of held.splice(0)) topaz.kill('SIGKILL'); +}); + beforeAll(() => { if (!ready) return; fixture = makeFixture(); if (!fixture) return; + // Where the previous GemDB installed it, beside the pinned one: what lets a + // stone it started be stopped with its own stopstone. + fs.symlinkSync(previous as string, expectedEnginePath(from)); // What `upgradeScriptPath` looks for: /grail/scripts/upgrade_engine.sh. extension = fs.mkdtempSync(path.join(os.tmpdir(), 'gemdb-it-ext-')); fs.symlinkSync(path.resolve(grail), path.join(extension, 'grail')); @@ -181,8 +275,40 @@ describe.skipIf(!ready)('upgrading a database an earlier GemDB made', () => { fs.rmSync(backup, { force: true }); }, 600_000); + it('changes nothing when told not to disconnect a session the previous engine holds', async () => { + if (!fixture) return; + startPreviousDatabase(); + await holdPreviousSession(); + const before = fs.statSync(extentPath()).mtimeMs; + const warning = vi.spyOn(vscode.window, 'showWarningMessage'); + const { world: w } = world(true, from); + + const run = upgradeEngine({ from, to: PINNED_ENGINE_VERSION, extent: extentPath() }, w); + + await expect(run).rejects.toThrow(/nothing was changed.*Every VS Code window/); + expect(warning).toHaveBeenCalledWith( + expect.stringContaining('GemDB did not stop'), + { modal: true }, + 'Stop Anyway', + ); + expect(listProcesses().find((p) => p.type === 'stone')?.version).toBe(from); + // Left to the windows still using it, listener included: this engine's + // cannot serve that stone. + expect(listProcesses().find((p) => p.type === 'netldi')).toBeUndefined(); + expect(fs.statSync(extentPath()).mtimeMs).toBe(before); + expect(fs.existsSync(upgradeBackupPath(extentPath(), from))).toBe(false); + }, 600_000); + it('upgrades it in place, keeps the original, and leaves nothing running', async () => { if (!fixture) return; + // The stone the previous GemDB left running, with another window's + // session in it: stopped with the previous engine's own stopstone, once + // the user says Stop Anyway. + startPreviousDatabase(); + await holdPreviousSession(); + const warning = vi + .spyOn(vscode.window, 'showWarningMessage') + .mockResolvedValue('Stop Anyway' as unknown as vscode.MessageItem); fs.mkdirSync(path.dirname(grailStampPath()), { recursive: true }); fs.writeFileSync(grailStampPath(), 'grail=old\n'); fs.mkdirSync(path.dirname(mcpStampPath()), { recursive: true }); @@ -194,6 +320,11 @@ describe.skipIf(!ready)('upgrading a database an earlier GemDB made', () => { ).resolves.toBe('upgraded'); expect(questions).toHaveLength(1); + expect(warning).toHaveBeenCalledWith( + expect.stringContaining('Every VS Code window running GemDB'), + { modal: true }, + 'Stop Anyway', + ); expect(repositoryVersion((fixture as Fixture).engine)).toBe(PINNED_ENGINE_VERSION); expect(fs.statSync(upgradeBackupPath(extentPath(), from)).size).toBe(CAP_BYTES); expect(listProcesses()).toEqual([]); diff --git a/src/__tests__/engineThatStarted.test.ts b/src/__tests__/engineThatStarted.test.ts new file mode 100644 index 0000000..46370df --- /dev/null +++ b/src/__tests__/engineThatStarted.test.ts @@ -0,0 +1,77 @@ +import * as fs from 'fs'; +import * as os from 'os'; +import * as path from 'path'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { __resetSettings, __setSetting } from '../__mocks__/vscode'; +import { EngineProcess } from '../gslist'; +import { engineDirName } from '../paths'; +import { engineThatStarted, startedByAnotherEngine } from '../processes'; + +/** + * Which engine's tools stop a stone that is already running. + * + * Stones outlive the editor, so after an update moves the pin the stone still + * up is the previous engine's, and the new engine's stopstone cannot log in to + * it (4044). Stopping it with the wrong engine is what left a user unable to + * stop or upgrade their database without reinstalling the old GemDB. + */ + +const PIN = '4.0.0.a8'; +const PREVIOUS = '4.0.0.a5'; + +function stone(version: string): EngineProcess { + return { type: 'stone', name: 'gemdb', version, pid: 101, status: 'OK', responding: true }; +} + +let root: string; + +beforeEach(() => { + __resetSettings(); + root = fs.mkdtempSync(path.join(os.tmpdir(), 'gemdb-engine-')); + __setSetting('gemdb.rootPath', root); + __setSetting('gemdb.engineVersion', PIN); +}); + +afterEach(() => { + fs.rmSync(root, { recursive: true, force: true }); +}); + +function install(version: string): string { + const dir = path.join(root, engineDirName(version)); + fs.mkdirSync(dir); + return dir; +} + +describe('the engine that stops a running database', () => { + it('is the pinned one for a stone the pinned engine started', () => { + install(PIN); + + expect(startedByAnotherEngine(stone(PIN))).toBe(false); + expect(engineThatStarted(stone(PIN))).toBeUndefined(); + }); + + it('is the previous one for a stone the previous engine started', () => { + install(PIN); + const previous = install(PREVIOUS); + + expect(startedByAnotherEngine(stone(PREVIOUS))).toBe(true); + expect(engineThatStarted(stone(PREVIOUS))).toBe(previous); + }); + + it('falls back to the pinned one when the previous engine is gone', () => { + install(PIN); + + expect(engineThatStarted(stone(PREVIOUS))).toBeUndefined(); + }); + + it('takes a version the process list cut short for the pinned one', () => { + __setSetting('gemdb.engineVersion', '4.0.0.Alpha1'); + + expect(startedByAnotherEngine(stone('4.0.0.Alpha'))).toBe(false); + }); + + it('is the pinned one when nothing is running', () => { + expect(startedByAnotherEngine(undefined)).toBe(false); + expect(engineThatStarted(undefined)).toBeUndefined(); + }); +}); diff --git a/src/__tests__/engineUpgrade.test.ts b/src/__tests__/engineUpgrade.test.ts index b8bfb6e..a9f161f 100644 --- a/src/__tests__/engineUpgrade.test.ts +++ b/src/__tests__/engineUpgrade.test.ts @@ -34,14 +34,15 @@ function makeWorld(options: { confirm?: boolean; noRoom?: boolean; stoneUp?: boolean; - listenerUp?: boolean; + /** The stop fails outright, as a login refused by the stone does. */ stoneWillNotStop?: boolean; + /** The stop settles with the stone still up, as a declined Stop Anyway does. */ + stopDeclined?: boolean; scriptFails?: string; /** What copydbf reads after the script, success or failure. */ versionAfter?: string | undefined; }): { calls: string[]; reports: string[]; world: UpgradeWorld } { let stoneUp = options.stoneUp ?? false; - let listenerUp = options.listenerUp ?? false; const calls: string[] = []; const reports: string[] = []; const world: UpgradeWorld = { @@ -65,18 +66,11 @@ function makeWorld(options: { calls.push('unlock'); } }, - logout: () => calls.push('logout'), stoneUp: () => stoneUp, - listenerUp: () => listenerUp, - stopStone: () => { - calls.push('stopStone'); + stopDatabase: () => { + calls.push('stopDatabase'); if (options.stoneWillNotStop) return Promise.reject(new Error('login failed')); - stoneUp = false; - return Promise.resolve(); - }, - stopNetldi: () => { - calls.push('stopNetldi'); - listenerUp = false; + if (!options.stopDeclined) stoneUp = false; return Promise.resolve(); }, runScript: (report) => { @@ -126,7 +120,7 @@ describe('the backup and the progress lines', () => { describe('upgrading the database', () => { it('asks first, and touches nothing when the answer is no', async () => { - const { calls, world } = makeWorld({ confirm: false, stoneUp: true, listenerUp: true }); + const { calls, world } = makeWorld({ confirm: false, stoneUp: true }); await expect(upgradeEngine(PLAN, world)).resolves.toBe('declined'); expect(calls).toEqual([`confirm(4.0.0.a5,4.0.0.a8,${BACKUP})`]); }); @@ -134,21 +128,19 @@ describe('upgrading the database', () => { it('refuses before stopping anything when the disk cannot hold the backup', async () => { const { calls, world } = makeWorld({ noRoom: true, stoneUp: true }); await expect(upgradeEngine(PLAN, world)).rejects.toThrow(DiskSpaceError); - expect(calls).not.toContain('stopStone'); + expect(calls).not.toContain('stopDatabase'); expect(calls).not.toContain('script'); }); - it('stops the previous engine’s processes, under the lock, before the script runs', async () => { - const { calls, reports, world } = makeWorld({ stoneUp: true, listenerUp: true }); + it('stops the database, under the lock, before the script runs', async () => { + const { calls, reports, world } = makeWorld({ stoneUp: true }); await expect(upgradeEngine(PLAN, world)).resolves.toBe('upgraded'); expect(calls).toEqual([ `confirm(4.0.0.a5,4.0.0.a8,${BACKUP})`, 'room', 'progress', 'lock', - 'logout', - 'stopStone', - 'stopNetldi', + 'stopDatabase', 'script', 'copydbf', 'unlock', @@ -174,6 +166,24 @@ describe('upgrading the database', () => { expect(calls.at(-1)).toBe('unlock'); }); + it('changes nothing when the user will not disconnect the sessions in the way', async () => { + const { calls, world } = makeWorld({ stoneUp: true, stopDeclined: true }); + + const result = upgradeEngine(PLAN, world); + + await expect(result).rejects.toThrow(/nothing was changed/); + expect(calls).not.toContain('script'); + expect(calls).not.toContain('forgetInstalls'); + }); + + it('names other editor windows as what may be holding the database open', async () => { + const { world } = makeWorld({ stoneUp: true, stopDeclined: true }); + + const result = upgradeEngine(PLAN, world); + + await expect(result).rejects.toThrow(/Every VS Code window running GemDB/); + }); + it('says the database is back as it was when the script restored it', async () => { const { calls, world } = makeWorld({ scriptFails: 'upgradeImage failed; extent restored' }); const result = upgradeEngine(PLAN, world); diff --git a/src/__tests__/engineUpgradeStart.test.ts b/src/__tests__/engineUpgradeStart.test.ts index 3c2d4a8..7653033 100644 --- a/src/__tests__/engineUpgradeStart.test.ts +++ b/src/__tests__/engineUpgradeStart.test.ts @@ -65,6 +65,8 @@ vi.mock('../processes', () => ({ findStone: () => true, findNetldi: () => true, engineEnvironment: () => ({}), + engineThatStarted: () => undefined, + startedByAnotherEngine: () => false, ensureProcesses: () => ensureProcesses(), isListening: () => true, isRunning: () => true, diff --git a/src/__tests__/startProcesses.test.ts b/src/__tests__/startProcesses.test.ts index ba356b5..593aab6 100644 --- a/src/__tests__/startProcesses.test.ts +++ b/src/__tests__/startProcesses.test.ts @@ -67,6 +67,7 @@ vi.mock('../lock', async (importOriginal) => { }); const { expectedEnginePath } = await import('../paths'); +const { PINNED_ENGINE_VERSION } = await import('../config'); const { STONE_LOCK_NAME } = await import('../lock'); const { EXTERNAL_SHUTTING_DOWN_MESSAGE, @@ -79,8 +80,13 @@ const { } = await import('../processes'); const { parseGslist } = await import('../gslist'); -function row(status: string, type: 'Stone' | 'Netldi', name: string): string { - return `${status.padEnd(12)} 4.0.0.a4 me 79386 51475 Sep 28 19:31 ${type.padEnd(7)} ${name}`; +function row( + status: string, + type: 'Stone' | 'Netldi', + name: string, + version = PINNED_ENGINE_VERSION, +): string { + return `${status.padEnd(12)} ${version.padEnd(9)} me 79386 51475 Sep 28 19:31 ${type.padEnd(7)} ${name}`; } const STONE_UP = row('OK', 'Stone', 'gemdb'); @@ -478,6 +484,13 @@ describe('putting the listener back after a declined force-stop', () => { expect(spawned).toEqual([]); }); + it('starts nothing beside a stone another engine started', async () => { + listings = [row('OK', 'Stone', 'gemdb', '4.0.0.a5')]; + + expect(await ensureListener()).toBe(false); + expect(spawned).toEqual([]); + }); + it('starts nothing when the listener is already back', async () => { listings = [BOTH_UP]; diff --git a/src/engineUpgrade.ts b/src/engineUpgrade.ts index 701c67e..d580949 100644 --- a/src/engineUpgrade.ts +++ b/src/engineUpgrade.ts @@ -184,12 +184,14 @@ export interface UpgradeWorld { assertRoomForBackup(): void; /** Run `work` holding the stone lock, so no window starts the stone meanwhile. */ withStoneLock(work: () => Promise): Promise; - /** Log every session out: none may outlive the database they logged in to. */ - logout(): void; + /** + * Stop the database the way GemDB: Stop GemDB does (`runStop`): this window's + * sessions out, the MCP server, the listener, then the stone, asking before + * it disconnects anyone else. Settles with the stone still up when the user + * says no. + */ + stopDatabase(): Promise; stoneUp(): boolean; - listenerUp(): boolean; - stopStone(): Promise; - stopNetldi(): Promise; /** The upgrade itself; `report` gets each progress line. */ runScript(report: (line: string) => void): Promise; /** The engine version that wrote the extent now, if it can be read. */ @@ -230,15 +232,14 @@ export async function upgradeEngine( world.withStoneLock(async () => { // The previous engine's stone and listener may still be up: they outlive // the editor, and an extension update is what brings a new engine. Its - // listener would hand every session an old gem, so it goes too. - world.logout(); + // listener would hand every session an old gem, so it goes too. Every + // other window holds a session on it, and one not reloaded since the + // update is still the previous GemDB, which no notebook or Shell closed + // here can release, so a refusal is asked about, as Stop asks. let stopError: string | undefined; + if (world.stoneUp()) report('Stopping the database…'); try { - if (world.stoneUp()) { - report('Stopping the database…'); - await world.stopStone(); - } - if (world.listenerUp()) await world.stopNetldi(); + await world.stopDatabase(); } catch (e) { stopError = e instanceof Error ? e.message : String(e); world.log(`Stopping the database for the upgrade: ${stopError}`); @@ -249,8 +250,11 @@ export async function upgradeEngine( if (world.stoneUp()) { throw new EngineUpgradeError( 'GemDB could not stop the database to upgrade it, so nothing was changed' + - (stopError ? ` (${stopError.split('\n')[0]})` : '') + - '. Close the notebooks and GemDB Shells using it, then start GemDB again.', + (stopError + ? ` (${stopError.split('\n')[0]}). The GemDB output has the details.` + : '. Every VS Code window running GemDB keeps a session on it, even with no ' + + 'notebook open, and so does a GemDB Shell. Reload or close the other ' + + 'windows, or choose Stop Anyway, then start GemDB again.'), ); } diff --git a/src/gslist.ts b/src/gslist.ts index 9791a32..6366f48 100644 --- a/src/gslist.ts +++ b/src/gslist.ts @@ -47,8 +47,9 @@ export interface EngineProcess { * tests, because the pin that hides the truncation today is not the pin * forever. * - * Nothing consumes the version field, so accepting whatever the engine prints - * costs nothing and matching it narrowly costs everything. + * Accept whatever the engine prints: matching it narrowly costs everything. + * The one consumer, `engineThatStarted`, compares it as a prefix of the pin + * for exactly this reason. * * Rows that are neither a Stone nor a Netldi — the shared page cache gets its * own row — do not match and are skipped, as are the header and separator diff --git a/src/lifecycle.ts b/src/lifecycle.ts index 2cb0d0d..bc6ff11 100644 --- a/src/lifecycle.ts +++ b/src/lifecycle.ts @@ -77,11 +77,13 @@ import { import { assertExternalDatabaseUp, engineEnvironment, + engineThatStarted, ensureListener, ensureProcesses, findStone, isListening, isRunning, + startedByAnotherEngine, stopNetldi, stopStone, } from './processes'; @@ -828,9 +830,6 @@ export function engineUpgradeWorld( engine: string, from: string, ): UpgradeWorld { - // A stone the previous engine started answers only to that engine's - // stopstone (measured: a8's fails to log in to an a5 stone, error 4044). - const previousEngine = enginePath(from); return { confirm: confirmEngineUpgrade, withProgress: (work) => @@ -844,18 +843,38 @@ export function engineUpgradeWorld( withStoneLock: async (work) => { await withStoneLock(work); }, - logout: logoutAll, + // Stop's own steps and question. `stopStone` and `stopNetldi` pick the + // engine that started each process, which is the previous one here: a8's + // stopstone fails to log in to an a5 stone (4044). + stopDatabase: () => + runStop({ + logout: logoutAll, + stopMcpServer, + stoneUp: () => isRunning(), + listenerUp: () => isListening(), + stopStone: async (force) => { + const stone = findStone(); + if (startedByAnotherEngine(stone) && !engineThatStarted(stone)) { + throw new Error( + `the running database was started by GemStone ${stone?.version ?? from}, ` + + 'which is no longer installed', + ); + } + await stopStone(force); + }, + stopNetldi: () => stopNetldi(), + // A declined force-stop leaves the stone to the sessions still in it, + // but not the listener. This engine's cannot serve the previous + // engine's stone, and the previous engine's would be no better: setup + // has already staged this release's Grail, built for this engine, at + // the path every session the listener forks loads its shim from. The + // windows still on the previous GemDB keep the sessions they have; + // reloading them is what the failure says to do. + startNetldi: () => Promise.resolve(), + confirmForce, + log, + }), stoneUp: () => isRunning(), - listenerUp: () => isListening(), - stopStone: async () => { - if (!previousEngine && findStone()?.version !== engineVersion()) { - throw new Error( - `the running database was started by GemStone ${from}, which is no longer installed`, - ); - } - await stopStone(false, previousEngine); - }, - stopNetldi: () => stopNetldi(previousEngine), runScript: (report) => runUpgradeScript({ stoneConfig: writeUpgradeStoneConfig(), @@ -1265,8 +1284,9 @@ async function stopOnce(): Promise { async function confirmForce(reason: string): Promise { const choice = await vscode.window.showWarningMessage( `GemDB did not stop:\n\n${reason}\n\n` + - 'This is usually a session that is still logged in — an open GemDB Shell terminal ' + - 'counts as one, and so does a notebook in another window.\n\n' + + 'This is usually a session that is still logged in. Every VS Code window running ' + + 'GemDB keeps one, even with no notebook open — including a window not reloaded ' + + 'since GemDB updated — and so does each GemDB Shell and notebook.\n\n' + 'Stopping anyway disconnects every session. Work that has not been committed is lost.', { modal: true }, 'Stop Anyway', diff --git a/src/processes.ts b/src/processes.ts index 293b214..d7a38e4 100644 --- a/src/processes.ts +++ b/src/processes.ts @@ -9,6 +9,7 @@ import { NETLDI_NAME, STONE_NAME, STOP_TIMEOUT_SECONDS, + engineVersion, externalDatabase, netldiName, rootPath, @@ -456,6 +457,16 @@ export async function ensureListener(): Promise { return false; } if (findNetldi(running)) return false; + // A listener from this engine beside a stone another one started would + // hand every session a gem that cannot log in to it (4044). + const stone = findStone(running); + if (startedByAnotherEngine(stone)) { + log( + `The database was started by GemStone ${stone?.version}; not starting a ` + + `GemStone ${engineVersion()} session listener beside it.`, + ); + return false; + } return startNetldi(); }, { satisfied: async () => findNetldi(await listProcessesAsync()) !== undefined }, @@ -608,14 +619,48 @@ export function stopStoneArgs(force: boolean): string[] { } /** - * Stop GemDB's stone. `gemstone` names the engine to stop it with, when it is - * not the one GemDB runs now: a stone the previous engine started, before an - * engine upgrade. + * Whether `process` was started by an engine other than the one GemDB runs + * now. A prefix counts as the same engine: `gslist` can truncate the version + * (see `parseGslist`), and a truncated pin is still the pin. + */ +export function startedByAnotherEngine(process: EngineProcess | undefined): boolean { + if (!process || externalDatabase()) return false; + return !engineVersion().startsWith(process.version); +} + +/** + * The engine to stop `process` with: the one that started it. + * + * Not always the one GemDB runs now. Stones and listeners outlive the editor, + * so after an extension update moves the pin, the processes still up are the + * previous engine's, and this engine's `stopstone` cannot log in to that stone + * (measured: a8's against an a5 stone fails with 4044, "The Gem and Stone + * versions are incompatible"). Undefined, meaning GemDB's own engine, for one + * it started, for an external database (there is only the one), and when the + * previous engine is no longer installed, which is logged: the stop is tried + * anyway, and its own error is the one worth showing. + */ +export function engineThatStarted(process: EngineProcess | undefined): string | undefined { + if (!startedByAnotherEngine(process)) return undefined; + const version = process?.version ?? ''; + const engine = enginePath(version); + if (!engine) { + log( + `The database was started by GemStone ${version}, which is no longer installed; ` + + `trying GemStone ${engineVersion()}'s tools instead.`, + ); + } + return engine; +} + +/** + * Stop GemDB's stone, with the engine that started it ({@link engineThatStarted}) + * unless `gemstone` names one. */ export async function stopStone(force = false, gemstone?: string): Promise { requireOwnDatabase('stop'); logStep(force ? 'Stopping the database, disconnecting other sessions' : 'Stopping the database'); - const env = engineEnvironment(gemstone); + const env = engineEnvironment(gemstone ?? engineThatStarted(findStone())); await runEngineCommand( path.join(env.GEMSTONE, 'bin', 'stopstone'), stopStoneArgs(force), @@ -624,9 +669,10 @@ export async function stopStone(force = false, gemstone?: string): Promise ); } +/** Stop GemDB's listener, with the engine that started it, as {@link stopStone}. */ export async function stopNetldi(gemstone?: string): Promise { requireOwnDatabase('stop'); - const env = engineEnvironment(gemstone); + const env = engineEnvironment(gemstone ?? engineThatStarted(findNetldi())); await runEngineCommand( path.join(env.GEMSTONE, 'bin', 'stopnetldi'), [NETLDI_NAME],