app.js 7.6 KB

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