app.js 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. // Metrics must be initialized before importing anything else
  2. require('@overleaf/metrics/initialize')
  3. const Metrics = require('@overleaf/metrics')
  4. const Settings = require('@overleaf/settings')
  5. const async = require('async')
  6. const logger = require('@overleaf/logger')
  7. logger.initialize('real-time')
  8. Metrics.event_loop.monitor(logger)
  9. Metrics.open_sockets.monitor()
  10. const express = require('express')
  11. const session = require('express-session')
  12. const redis = require('@overleaf/redis-wrapper')
  13. if (Settings.sentry && Settings.sentry.dsn) {
  14. logger.initializeErrorReporting(Settings.sentry.dsn)
  15. }
  16. const sessionRedisClient = redis.createClient(Settings.redis.websessions)
  17. const RedisStore = require('connect-redis')(session)
  18. const SessionSockets = require('./app/js/SessionSockets')
  19. const CookieParser = require('cookie-parser')
  20. const DrainManager = require('./app/js/DrainManager')
  21. const HealthCheckManager = require('./app/js/HealthCheckManager')
  22. const DeploymentManager = require('./app/js/DeploymentManager')
  23. const Path = require('path')
  24. // NOTE: debug is invoked for every blob that is put on the wire
  25. const socketIoLogger = {
  26. error(...message) {
  27. logger.debug({ fromSocketIo: true, originalLevel: 'error' }, ...message)
  28. },
  29. warn(...message) {
  30. logger.debug({ fromSocketIo: true, originalLevel: 'warn' }, ...message)
  31. },
  32. info() {},
  33. debug() {},
  34. log() {},
  35. }
  36. // monitor status file to take dark deployments out of the load-balancer
  37. DeploymentManager.initialise()
  38. // Set up socket.io server
  39. const app = express()
  40. const server = require('http').createServer(app)
  41. server.keepAliveTimeout = Settings.keepAliveTimeoutMs
  42. const io = require('socket.io').listen(server, {
  43. logger: socketIoLogger,
  44. })
  45. // Bind to sessions
  46. const sessionStore = new RedisStore({ client: sessionRedisClient })
  47. const cookieParser = CookieParser(Settings.security.sessionSecret)
  48. const sessionSockets = new SessionSockets(
  49. io,
  50. sessionStore,
  51. cookieParser,
  52. Settings.cookieName
  53. )
  54. Metrics.injectMetricsRoute(app)
  55. io.configure(function () {
  56. // Don't use socket.io to serve client
  57. io.disable('browser client')
  58. // Fix for Safari 5 error of "Error during WebSocket handshake: location mismatch"
  59. // See http://answers.dotcloud.com/question/578/problem-with-websocket-over-ssl-in-safari-with
  60. io.set('match origin protocol', true)
  61. // gzip uses a Node 0.8.x method of calling the gzip program which
  62. // doesn't work with 0.6.x
  63. // io.enable('browser client gzip')
  64. io.set('transports', [
  65. 'websocket',
  66. 'flashsocket',
  67. 'htmlfile',
  68. 'xhr-polling',
  69. 'jsonp-polling',
  70. ])
  71. })
  72. // Serve socket.io.js client file from imported dist folder
  73. // The express sendFile method correctly handles conditional
  74. // requests using the last-modified time and etag (which is
  75. // a combination of mtime and size)
  76. const socketIOClientFolder = require('socket.io-client').dist
  77. app.get('/socket.io/socket.io.js', function (req, res) {
  78. res.sendFile(Path.join(socketIOClientFolder, 'socket.io.min.js'))
  79. })
  80. // a 200 response on '/' is required for load balancer health checks
  81. // these operate separately from kubernetes readiness checks
  82. app.get('/', function (req, res) {
  83. if (Settings.shutDownInProgress || DeploymentManager.deploymentIsClosed()) {
  84. res.sendStatus(503) // Service unavailable
  85. } else {
  86. res.send('real-time is open')
  87. }
  88. })
  89. app.get('/status', function (req, res) {
  90. if (Settings.shutDownInProgress) {
  91. res.sendStatus(503) // Service unavailable
  92. } else {
  93. res.send('real-time is alive')
  94. }
  95. })
  96. app.get('/debug/events', function (req, res) {
  97. Settings.debugEvents = parseInt(req.query.count, 10) || 20
  98. logger.info({ count: Settings.debugEvents }, 'starting debug mode')
  99. res.send(`debug mode will log next ${Settings.debugEvents} events`)
  100. })
  101. const rclient = require('@overleaf/redis-wrapper').createClient(
  102. Settings.redis.realtime
  103. )
  104. function healthCheck(req, res) {
  105. rclient.healthCheck(function (error) {
  106. if (error) {
  107. logger.err({ err: error }, 'failed redis health check')
  108. res.sendStatus(500)
  109. } else if (HealthCheckManager.isFailing()) {
  110. const status = HealthCheckManager.status()
  111. logger.err({ pubSubErrors: status }, 'failed pubsub health check')
  112. res.sendStatus(500)
  113. } else {
  114. res.sendStatus(200)
  115. }
  116. })
  117. }
  118. app.get(
  119. '/health_check',
  120. (req, res, next) => {
  121. if (Settings.shutDownComplete) {
  122. return res.sendStatus(503)
  123. }
  124. next()
  125. },
  126. healthCheck
  127. )
  128. app.get('/health_check/redis', healthCheck)
  129. // log http requests for routes defined from this point onwards
  130. app.use(Metrics.http.monitor(logger))
  131. const Router = require('./app/js/Router')
  132. Router.configure(app, io, sessionSockets)
  133. const WebsocketLoadBalancer = require('./app/js/WebsocketLoadBalancer')
  134. WebsocketLoadBalancer.listenForEditorEvents(io)
  135. const DocumentUpdaterController = require('./app/js/DocumentUpdaterController')
  136. DocumentUpdaterController.listenForUpdatesFromDocumentUpdater(io)
  137. const { port } = Settings.internal.realTime
  138. const { host } = Settings.internal.realTime
  139. server.listen(port, host, function (error) {
  140. if (error) {
  141. throw error
  142. }
  143. logger.info(`realtime starting up, listening on ${host}:${port}`)
  144. })
  145. // Stop huge stack traces in logs from all the socket.io parsing steps.
  146. Error.stackTraceLimit = 10
  147. function shutdownCleanly(signal) {
  148. const connectedClients = io.sockets.clients().length
  149. if (connectedClients === 0) {
  150. logger.info('no clients connected, exiting')
  151. process.exit()
  152. } else {
  153. logger.info(
  154. { connectedClients },
  155. 'clients still connected, not shutting down yet'
  156. )
  157. setTimeout(() => shutdownCleanly(signal), 30 * 1000)
  158. }
  159. }
  160. function drainAndShutdown(signal) {
  161. if (Settings.shutDownInProgress) {
  162. logger.info({ signal }, 'shutdown already in progress, ignoring signal')
  163. } else {
  164. Settings.shutDownInProgress = true
  165. const { statusCheckInterval } = Settings
  166. if (statusCheckInterval) {
  167. logger.info(
  168. { signal },
  169. `received interrupt, delay drain by ${statusCheckInterval}ms`
  170. )
  171. }
  172. setTimeout(function () {
  173. logger.info(
  174. { signal },
  175. `received interrupt, starting drain over ${shutdownDrainTimeWindow} mins`
  176. )
  177. DrainManager.startDrainTimeWindow(io, shutdownDrainTimeWindow, () => {
  178. setTimeout(() => {
  179. const staleClients = io.sockets.clients()
  180. if (staleClients.length !== 0) {
  181. logger.info(
  182. { staleClients: staleClients.map(client => client.id) },
  183. 'forcefully disconnecting stale clients'
  184. )
  185. staleClients.forEach(client => {
  186. client.disconnect()
  187. })
  188. }
  189. // Mark the node as unhealthy.
  190. Settings.shutDownComplete = true
  191. }, Settings.gracefulReconnectTimeoutMs)
  192. })
  193. shutdownCleanly(signal)
  194. }, statusCheckInterval)
  195. }
  196. }
  197. Settings.shutDownInProgress = false
  198. const shutdownDrainTimeWindow = parseInt(Settings.shutdownDrainTimeWindow, 10)
  199. if (Settings.shutdownDrainTimeWindow) {
  200. logger.info({ shutdownDrainTimeWindow }, 'shutdownDrainTimeWindow enabled')
  201. for (const signal of [
  202. 'SIGINT',
  203. 'SIGHUP',
  204. 'SIGQUIT',
  205. 'SIGUSR1',
  206. 'SIGUSR2',
  207. 'SIGTERM',
  208. 'SIGABRT',
  209. ]) {
  210. process.on(signal, drainAndShutdown)
  211. } // signal is passed as argument to event handler
  212. // global exception handler
  213. if (Settings.errors && Settings.errors.catchUncaughtErrors) {
  214. process.removeAllListeners('uncaughtException')
  215. process.on('uncaughtException', function (error) {
  216. if (
  217. [
  218. 'ETIMEDOUT',
  219. 'EHOSTUNREACH',
  220. 'EPIPE',
  221. 'ECONNRESET',
  222. 'ERR_STREAM_WRITE_AFTER_END',
  223. ].includes(error.code)
  224. ) {
  225. Metrics.inc('disconnected_write', 1, { status: error.code })
  226. return logger.warn(
  227. { err: error },
  228. 'attempted to write to disconnected client'
  229. )
  230. }
  231. logger.error({ err: error }, 'uncaught exception')
  232. if (Settings.errors && Settings.errors.shutdownOnUncaughtError) {
  233. drainAndShutdown('SIGABRT')
  234. }
  235. })
  236. }
  237. }
  238. if (Settings.continualPubsubTraffic) {
  239. logger.debug('continualPubsubTraffic enabled')
  240. const pubsubClient = redis.createClient(Settings.redis.pubsub)
  241. const clusterClient = redis.createClient(Settings.redis.websessions)
  242. const publishJob = function (channel, callback) {
  243. const checker = new HealthCheckManager(channel)
  244. logger.debug({ channel }, 'sending pub to keep connection alive')
  245. const json = JSON.stringify({
  246. health_check: true,
  247. key: checker.id,
  248. date: new Date().toString(),
  249. })
  250. Metrics.summary(`redis.publish.${channel}`, json.length)
  251. pubsubClient.publish(channel, json, function (err) {
  252. if (err) {
  253. logger.err({ err, channel }, 'error publishing pubsub traffic to redis')
  254. }
  255. const blob = JSON.stringify({ keep: 'alive' })
  256. Metrics.summary('redis.publish.cluster-continual-traffic', blob.length)
  257. clusterClient.publish('cluster-continual-traffic', blob, callback)
  258. })
  259. }
  260. const runPubSubTraffic = () =>
  261. async.map(['applied-ops', 'editor-events'], publishJob, () =>
  262. setTimeout(runPubSubTraffic, 1000 * 20)
  263. )
  264. runPubSubTraffic()
  265. }