Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

detect EADDRINUSE on server start #1348

Draft
wants to merge 4 commits into
base: master
Choose a base branch
from
Draft
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
73 changes: 59 additions & 14 deletions apps/server/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { LogOrigin, Playback, SimpleDirection, SimplePlayback } from 'ontime-typ
import 'dotenv/config';
import express from 'express';
import expressStaticGzip from 'express-static-gzip';
import http, { type Server } from 'http';
import http, { Server } from 'http';
import cors from 'cors';
import serverTiming from 'server-timing';
import { extname, resolve } from 'path';
Expand Down Expand Up @@ -171,11 +171,18 @@ export const initAssets = async () => {
*/
export const startServer = async (
escalateErrorFn?: (error: string) => void,
): Promise<{ message: string; serverPort: number }> => {
): Promise<{ message: string; serverPort: number; portError: boolean }> => {
checkStart(OntimeStartOrder.InitServer);
const { serverPort } = getDataProvider().getSettings();
const settings = getDataProvider().getSettings();
const { serverPort: desiredPort } = settings;

expressServer = http.createServer(app);

// the express server must be started before the socket otherwise the on error eventlissner will not attach properly
const resultPort = await serverTryDesiredPort(expressServer, desiredPort);
const portError = resultPort !== desiredPort;
await getDataProvider().setSettings({ ...settings, serverPort: resultPort });

socket.init(expressServer);

/**
Expand Down Expand Up @@ -220,19 +227,21 @@ export const startServer = async (
// TODO: pass event store to rundownservice
runtimeService.init(maybeRestorePoint);

expressServer.listen(serverPort, '0.0.0.0', () => {
const nif = getNetworkInterfaces();
consoleSuccess(`Local: http://localhost:${serverPort}/editor`);
for (const key in nif) {
const address = nif[key].address;
consoleSuccess(`Network: http://${address}:${serverPort}/editor`);
}
});
const nif = getNetworkInterfaces();
consoleSuccess(`Local: http://localhost:${resultPort}/editor`);
for (const key in nif) {
const address = nif[key].address;
consoleSuccess(`Network: http://${address}:${resultPort}/editor`);
}

const returnMessage = `Ontime is listening on port ${serverPort}`;
const returnMessage = `Ontime is listening on port ${resultPort}`;
logger.info(LogOrigin.Server, returnMessage);

return { message: returnMessage, serverPort };
return {
message: returnMessage,
serverPort: resultPort,
portError,
};
};

/**
Expand Down Expand Up @@ -297,7 +306,7 @@ process.on('unhandledRejection', async (error) => {
consoleError(error.stack);
}
generateCrashReport(error);
logger.crash(LogOrigin.Server, `Uncaught exception | ${error}`);
logger.crash(LogOrigin.Server, `Uncaught rejection | ${error}`);
await shutdown(1);
});

Expand All @@ -314,3 +323,39 @@ process.on('uncaughtException', async (error) => {
process.once('SIGHUP', async () => shutdown(0));
process.once('SIGINT', async () => shutdown(0));
process.once('SIGTERM', async () => shutdown(0));

/**
* @description tries to open the server with the desired port, and if getting a `EADDRINUSE` will change to an efemeral port
* @param {http.Server}server http server object
* @param {number}desiredPort the desired port
* @returns {number} the resulting port number
* @throws any other server errors will result in a throw
*/
async function serverTryDesiredPort(server: http.Server, desiredPort: number): Promise<number> {
return new Promise((res) => {
expressServer.once('error', (e) => {
if (testForPortInUser(e)) {
logger.error(LogOrigin.Server, `Failed open the desired port: ${desiredPort} | to moving to Ephemeral port`);
server.listen(0, '0.0.0.0', () => {
// @ts-expect-error TODO: find proper documentation for this api
const port: number = server.address().port;
res(port);
});
} else {
throw e;
}
});
server.listen(desiredPort, '0.0.0.0', () => {
// @ts-expect-error TODO: find proper documentation for this api
const port: number = server.address().port;
res(port);
});
});
}

function testForPortInUser(err: unknown) {
if (typeof err === 'object' && 'code' in err && err.code === 'EADDRINUSE') {
return true;
}
return false;
}