app.js 8.5 KB

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