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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
157 changes: 143 additions & 14 deletions packages/diagram-server/src/server/elk-server/elk-server-process.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -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<number, StartedServer>();
private starting: Promise<number | undefined> | undefined;
private disposed = false;
/** Why the last start failed; logged once, not on every layout. */
Expand Down Expand Up @@ -55,34 +113,94 @@ 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<T>(port: number, layout: () => Promise<T>): Promise<T> {
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;
this.stop();
}

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<number | undefined> {
if (!fs.existsSync(this.options.jar)) {
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, {
Expand All @@ -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());
}
});

Expand All @@ -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;
Expand Down
2 changes: 1 addition & 1 deletion packages/diagram-server/src/server/elk-server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ type LaidOut<T extends ElkNode> = Awaited<ReturnType<ELK['layout']>> & Omit<T, '
export class SwitchingElk implements ELK {
constructor(
private readonly elkjs: ELK,
private readonly server: Pick<ElkServerProcess, 'ensureStarted'>,
private readonly server: Pick<ElkServerProcess, 'ensureStarted'> & Partial<Pick<ElkServerProcess, 'during'>>,
private readonly options: Pick<ElkServerOptions, 'engine' | 'timeoutMs'>,
private readonly layoutOnPort: typeof layoutOnServer = layoutOnServer
) {}
Expand All @@ -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<ElkNode> => 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<T>;
} catch (error) {
Expand Down
4 changes: 3 additions & 1 deletion packages/diagram-server/src/server/layout-cost.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading
Loading