2023-10-18 04:32:14 -04:00
|
|
|
// Metrics must be initialized before importing anything else
|
|
|
|
require('@overleaf/metrics/initialize')
|
|
|
|
|
2020-11-25 06:57:22 -05:00
|
|
|
const Metrics = require('@overleaf/metrics')
|
2021-07-12 12:47:18 -04:00
|
|
|
const Settings = require('@overleaf/settings')
|
2020-06-23 13:30:51 -04:00
|
|
|
const async = require('async')
|
|
|
|
|
2021-12-14 08:00:35 -05:00
|
|
|
const logger = require('@overleaf/logger')
|
2020-06-23 13:30:51 -04:00
|
|
|
logger.initialize('real-time')
|
|
|
|
Metrics.event_loop.monitor(logger)
|
2023-05-22 06:36:51 -04:00
|
|
|
Metrics.open_sockets.monitor()
|
2020-06-23 13:30:51 -04:00
|
|
|
|
|
|
|
const express = require('express')
|
|
|
|
const session = require('express-session')
|
2020-11-10 06:32:06 -05:00
|
|
|
const redis = require('@overleaf/redis-wrapper')
|
2020-07-07 06:06:02 -04:00
|
|
|
if (Settings.sentry && Settings.sentry.dsn) {
|
2020-06-23 13:30:51 -04:00
|
|
|
logger.initializeErrorReporting(Settings.sentry.dsn)
|
2020-06-23 13:30:48 -04:00
|
|
|
}
|
|
|
|
|
2020-06-23 13:30:51 -04:00
|
|
|
const sessionRedisClient = redis.createClient(Settings.redis.websessions)
|
2020-06-23 13:30:48 -04:00
|
|
|
|
2020-06-23 13:30:51 -04:00
|
|
|
const RedisStore = require('connect-redis')(session)
|
|
|
|
const SessionSockets = require('./app/js/SessionSockets')
|
|
|
|
const CookieParser = require('cookie-parser')
|
2020-06-23 13:30:48 -04:00
|
|
|
|
2020-06-23 13:30:51 -04:00
|
|
|
const DrainManager = require('./app/js/DrainManager')
|
|
|
|
const HealthCheckManager = require('./app/js/HealthCheckManager')
|
2021-03-19 12:27:27 -04:00
|
|
|
const DeploymentManager = require('./app/js/DeploymentManager')
|
2020-06-23 13:30:48 -04:00
|
|
|
|
2024-11-08 05:21:56 -05:00
|
|
|
const Path = require('node:path')
|
2022-10-27 06:26:40 -04:00
|
|
|
|
2020-08-28 06:47:45 -04:00
|
|
|
// NOTE: debug is invoked for every blob that is put on the wire
|
|
|
|
const socketIoLogger = {
|
|
|
|
error(...message) {
|
2021-09-14 04:36:24 -04:00
|
|
|
logger.debug({ fromSocketIo: true, originalLevel: 'error' }, ...message)
|
2020-08-28 06:47:45 -04:00
|
|
|
},
|
|
|
|
warn(...message) {
|
2021-09-14 04:36:24 -04:00
|
|
|
logger.debug({ fromSocketIo: true, originalLevel: 'warn' }, ...message)
|
2020-08-28 06:47:45 -04:00
|
|
|
},
|
|
|
|
info() {},
|
|
|
|
debug() {},
|
2021-07-13 07:04:45 -04:00
|
|
|
log() {},
|
2020-08-28 06:47:45 -04:00
|
|
|
}
|
|
|
|
|
2021-03-19 12:27:27 -04:00
|
|
|
// monitor status file to take dark deployments out of the load-balancer
|
|
|
|
DeploymentManager.initialise()
|
|
|
|
|
2020-06-23 13:30:48 -04:00
|
|
|
// Set up socket.io server
|
2020-06-23 13:30:51 -04:00
|
|
|
const app = express()
|
2020-06-23 13:30:48 -04:00
|
|
|
|
2024-11-08 05:21:56 -05:00
|
|
|
const server = require('node:http').createServer(app)
|
2023-10-23 08:42:55 -04:00
|
|
|
server.keepAliveTimeout = Settings.keepAliveTimeoutMs
|
2020-08-28 06:47:45 -04:00
|
|
|
const io = require('socket.io').listen(server, {
|
2021-07-13 07:04:45 -04:00
|
|
|
logger: socketIoLogger,
|
2020-08-28 06:47:45 -04:00
|
|
|
})
|
2020-06-23 13:30:48 -04:00
|
|
|
|
|
|
|
// Bind to sessions
|
2020-06-23 13:30:51 -04:00
|
|
|
const sessionStore = new RedisStore({ client: sessionRedisClient })
|
2024-05-23 10:51:27 -04:00
|
|
|
|
|
|
|
if (!Settings.security.sessionSecret) {
|
|
|
|
throw new Error('No SESSION_SECRET provided.')
|
|
|
|
}
|
|
|
|
|
|
|
|
const sessionSecrets = [
|
|
|
|
Settings.security.sessionSecret,
|
|
|
|
Settings.security.sessionSecretUpcoming,
|
|
|
|
Settings.security.sessionSecretFallback,
|
|
|
|
].filter(Boolean)
|
|
|
|
const cookieParser = CookieParser(sessionSecrets)
|
2020-06-23 13:30:51 -04:00
|
|
|
|
|
|
|
const sessionSockets = new SessionSockets(
|
|
|
|
io,
|
|
|
|
sessionStore,
|
|
|
|
cookieParser,
|
|
|
|
Settings.cookieName
|
|
|
|
)
|
|
|
|
|
|
|
|
Metrics.injectMetricsRoute(app)
|
|
|
|
|
|
|
|
io.configure(function () {
|
2022-10-27 06:26:40 -04:00
|
|
|
// Don't use socket.io to serve client
|
|
|
|
io.disable('browser client')
|
2020-06-23 13:30:51 -04:00
|
|
|
|
|
|
|
// Fix for Safari 5 error of "Error during WebSocket handshake: location mismatch"
|
|
|
|
// See http://answers.dotcloud.com/question/578/problem-with-websocket-over-ssl-in-safari-with
|
|
|
|
io.set('match origin protocol', true)
|
|
|
|
|
|
|
|
// gzip uses a Node 0.8.x method of calling the gzip program which
|
|
|
|
// doesn't work with 0.6.x
|
|
|
|
// io.enable('browser client gzip')
|
|
|
|
io.set('transports', [
|
|
|
|
'websocket',
|
|
|
|
'flashsocket',
|
|
|
|
'htmlfile',
|
|
|
|
'xhr-polling',
|
2021-07-13 07:04:45 -04:00
|
|
|
'jsonp-polling',
|
2020-06-23 13:30:51 -04:00
|
|
|
])
|
|
|
|
})
|
|
|
|
|
2022-10-27 06:26:40 -04:00
|
|
|
// Serve socket.io.js client file from imported dist folder
|
|
|
|
// The express sendFile method correctly handles conditional
|
|
|
|
// requests using the last-modified time and etag (which is
|
|
|
|
// a combination of mtime and size)
|
|
|
|
const socketIOClientFolder = require('socket.io-client').dist
|
|
|
|
app.get('/socket.io/socket.io.js', function (req, res) {
|
|
|
|
res.sendFile(Path.join(socketIOClientFolder, 'socket.io.min.js'))
|
|
|
|
})
|
|
|
|
|
2020-11-27 09:42:42 -05:00
|
|
|
// a 200 response on '/' is required for load balancer health checks
|
2021-03-19 12:27:27 -04:00
|
|
|
// these operate separately from kubernetes readiness checks
|
|
|
|
app.get('/', function (req, res) {
|
2021-03-22 07:15:59 -04:00
|
|
|
if (Settings.shutDownInProgress || DeploymentManager.deploymentIsClosed()) {
|
2021-03-19 12:27:27 -04:00
|
|
|
res.sendStatus(503) // Service unavailable
|
|
|
|
} else {
|
|
|
|
res.send('real-time is open')
|
|
|
|
}
|
|
|
|
})
|
2020-06-23 13:30:51 -04:00
|
|
|
|
2020-07-07 06:06:02 -04:00
|
|
|
app.get('/status', function (req, res) {
|
2020-06-23 13:30:51 -04:00
|
|
|
if (Settings.shutDownInProgress) {
|
2020-07-22 04:45:14 -04:00
|
|
|
res.sendStatus(503) // Service unavailable
|
2020-06-23 13:30:51 -04:00
|
|
|
} else {
|
2021-03-19 12:27:27 -04:00
|
|
|
res.send('real-time is alive')
|
2020-06-23 13:30:51 -04:00
|
|
|
}
|
|
|
|
})
|
|
|
|
|
2020-07-07 06:06:02 -04:00
|
|
|
app.get('/debug/events', function (req, res) {
|
|
|
|
Settings.debugEvents = parseInt(req.query.count, 10) || 20
|
2021-09-14 04:36:24 -04:00
|
|
|
logger.info({ count: Settings.debugEvents }, 'starting debug mode')
|
2020-07-07 06:06:02 -04:00
|
|
|
res.send(`debug mode will log next ${Settings.debugEvents} events`)
|
2020-06-23 13:30:51 -04:00
|
|
|
})
|
|
|
|
|
2020-11-10 06:32:06 -05:00
|
|
|
const rclient = require('@overleaf/redis-wrapper').createClient(
|
2020-06-23 13:30:51 -04:00
|
|
|
Settings.redis.realtime
|
|
|
|
)
|
|
|
|
|
2020-07-07 06:06:02 -04:00
|
|
|
function healthCheck(req, res) {
|
2020-06-23 13:30:51 -04:00
|
|
|
rclient.healthCheck(function (error) {
|
2020-07-07 06:06:02 -04:00
|
|
|
if (error) {
|
2020-06-23 13:30:51 -04:00
|
|
|
logger.err({ err: error }, 'failed redis health check')
|
2020-07-07 06:06:02 -04:00
|
|
|
res.sendStatus(500)
|
2020-06-23 13:30:48 -04:00
|
|
|
} else if (HealthCheckManager.isFailing()) {
|
2020-06-23 13:30:51 -04:00
|
|
|
const status = HealthCheckManager.status()
|
|
|
|
logger.err({ pubSubErrors: status }, 'failed pubsub health check')
|
2020-07-07 06:06:02 -04:00
|
|
|
res.sendStatus(500)
|
2020-06-23 13:30:48 -04:00
|
|
|
} else {
|
2020-07-07 06:06:02 -04:00
|
|
|
res.sendStatus(200)
|
2020-06-23 13:30:48 -04:00
|
|
|
}
|
2020-06-23 13:30:51 -04:00
|
|
|
})
|
2020-07-07 06:06:02 -04:00
|
|
|
}
|
2020-08-13 07:39:51 -04:00
|
|
|
app.get(
|
|
|
|
'/health_check',
|
|
|
|
(req, res, next) => {
|
|
|
|
if (Settings.shutDownComplete) {
|
|
|
|
return res.sendStatus(503)
|
|
|
|
}
|
|
|
|
next()
|
|
|
|
},
|
|
|
|
healthCheck
|
|
|
|
)
|
2020-06-23 13:30:48 -04:00
|
|
|
|
2020-06-23 13:30:51 -04:00
|
|
|
app.get('/health_check/redis', healthCheck)
|
2020-06-23 13:30:48 -04:00
|
|
|
|
2021-09-14 04:36:24 -04:00
|
|
|
// log http requests for routes defined from this point onwards
|
|
|
|
app.use(Metrics.http.monitor(logger))
|
|
|
|
|
2020-06-23 13:30:51 -04:00
|
|
|
const Router = require('./app/js/Router')
|
|
|
|
Router.configure(app, io, sessionSockets)
|
2020-06-23 13:30:48 -04:00
|
|
|
|
2020-06-23 13:30:51 -04:00
|
|
|
const WebsocketLoadBalancer = require('./app/js/WebsocketLoadBalancer')
|
|
|
|
WebsocketLoadBalancer.listenForEditorEvents(io)
|
2020-06-23 13:30:48 -04:00
|
|
|
|
2020-06-23 13:30:51 -04:00
|
|
|
const DocumentUpdaterController = require('./app/js/DocumentUpdaterController')
|
|
|
|
DocumentUpdaterController.listenForUpdatesFromDocumentUpdater(io)
|
2020-06-23 13:30:48 -04:00
|
|
|
|
2020-06-23 13:30:51 -04:00
|
|
|
const { port } = Settings.internal.realTime
|
|
|
|
const { host } = Settings.internal.realTime
|
2020-06-23 13:30:48 -04:00
|
|
|
|
2020-06-23 13:30:51 -04:00
|
|
|
server.listen(port, host, function (error) {
|
2020-07-07 06:06:02 -04:00
|
|
|
if (error) {
|
2020-06-23 13:30:51 -04:00
|
|
|
throw error
|
|
|
|
}
|
2020-07-07 06:06:02 -04:00
|
|
|
logger.info(`realtime starting up, listening on ${host}:${port}`)
|
2020-06-23 13:30:51 -04:00
|
|
|
})
|
2020-06-23 13:30:48 -04:00
|
|
|
|
2020-06-23 13:30:51 -04:00
|
|
|
// Stop huge stack traces in logs from all the socket.io parsing steps.
|
|
|
|
Error.stackTraceLimit = 10
|
|
|
|
|
2024-06-25 07:03:05 -04:00
|
|
|
function shutdownAfterAllClientsHaveDisconnected() {
|
2020-07-07 06:06:02 -04:00
|
|
|
const connectedClients = io.sockets.clients().length
|
2020-06-23 13:30:51 -04:00
|
|
|
if (connectedClients === 0) {
|
2024-06-25 07:03:05 -04:00
|
|
|
logger.info({}, 'no clients connected, exiting')
|
2020-07-07 06:06:02 -04:00
|
|
|
process.exit()
|
2020-06-23 13:30:51 -04:00
|
|
|
} else {
|
2021-09-14 04:36:24 -04:00
|
|
|
logger.info(
|
2020-06-23 13:30:51 -04:00
|
|
|
{ connectedClients },
|
|
|
|
'clients still connected, not shutting down yet'
|
|
|
|
)
|
2024-06-25 07:03:05 -04:00
|
|
|
setTimeout(() => shutdownAfterAllClientsHaveDisconnected(), 5_000)
|
2020-06-23 13:30:51 -04:00
|
|
|
}
|
|
|
|
}
|
2020-06-23 13:30:48 -04:00
|
|
|
|
2020-07-07 06:06:02 -04:00
|
|
|
function drainAndShutdown(signal) {
|
2020-06-23 13:30:51 -04:00
|
|
|
if (Settings.shutDownInProgress) {
|
2021-09-14 04:36:24 -04:00
|
|
|
logger.info({ signal }, 'shutdown already in progress, ignoring signal')
|
2020-06-23 13:30:51 -04:00
|
|
|
} else {
|
|
|
|
Settings.shutDownInProgress = true
|
|
|
|
const { statusCheckInterval } = Settings
|
|
|
|
if (statusCheckInterval) {
|
2021-09-14 04:36:24 -04:00
|
|
|
logger.info(
|
2020-06-23 13:30:51 -04:00
|
|
|
{ signal },
|
|
|
|
`received interrupt, delay drain by ${statusCheckInterval}ms`
|
|
|
|
)
|
|
|
|
}
|
2020-07-07 06:06:02 -04:00
|
|
|
setTimeout(function () {
|
2021-09-14 04:36:24 -04:00
|
|
|
logger.info(
|
2020-06-23 13:30:51 -04:00
|
|
|
{ signal },
|
|
|
|
`received interrupt, starting drain over ${shutdownDrainTimeWindow} mins`
|
|
|
|
)
|
2020-08-13 07:12:12 -04:00
|
|
|
DrainManager.startDrainTimeWindow(io, shutdownDrainTimeWindow, () => {
|
2024-06-25 07:03:05 -04:00
|
|
|
shutdownAfterAllClientsHaveDisconnected()
|
2020-08-13 07:12:12 -04:00
|
|
|
setTimeout(() => {
|
|
|
|
const staleClients = io.sockets.clients()
|
|
|
|
if (staleClients.length !== 0) {
|
2021-09-14 04:36:24 -04:00
|
|
|
logger.info(
|
2021-07-13 07:04:45 -04:00
|
|
|
{ staleClients: staleClients.map(client => client.id) },
|
2020-08-13 07:12:12 -04:00
|
|
|
'forcefully disconnecting stale clients'
|
|
|
|
)
|
2021-07-13 07:04:45 -04:00
|
|
|
staleClients.forEach(client => {
|
2020-08-13 07:12:12 -04:00
|
|
|
client.disconnect()
|
|
|
|
})
|
|
|
|
}
|
2020-08-13 07:39:51 -04:00
|
|
|
// Mark the node as unhealthy.
|
|
|
|
Settings.shutDownComplete = true
|
2020-08-13 07:12:12 -04:00
|
|
|
}, Settings.gracefulReconnectTimeoutMs)
|
|
|
|
})
|
2020-06-23 13:30:51 -04:00
|
|
|
}, statusCheckInterval)
|
|
|
|
}
|
|
|
|
}
|
2020-06-23 13:30:48 -04:00
|
|
|
|
2020-06-23 13:30:51 -04:00
|
|
|
Settings.shutDownInProgress = false
|
2020-07-07 06:06:02 -04:00
|
|
|
const shutdownDrainTimeWindow = parseInt(Settings.shutdownDrainTimeWindow, 10)
|
|
|
|
if (Settings.shutdownDrainTimeWindow) {
|
2021-09-14 04:36:24 -04:00
|
|
|
logger.info({ shutdownDrainTimeWindow }, 'shutdownDrainTimeWindow enabled')
|
2020-06-23 13:30:51 -04:00
|
|
|
for (const signal of [
|
|
|
|
'SIGINT',
|
|
|
|
'SIGHUP',
|
|
|
|
'SIGQUIT',
|
|
|
|
'SIGUSR1',
|
|
|
|
'SIGUSR2',
|
|
|
|
'SIGTERM',
|
2021-07-13 07:04:45 -04:00
|
|
|
'SIGABRT',
|
2020-06-23 13:30:51 -04:00
|
|
|
]) {
|
|
|
|
process.on(signal, drainAndShutdown)
|
|
|
|
} // signal is passed as argument to event handler
|
|
|
|
|
|
|
|
// global exception handler
|
2020-07-07 06:06:02 -04:00
|
|
|
if (Settings.errors && Settings.errors.catchUncaughtErrors) {
|
2020-06-23 13:30:51 -04:00
|
|
|
process.removeAllListeners('uncaughtException')
|
|
|
|
process.on('uncaughtException', function (error) {
|
2020-08-12 06:45:36 -04:00
|
|
|
if (
|
2020-09-22 09:10:23 -04:00
|
|
|
[
|
|
|
|
'ETIMEDOUT',
|
|
|
|
'EHOSTUNREACH',
|
|
|
|
'EPIPE',
|
|
|
|
'ECONNRESET',
|
2021-07-13 07:04:45 -04:00
|
|
|
'ERR_STREAM_WRITE_AFTER_END',
|
2020-09-22 09:10:23 -04:00
|
|
|
].includes(error.code)
|
2020-08-12 06:45:36 -04:00
|
|
|
) {
|
2020-06-23 13:30:51 -04:00
|
|
|
Metrics.inc('disconnected_write', 1, { status: error.code })
|
|
|
|
return logger.warn(
|
|
|
|
{ err: error },
|
|
|
|
'attempted to write to disconnected client'
|
|
|
|
)
|
|
|
|
}
|
|
|
|
logger.error({ err: error }, 'uncaught exception')
|
2020-07-07 06:06:02 -04:00
|
|
|
if (Settings.errors && Settings.errors.shutdownOnUncaughtError) {
|
|
|
|
drainAndShutdown('SIGABRT')
|
2020-06-23 13:30:51 -04:00
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
2020-06-23 13:30:48 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
if (Settings.continualPubsubTraffic) {
|
2021-09-14 04:36:24 -04:00
|
|
|
logger.debug('continualPubsubTraffic enabled')
|
2020-06-23 13:30:51 -04:00
|
|
|
|
|
|
|
const pubsubClient = redis.createClient(Settings.redis.pubsub)
|
|
|
|
const clusterClient = redis.createClient(Settings.redis.websessions)
|
|
|
|
|
|
|
|
const publishJob = function (channel, callback) {
|
|
|
|
const checker = new HealthCheckManager(channel)
|
|
|
|
logger.debug({ channel }, 'sending pub to keep connection alive')
|
|
|
|
const json = JSON.stringify({
|
|
|
|
health_check: true,
|
|
|
|
key: checker.id,
|
2021-07-13 07:04:45 -04:00
|
|
|
date: new Date().toString(),
|
2020-06-23 13:30:51 -04:00
|
|
|
})
|
|
|
|
Metrics.summary(`redis.publish.${channel}`, json.length)
|
2020-07-07 06:06:02 -04:00
|
|
|
pubsubClient.publish(channel, json, function (err) {
|
|
|
|
if (err) {
|
2020-06-23 13:30:51 -04:00
|
|
|
logger.err({ err, channel }, 'error publishing pubsub traffic to redis')
|
|
|
|
}
|
|
|
|
const blob = JSON.stringify({ keep: 'alive' })
|
|
|
|
Metrics.summary('redis.publish.cluster-continual-traffic', blob.length)
|
2020-07-07 06:06:02 -04:00
|
|
|
clusterClient.publish('cluster-continual-traffic', blob, callback)
|
2020-06-23 13:30:51 -04:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2020-07-07 06:06:02 -04:00
|
|
|
const runPubSubTraffic = () =>
|
2020-06-24 05:41:55 -04:00
|
|
|
async.map(['applied-ops', 'editor-events'], publishJob, () =>
|
2020-06-23 13:30:51 -04:00
|
|
|
setTimeout(runPubSubTraffic, 1000 * 20)
|
|
|
|
)
|
|
|
|
|
|
|
|
runPubSubTraffic()
|
2020-06-23 13:30:48 -04:00
|
|
|
}
|