diff --git a/CHANGELOG.md b/CHANGELOG.md index 8f8391f..b2d169f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -211,6 +211,22 @@ platform API version. ### Fixed +- **The ELK server lays out deep graphs, and one it cannot is not waited + for.** ELK's network simplex walks a graph by recursion, and on the + megabyte a JVM gives a thread a warm server overflowed its stack on a deep + graph of 10,000 nodes. The server catches that error, logs it and never + answers, so the layout waited out its whole timeout (120 s) before it was + refused or handed to elkjs. The server's threads now get a 64 MB stack + (`ELK_SERVER_STACK`, unless `layout.javaOpts`, `JAVA_TOOL_OPTIONS` or + `JDK_JAVA_OPTIONS` name one with `-Xss`), with which that graph lays out + in five seconds and one of 20,000 nodes in ten. A server that still + reports a stack overflow is retired: the next layout starts another, the + old one answers what else it was asked (the layouts of other diagrams), + and it is ended when the layouts that overflowed are all it has left + (`ElkServerProcess.during`). Those fail at once (3 s on a stack made too + small for the check) and say why: the status line and the log name the + stack, and the JVM options that give more (`-Xmx2g -Xss256m`: the options + of the settings replace the default heap too). - **A flow symbol whose text is not a string.** A number in a depiction's `text`, `glyph`, `mark` or `to` (from a producer's JSON) is read as its digits, and any other value that is not a string counts as one not given. diff --git a/packages/diagram-server/src/server/elk-server/elk-server-options.ts b/packages/diagram-server/src/server/elk-server/elk-server-options.ts index d7e7344..89d415f 100644 --- a/packages/diagram-server/src/server/elk-server/elk-server-options.ts +++ b/packages/diagram-server/src/server/elk-server/elk-server-options.ts @@ -29,7 +29,7 @@ export interface ElkServerOptions { jar: string; /** The `java` to run; default `$JAVA_HOME/bin/java`, else `java` on the PATH. */ javaPath?: string; - /** JVM options, split on whitespace (e.g. `-Xmx2g`). */ + /** JVM options, split on whitespace (e.g. `-Xmx2g`). The server's threads get a 64 MB stack unless `-Xss` is among them. */ javaOpts?: string; /** * How long one layout may take on the server. Past it elkjs takes the diff --git a/packages/diagram-server/src/server/elk-server/elk-server-process.ts b/packages/diagram-server/src/server/elk-server/elk-server-process.ts index 3bdd285..1846453 100644 --- a/packages/diagram-server/src/server/elk-server/elk-server-process.ts +++ b/packages/diagram-server/src/server/elk-server/elk-server-process.ts @@ -9,6 +9,16 @@ * started again by the next layout that asks for it; until then layouts go to * elkjs. Nothing waits on a server that cannot start: no Java, no jar, or no * "listening" within the start timeout, and the layout goes to elkjs. + * + * A layout that overflows the stack of its thread is the other failure the + * server does not answer: it catches the error, logs it and leaves the + * request open, so the layout would wait out its whole timeout. The threads + * get a stack deep graphs fit in ({@link ELK_SERVER_STACK}). A server that + * still says a layout overflowed is healthy but for that request, and is + * shared by every diagram: it is retired, so the next layout starts another, + * answers what else it was asked ({@link ElkServerProcess.during}), and is + * ended when the layouts that overflowed are all it has left. Ending it is + * what ends them, with the reason ({@link ELK_SERVER_OUT_OF_STACK}). */ import * as cp from 'node:child_process'; import * as fs from 'node:fs'; @@ -21,11 +31,59 @@ export const ELK_SERVER_START_TIMEOUT_MS = 15_000; const LISTENING = /listening (?:to|on) [^\s:]*:(\d+)/i; +/** + * The stack of the server's threads, when the JVM options name none. ELK's + * network simplex walks its spanning tree by recursion, a frame a node. On + * the megabyte a JVM gives a thread, a warm server overflowed on a deep graph + * of 10,000 nodes that it lays out in five seconds with this stack, as it + * does one of 20,000. The memory is reserved, and used only as deep as a + * layout goes. + */ +export const ELK_SERVER_STACK = '-Xss64m'; + +/** + * The JVM's arguments for these options: split on whitespace, with the stack + * the server needs unless one is named, in the options or in what the JVM + * reads from the environment (an argument would override that one). + */ +export function jvmArguments(javaOpts: string | undefined, env: NodeJS.ProcessEnv = process.env): string[] { + const given = (javaOpts ?? '').split(/\s+/).filter(Boolean); + const namesStack = (options: readonly string[]): boolean => options.some(option => /^-Xss|^-XX:ThreadStackSize=/.test(option)); + const fromEnvironment = `${env.JAVA_TOOL_OPTIONS ?? ''} ${env.JDK_JAVA_OPTIONS ?? ''}`.split(/\s+/); + return namesStack(given) || namesStack(fromEnvironment) ? given : [ELK_SERVER_STACK, ...given]; +} + +/** + * What a layout that overflowed the server's stack fails with. The JVM + * options of the settings replace the default ones, heap included, so the + * advice names both. + */ +export const ELK_SERVER_OUT_OF_STACK = + 'the ELK server ran out of stack on this layout (the JVM options of the layout settings give its threads more, beside the heap: -Xmx2g -Xss256m)'; + +/** The line the JVM logs for a stack overflow the server caught, or one a thread died of. */ +const STACK_OVERFLOW_LINE = /^(?:Exception in thread "[^"]*" )?java\.lang\.StackOverflowError\b/; + +/** One server the process started. */ +interface StartedServer { + child: cp.ChildProcess; + /** The layouts it was asked for and has not answered ({@link ElkServerProcess.during}). */ + asked: number; + /** How many of them it said overflowed the stack, which it will never answer. */ + overflowed: number; + /** No longer the server new layouts go to. */ + retired: boolean; + /** Ended because the layouts that overflowed were all it had left. */ + endedForStack: boolean; +} + export type SpawnFunction = (command: string, args: string[], options: cp.SpawnOptions) => cp.ChildProcess; export class ElkServerProcess { private child: cp.ChildProcess | undefined; private port: number | undefined; + /** Every server still running, by its port: the current one, and retired ones answering what they were asked. */ + private readonly servers = new Map(); private starting: Promise | undefined; private disposed = false; /** Why the last start failed; logged once, not on every layout. */ @@ -55,6 +113,63 @@ export class ElkServerProcess { return this.child !== undefined && this.child.exitCode === null && !this.child.killed; } + /** + * Runs one layout on the server at `port`, so that the process knows what + * that server has still to answer. A server that said a layout overflowed + * its stack is ended once the layouts it cannot answer are all it has + * left, and those fail with the reason, not with the closed connection. + */ + async during(port: number, layout: () => Promise): Promise { + const server = this.servers.get(port); + if (!server) { + return layout(); + } + server.asked++; + try { + return await layout(); + } catch (error) { + if (server.endedForStack) { + throw new Error(ELK_SERVER_OUT_OF_STACK); + } + // A layout that fails on a server with an overflow to its name, + // by its timeout say, is taken for the one that overflowed. + if (server.overflowed > 0) { + server.overflowed--; + } + throw error; + } finally { + server.asked--; + this.endWhenDone(server); + } + } + + /** Ends a retired server that has nothing left it can answer. */ + private endWhenDone(server: StartedServer): void { + if (!server.retired || server.asked > server.overflowed || server.child.exitCode !== null || server.child.killed) { + return; + } + server.endedForStack = server.overflowed > 0; + server.child.kill('SIGKILL'); + } + + /** What a server says on its error stream, a whole line at a time. */ + private heard(server: StartedServer, line: string): void { + if (/OutOfMemoryError|Java heap space/.test(line)) { + // It keeps running, broken: nothing it was asked will be answered. + console.error('[dialogram layout] the ELK server ran out of heap; it restarts with the next layout (raise -Xmx in the layout settings)'); + server.child.kill('SIGKILL'); + } else if (STACK_OVERFLOW_LINE.test(line)) { + console.error('[dialogram layout] the ELK server ran out of stack on a layout; the next layout starts another server'); + server.overflowed++; + server.retired = true; + if (this.child === server.child) { + this.child = undefined; + this.port = undefined; + } + this.endWhenDone(server); + } + } + /** Stop the process for good; later layouts go to elkjs. */ dispose(): void { this.disposed = true; @@ -62,19 +177,22 @@ export class ElkServerProcess { } private stop(): void { - const child = this.child; + const children = new Set([...(this.child ? [this.child] : []), ...[...this.servers.values()].map(server => server.child)]); this.child = undefined; this.port = undefined; - if (!child || child.exitCode !== null) { - return; - } - child.kill('SIGTERM'); - const escalate = setTimeout(() => { - if (child.exitCode === null) { - child.kill('SIGKILL'); + this.servers.clear(); + for (const child of children) { + if (child.exitCode !== null) { + continue; } - }, 5000); - escalate.unref?.(); + child.kill('SIGTERM'); + const escalate = setTimeout(() => { + if (child.exitCode === null) { + child.kill('SIGKILL'); + } + }, 5000); + escalate.unref?.(); + } } private async start(): Promise { @@ -82,7 +200,7 @@ export class ElkServerProcess { return this.failed(`no ELK server jar at ${this.options.jar}`); } const port = await freePort(); - const args = [...(this.options.javaOpts ?? '').split(/\s+/).filter(Boolean), '-jar', this.options.jar, '--socket']; + const args = [...jvmArguments(this.options.javaOpts), '-jar', this.options.jar, '--socket']; let child: cp.ChildProcess; try { child = this.spawn(this.javaPath(), args, { @@ -94,16 +212,26 @@ export class ElkServerProcess { return this.failed(`could not run ${this.javaPath()}: ${String(error)}`); } this.child = child; + const server: StartedServer = { child, asked: 0, overflowed: 0, retired: false, endedForStack: false }; child.on('exit', () => { + for (const [port, started] of this.servers) { + if (started === server) { + this.servers.delete(port); + } + } if (this.child === child) { this.child = undefined; this.port = undefined; } }); + // Read by the line: a pipe hands a line over in pieces, and a word in + // the middle of one (an id the server quotes) is no error of the JVM. + let unfinished = ''; child.stderr?.on('data', data => { - if (/OutOfMemoryError|Java heap space/.test(String(data))) { - console.error('[dialogram layout] the ELK server ran out of heap; it restarts with the next layout (raise -Xmx in the layout settings)'); - child.kill('SIGKILL'); + const lines = (unfinished + String(data)).split('\n'); + unfinished = (lines.pop() ?? '').slice(-8192); + for (const line of lines) { + this.heard(server, line.trim()); } }); @@ -113,6 +241,7 @@ export class ElkServerProcess { return this.failed(`the ELK server did not start within ${this.startTimeoutMs} ms (is Java 17 or later installed?)`); } this.port = listening; + this.servers.set(listening, server); this.lastFailure = undefined; console.log(`[dialogram layout] ELK server listening on port ${listening} (pid ${child.pid})`); return listening; diff --git a/packages/diagram-server/src/server/elk-server/index.ts b/packages/diagram-server/src/server/elk-server/index.ts index 6f0eeff..0dcff89 100644 --- a/packages/diagram-server/src/server/elk-server/index.ts +++ b/packages/diagram-server/src/server/elk-server/index.ts @@ -11,7 +11,7 @@ import type { ElkServerOptions } from './elk-server-options'; import { SwitchingElk } from './switching-elk'; export * from './elk-server-options'; -export { ElkServerProcess } from './elk-server-process'; +export { ELK_SERVER_OUT_OF_STACK, ELK_SERVER_STACK, ElkServerProcess, jvmArguments } from './elk-server-process'; export { AUTO_ELKJS_BUDGET_MS, ELKJS_TAKEOVER_BUDGET_MS, diff --git a/packages/diagram-server/src/server/elk-server/switching-elk.ts b/packages/diagram-server/src/server/elk-server/switching-elk.ts index 5dca9fc..24854f5 100644 --- a/packages/diagram-server/src/server/elk-server/switching-elk.ts +++ b/packages/diagram-server/src/server/elk-server/switching-elk.ts @@ -124,7 +124,7 @@ type LaidOut = Awaited> & Omit, + private readonly server: Pick & Partial>, private readonly options: Pick, private readonly layoutOnPort: typeof layoutOnServer = layoutOnServer ) {} @@ -140,7 +140,9 @@ export class SwitchingElk implements ELK { const timeoutMs = this.options.timeoutMs ?? DEFAULT_ELK_SERVER_TIMEOUT_MS; try { // The server's layout is written into the graph it was given, as elkjs's is. - const result = await this.layoutOnPort(port, graph, timeoutMs); + // Through the process, which knows by it what its server has still to answer. + const onServer = (): Promise => this.layoutOnPort(port, graph, timeoutMs); + const result = await (this.server.during ? this.server.during(port, onServer) : onServer()); console.log(`[dialogram layout] ELK server: ${what} in ${Date.now() - started} ms (estimated ${estimate.serverMs} ms, elkjs ${estimate.elkjsMs} ms)`); return result as LaidOut; } catch (error) { diff --git a/packages/diagram-server/src/server/layout-cost.ts b/packages/diagram-server/src/server/layout-cost.ts index a596cac..78540c5 100644 --- a/packages/diagram-server/src/server/layout-cost.ts +++ b/packages/diagram-server/src/server/layout-cost.ts @@ -517,7 +517,9 @@ export function formatLayoutMs(ms: number): string { * middle preset. The fast preset places simply, and its time follows the * nodes. At 10,000 nodes elkjs gave no layout of the four deepest of the six * graphs, and the server none of the deepest: the stack of each engine ends - * first, which no rate tells. + * first, which no rate tells. (The server's threads had a megabyte then. With + * the 64 MB they have now, `ELK_SERVER_STACK`, it lays that graph out in five + * seconds.) * * The rates were then checked on seven graphs they were not fitted to, the * modules of a RISC-V core as written and as synthesised, of 40 to 1,225 diff --git a/packages/diagram-server/test/elk-server.test.ts b/packages/diagram-server/test/elk-server.test.ts index ea1c101..81d8b7e 100644 --- a/packages/diagram-server/test/elk-server.test.ts +++ b/packages/diagram-server/test/elk-server.test.ts @@ -16,12 +16,12 @@ import { createServer, type Server } from 'node:net'; import * as path from 'node:path'; import { PassThrough } from 'node:stream'; import { gunzipSync, gzipSync } from 'node:zlib'; -import { afterEach, describe, expect, it, vi } from 'vitest'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import ElkConstructor from 'elkjs/lib/elk.bundled.js'; import type { ELK, ElkNode } from 'elkjs'; import { DefaultElementFilter } from '@eclipse-glsp/layout-elk'; import { FRAME_HEADER_BYTES, FRAME_MAGIC, encodeFrame, layoutOnServer } from '../src/server/elk-server/elk-server-client'; -import { ElkServerProcess, type SpawnFunction } from '../src/server/elk-server/elk-server-process'; +import { ELK_SERVER_OUT_OF_STACK, ELK_SERVER_STACK, ElkServerProcess, jvmArguments, type SpawnFunction } from '../src/server/elk-server/elk-server-process'; import { AUTO_ELKJS_BUDGET_MS, ELKJS_TAKEOVER_BUDGET_MS, @@ -157,10 +157,135 @@ describe('the ELK server process', () => { expect(first).toBe(5123); expect(second).toBe(5123); - expect(spawned).toEqual([['-Xmx1g', '-jar', jar, '--socket']]); + expect(spawned).toEqual([[ELK_SERVER_STACK, '-Xmx1g', '-jar', jar, '--socket']]); process.dispose(); }); + it('gives the threads of the server a deep stack, unless the JVM options or the environment name one', () => { + expect(ELK_SERVER_STACK).toBe('-Xss64m'); + expect(jvmArguments(undefined, {})).toEqual(['-Xss64m']); + expect(jvmArguments(' -Xmx2g -ea ', {})).toEqual(['-Xss64m', '-Xmx2g', '-ea']); + expect(jvmArguments('-Xmx2g -Xss8m', {})).toEqual(['-Xmx2g', '-Xss8m']); + expect(jvmArguments('-XX:ThreadStackSize=4096', {})).toEqual(['-XX:ThreadStackSize=4096']); + // An argument would override what the JVM reads from the environment. + expect(jvmArguments('-Xmx2g', { JAVA_TOOL_OPTIONS: '-Dfile.encoding=UTF-8 -Xss512k' })).toEqual(['-Xmx2g']); + expect(jvmArguments('-Xmx2g', { JDK_JAVA_OPTIONS: '-XX:ThreadStackSize=2048' })).toEqual(['-Xmx2g']); + expect(jvmArguments('-Xmx2g', { JAVA_TOOL_OPTIONS: '-Dfile.encoding=UTF-8' })).toEqual(['-Xss64m', '-Xmx2g']); + }); + + describe('when the server says a layout overflowed its stack', () => { + /** What java.util.logging prints for the error the server caught. */ + const OVERFLOW = 'SEVERE: [3] Error: null\njava.lang.StackOverflowError\n\tat org.eclipse.elk.alg.common.networksimplex.NetworkSimplex.tightTreeDFS(NetworkSimplex.java:412)\n'; + const settle = (): Promise => new Promise(resolve => setTimeout(resolve, 10)); + function started(): { process: ElkServerProcess; children: any[] } { + const children: any[] = []; + const spawn: SpawnFunction = () => { + const child = fakeChild(`ELK Server listening on /127.0.0.1:${5300 + children.length}`); + children.push(child); + return child; + }; + return { process: new ElkServerProcess({ jar }, spawn), children }; + } + /** A layout in flight on `child`: it ends when told to, or fails when the server is ended. */ + function inFlight(child: any): { layout: () => Promise; answer: () => void } { + let answer: () => void = () => undefined; + const layout = (): Promise => + new Promise((resolve, reject) => { + answer = () => resolve('laid out'); + child.once('exit', () => reject(new Error('the ELK server closed the connection'))); + }); + return { layout, answer: () => answer() }; + } + let said: ReturnType; + beforeEach(() => { + said = vi.spyOn(console, 'error').mockImplementation(() => undefined); + }); + afterEach(() => said.mockRestore()); + + it('ends it at once when it was asked nothing else, and the next layout starts another', async () => { + const { process, children } = started(); + expect(await process.ensureStarted()).toBe(5300); + children[0].stderr.write(OVERFLOW); + await settle(); + + expect(children[0].killed).toBe(true); + expect(said.mock.calls.map(call => String(call[0])).join('\n')).toMatch(/ran out of stack on a layout/); + expect(await process.ensureStarted()).toBe(5301); + process.dispose(); + }); + + it('lets it answer the other layouts first, then ends the one that overflowed with the reason', async () => { + const { process, children } = started(); + const port = (await process.ensureStarted())!; + const deep = inFlight(children[0]); + const other = inFlight(children[0]); + const overflowed = process.during(port, deep.layout); + const answered = process.during(port, other.layout); + const outcome = overflowed.then(() => 'laid out', error => String(error.message)); + children[0].stderr.write(OVERFLOW); + await settle(); + + // Still answering the other diagram, and no longer the server new layouts go to. + expect(children[0].killed).toBe(false); + expect(await process.ensureStarted()).toBe(5301); + expect(children[1].killed).toBe(false); + + other.answer(); + await expect(answered).resolves.toBe('laid out'); + await expect(outcome).resolves.toBe(ELK_SERVER_OUT_OF_STACK); + expect(children[0].killed).toBe(true); + expect(children[1].killed).toBe(false); + process.dispose(); + expect(children[1].killed).toBe(true); + }); + + it('does not end a layout still running because the one that overflowed timed out first', async () => { + const { process, children } = started(); + const port = (await process.ensureStarted())!; + const slow = inFlight(children[0]); + const answered = process.during(port, slow.layout); + const timedOut = process.during(port, () => new Promise((_, reject) => setTimeout(() => reject(new Error('the ELK server took longer than 20 ms')), 20))); + const outcome = timedOut.then(() => 'laid out', error => String(error.message)); + children[0].stderr.write(OVERFLOW); + + await expect(outcome).resolves.toBe('the ELK server took longer than 20 ms'); + expect(children[0].killed).toBe(false); + slow.answer(); + await expect(answered).resolves.toBe('laid out'); + // Retired, and with nothing left to answer. + expect(children[0].killed).toBe(true); + process.dispose(); + }); + + it('hears the line when the pipe hands it over in pieces, and not the word inside another line', async () => { + const { process, children } = started(); + await process.ensureStarted(); + children[0].stderr.write('WARNING: no layout provider for node StackOverflowErrorHandler (java.lang.StackOverflowError quoted)\n'); + await settle(); + expect(children[0].killed).toBe(false); + + children[0].stderr.write('SEVERE: [3] Error: null\njava.lang.StackOverf'); + await settle(); + expect(children[0].killed).toBe(false); + children[0].stderr.write('lowError\n\tat org.eclipse.elk'); + await settle(); + expect(children[0].killed).toBe(true); + process.dispose(); + }); + + it('still ends a server out of heap at once, whatever it was asked', async () => { + const { process, children } = started(); + const port = (await process.ensureStarted())!; + const asked = inFlight(children[0]); + const outcome = process.during(port, asked.layout).then(() => 'laid out', error => String(error.message)); + children[0].stderr.write('Exception in thread "pool-1-thread-2" java.lang.OutOfMemoryError: Java heap space\n'); + + await expect(outcome).resolves.toBe('the ELK server closed the connection'); + expect(children[0].killed).toBe(true); + process.dispose(); + }); + }); + it('starts again after the process died', async () => { const children: ChildProcess[] = []; const spawn: SpawnFunction = () => { @@ -305,6 +430,16 @@ describe('the engine a graph goes to', () => { expect(java.starts).toBe(0); }); + it('asks the server through its process, which knows by it what the server has still to answer', async () => { + const through: number[] = []; + const tracking = { ...server(5000), during: async (port: number, layout: () => Promise): Promise => { through.push(port); return layout(); } }; + const sent: ElkNode[] = []; + await new SwitchingElk(elkjs(), tracking, { engine: 'elk-server' }, async (_port, g) => { sent.push(g); return g; }).layout(chain(3)); + + expect(through).toEqual([5000]); + expect(sent).toHaveLength(1); + }); + it('falls back to elkjs when the server cannot start or fails, for a graph elkjs finishes in time', async () => { const noServer = elkjs(); await new SwitchingElk(noServer, server(undefined), { engine: 'elk-server' }).layout(chain(3));