app.js 8.1 KB

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