app.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. const Metrics = require('@overleaf/metrics')
  2. Metrics.initialize('clsi')
  3. const CompileController = require('./app/js/CompileController')
  4. const ContentController = require('./app/js/ContentController')
  5. const Settings = require('@overleaf/settings')
  6. const logger = require('@overleaf/logger')
  7. logger.initialize('clsi')
  8. if (Settings.sentry.dsn != null) {
  9. logger.initializeErrorReporting(Settings.sentry.dsn)
  10. }
  11. const smokeTest = require('./test/smoke/js/SmokeTests')
  12. const ContentTypeMapper = require('./app/js/ContentTypeMapper')
  13. const Errors = require('./app/js/Errors')
  14. const Path = require('path')
  15. Metrics.open_sockets.monitor(logger)
  16. Metrics.memory.monitor(logger)
  17. const ProjectPersistenceManager = require('./app/js/ProjectPersistenceManager')
  18. const OutputCacheManager = require('./app/js/OutputCacheManager')
  19. const ContentCacheManager = require('./app/js/ContentCacheManager')
  20. ProjectPersistenceManager.init()
  21. OutputCacheManager.init()
  22. const express = require('express')
  23. const bodyParser = require('body-parser')
  24. const app = express()
  25. Metrics.injectMetricsRoute(app)
  26. app.use(Metrics.http.monitor(logger))
  27. // Compile requests can take longer than the default two
  28. // minutes (including file download time), so bump up the
  29. // timeout a bit.
  30. const TIMEOUT = 10 * 60 * 1000
  31. app.use(function (req, res, next) {
  32. req.setTimeout(TIMEOUT)
  33. res.setTimeout(TIMEOUT)
  34. res.removeHeader('X-Powered-By')
  35. next()
  36. })
  37. app.param('project_id', function (req, res, next, projectId) {
  38. if (projectId?.match(/^[a-zA-Z0-9_-]+$/)) {
  39. next()
  40. } else {
  41. next(new Error('invalid project id'))
  42. }
  43. })
  44. app.param('user_id', function (req, res, next, userId) {
  45. if (userId?.match(/^[0-9a-f]{24}$/)) {
  46. next()
  47. } else {
  48. next(new Error('invalid user id'))
  49. }
  50. })
  51. app.param('build_id', function (req, res, next, buildId) {
  52. if (buildId?.match(OutputCacheManager.BUILD_REGEX)) {
  53. next()
  54. } else {
  55. next(new Error(`invalid build id ${buildId}`))
  56. }
  57. })
  58. app.param('contentId', function (req, res, next, contentId) {
  59. if (contentId?.match(OutputCacheManager.CONTENT_REGEX)) {
  60. next()
  61. } else {
  62. next(new Error(`invalid content id ${contentId}`))
  63. }
  64. })
  65. app.param('hash', function (req, res, next, hash) {
  66. if (hash?.match(ContentCacheManager.HASH_REGEX)) {
  67. next()
  68. } else {
  69. next(new Error(`invalid hash ${hash}`))
  70. }
  71. })
  72. app.post(
  73. '/project/:project_id/compile',
  74. bodyParser.json({ limit: Settings.compileSizeLimit }),
  75. CompileController.compile
  76. )
  77. app.post('/project/:project_id/compile/stop', CompileController.stopCompile)
  78. app.delete('/project/:project_id', CompileController.clearCache)
  79. app.get('/project/:project_id/sync/code', CompileController.syncFromCode)
  80. app.get('/project/:project_id/sync/pdf', CompileController.syncFromPdf)
  81. app.get('/project/:project_id/wordcount', CompileController.wordcount)
  82. app.get('/project/:project_id/status', CompileController.status)
  83. app.post('/project/:project_id/status', CompileController.status)
  84. // Per-user containers
  85. app.post(
  86. '/project/:project_id/user/:user_id/compile',
  87. bodyParser.json({ limit: Settings.compileSizeLimit }),
  88. CompileController.compile
  89. )
  90. app.post(
  91. '/project/:project_id/user/:user_id/compile/stop',
  92. CompileController.stopCompile
  93. )
  94. app.delete('/project/:project_id/user/:user_id', CompileController.clearCache)
  95. app.get(
  96. '/project/:project_id/user/:user_id/sync/code',
  97. CompileController.syncFromCode
  98. )
  99. app.get(
  100. '/project/:project_id/user/:user_id/sync/pdf',
  101. CompileController.syncFromPdf
  102. )
  103. app.get(
  104. '/project/:project_id/user/:user_id/wordcount',
  105. CompileController.wordcount
  106. )
  107. const ForbidSymlinks = require('./app/js/StaticServerForbidSymlinks')
  108. // create a static server which does not allow access to any symlinks
  109. // avoids possible mismatch of root directory between middleware check
  110. // and serving the files
  111. const staticCompileServer = ForbidSymlinks(
  112. express.static,
  113. Settings.path.compilesDir,
  114. {
  115. setHeaders(res, path, stat) {
  116. if (Path.basename(path) === 'output.pdf') {
  117. // Calculate an etag in the same way as nginx
  118. // https://github.com/tj/send/issues/65
  119. const etag = (path, stat) =>
  120. `"${Math.ceil(+stat.mtime / 1000).toString(16)}` +
  121. '-' +
  122. Number(stat.size).toString(16) +
  123. '"'
  124. res.set('Etag', etag(path, stat))
  125. }
  126. res.set('Content-Type', ContentTypeMapper.map(path))
  127. },
  128. }
  129. )
  130. const staticOutputServer = ForbidSymlinks(
  131. express.static,
  132. Settings.path.outputDir,
  133. {
  134. setHeaders(res, path, stat) {
  135. if (Path.basename(path) === 'output.pdf') {
  136. // Calculate an etag in the same way as nginx
  137. // https://github.com/tj/send/issues/65
  138. const etag = (path, stat) =>
  139. `"${Math.ceil(+stat.mtime / 1000).toString(16)}` +
  140. '-' +
  141. Number(stat.size).toString(16) +
  142. '"'
  143. res.set('Etag', etag(path, stat))
  144. }
  145. res.set('Content-Type', ContentTypeMapper.map(path))
  146. },
  147. }
  148. )
  149. app.get(
  150. '/project/:project_id/user/:user_id/build/:build_id/output/*',
  151. function (req, res, next) {
  152. // for specific build get the path from the OutputCacheManager (e.g. .clsi/buildId)
  153. req.url =
  154. `/${req.params.project_id}-${req.params.user_id}/` +
  155. OutputCacheManager.path(req.params.build_id, `/${req.params[0]}`)
  156. staticOutputServer(req, res, next)
  157. }
  158. )
  159. app.get(
  160. '/project/:projectId/content/:contentId/:hash',
  161. ContentController.getPdfRange
  162. )
  163. app.get(
  164. '/project/:projectId/user/:userId/content/:contentId/:hash',
  165. ContentController.getPdfRange
  166. )
  167. app.get(
  168. '/project/:project_id/build/:build_id/output/*',
  169. function (req, res, next) {
  170. // for specific build get the path from the OutputCacheManager (e.g. .clsi/buildId)
  171. req.url =
  172. `/${req.params.project_id}/` +
  173. OutputCacheManager.path(req.params.build_id, `/${req.params[0]}`)
  174. staticOutputServer(req, res, next)
  175. }
  176. )
  177. app.get(
  178. '/project/:project_id/user/:user_id/output/*',
  179. function (req, res, next) {
  180. // for specific user get the path to the top level file
  181. logger.warn(
  182. { url: req.url },
  183. 'direct request for file in compile directory'
  184. )
  185. req.url = `/${req.params.project_id}-${req.params.user_id}/${req.params[0]}`
  186. staticCompileServer(req, res, next)
  187. }
  188. )
  189. app.get('/project/:project_id/output/*', function (req, res, next) {
  190. logger.warn({ url: req.url }, 'direct request for file in compile directory')
  191. if (req.query?.build?.match(OutputCacheManager.BUILD_REGEX)) {
  192. // for specific build get the path from the OutputCacheManager (e.g. .clsi/buildId)
  193. req.url =
  194. `/${req.params.project_id}/` +
  195. OutputCacheManager.path(req.query.build, `/${req.params[0]}`)
  196. } else {
  197. req.url = `/${req.params.project_id}/${req.params[0]}`
  198. }
  199. staticCompileServer(req, res, next)
  200. })
  201. app.get('/oops', function (req, res, next) {
  202. logger.error({ err: 'hello' }, 'test error')
  203. res.send('error\n')
  204. })
  205. app.get('/oops-internal', function (req, res, next) {
  206. setTimeout(function () {
  207. throw new Error('Test error')
  208. }, 1)
  209. })
  210. app.get('/status', (req, res, next) => res.send('CLSI is alive\n'))
  211. Settings.processTooOld = false
  212. if (Settings.processLifespanLimitMs) {
  213. Settings.processLifespanLimitMs +=
  214. Settings.processLifespanLimitMs * (Math.random() / 10)
  215. logger.debug(
  216. 'Lifespan limited to ',
  217. Date.now() + Settings.processLifespanLimitMs
  218. )
  219. setTimeout(() => {
  220. logger.debug('shutting down, process is too old')
  221. Settings.processTooOld = true
  222. }, Settings.processLifespanLimitMs)
  223. }
  224. function runSmokeTest() {
  225. if (Settings.processTooOld) return
  226. const INTERVAL = 30 * 1000
  227. if (
  228. smokeTest.lastRunSuccessful() &&
  229. CompileController.timeSinceLastSuccessfulCompile() < INTERVAL / 2
  230. ) {
  231. logger.debug('skipping smoke tests, got recent successful user compile')
  232. return setTimeout(runSmokeTest, INTERVAL / 2)
  233. }
  234. logger.debug('running smoke tests')
  235. smokeTest.triggerRun(err => {
  236. if (err) logger.error({ err }, 'smoke tests failed')
  237. setTimeout(runSmokeTest, INTERVAL)
  238. })
  239. }
  240. if (Settings.smokeTest) {
  241. runSmokeTest()
  242. }
  243. app.get('/health_check', function (req, res) {
  244. if (Settings.processTooOld) {
  245. return res.status(500).json({ processTooOld: true })
  246. }
  247. smokeTest.sendLastResult(res)
  248. })
  249. app.get('/smoke_test_force', (req, res) => smokeTest.sendNewResult(res))
  250. app.use(function (error, req, res, next) {
  251. if (error instanceof Errors.NotFoundError) {
  252. logger.debug({ err: error, url: req.url }, 'not found error')
  253. res.sendStatus(404)
  254. } else if (error.code === 'EPIPE') {
  255. // inspect container returns EPIPE when shutting down
  256. res.sendStatus(503) // send 503 Unavailable response
  257. } else {
  258. logger.error({ err: error, url: req.url }, 'server error')
  259. res.sendStatus(error.statusCode || 500)
  260. }
  261. })
  262. const net = require('net')
  263. const os = require('os')
  264. let STATE = 'up'
  265. const loadTcpServer = net.createServer(function (socket) {
  266. socket.on('error', function (err) {
  267. if (err.code === 'ECONNRESET') {
  268. // this always comes up, we don't know why
  269. return
  270. }
  271. logger.err({ err }, 'error with socket on load check')
  272. socket.destroy()
  273. })
  274. if (STATE === 'up' && Settings.internal.load_balancer_agent.report_load) {
  275. let availableWorkingCpus
  276. const currentLoad = os.loadavg()[0]
  277. // staging clis's have 1 cpu core only
  278. if (os.cpus().length === 1) {
  279. availableWorkingCpus = 1
  280. } else {
  281. availableWorkingCpus = os.cpus().length - 1
  282. }
  283. const freeLoad = availableWorkingCpus - currentLoad
  284. const freeLoadPercentage = Math.round(
  285. (freeLoad / availableWorkingCpus) * 100
  286. )
  287. if (freeLoadPercentage <= 0) {
  288. // When its 0 the server is set to drain implicitly.
  289. // Drain will move new projects to different servers.
  290. // Drain will keep existing projects assigned to the same server.
  291. // Maint will more existing and new projects to different servers.
  292. socket.write(`maint, 0%\n`, 'ASCII')
  293. } else {
  294. // Ready will cancel the maint state.
  295. socket.write(`up, ready, ${freeLoadPercentage}%\n`, 'ASCII')
  296. }
  297. socket.end()
  298. } else {
  299. socket.write(`${STATE}\n`, 'ASCII')
  300. socket.end()
  301. }
  302. })
  303. const loadHttpServer = express()
  304. loadHttpServer.post('/state/up', function (req, res, next) {
  305. STATE = 'up'
  306. logger.debug('getting message to set server to down')
  307. res.sendStatus(204)
  308. })
  309. loadHttpServer.post('/state/down', function (req, res, next) {
  310. STATE = 'down'
  311. logger.debug('getting message to set server to down')
  312. res.sendStatus(204)
  313. })
  314. loadHttpServer.post('/state/maint', function (req, res, next) {
  315. STATE = 'maint'
  316. logger.debug('getting message to set server to maint')
  317. res.sendStatus(204)
  318. })
  319. const port = Settings.internal?.clsi?.port || 3013
  320. const host = Settings.internal?.clsi?.host || 'localhost'
  321. const loadTcpPort = Settings.internal.load_balancer_agent.load_port
  322. const loadHttpPort = Settings.internal.load_balancer_agent.local_port
  323. if (!module.parent) {
  324. // Called directly
  325. // handle uncaught exceptions when running in production
  326. if (Settings.catchErrors) {
  327. process.removeAllListeners('uncaughtException')
  328. process.on('uncaughtException', error =>
  329. logger.error({ err: error }, 'uncaughtException')
  330. )
  331. }
  332. app.listen(port, host, error => {
  333. if (error) {
  334. logger.fatal({ error }, `Error starting CLSI on ${host}:${port}`)
  335. } else {
  336. logger.debug(`CLSI starting up, listening on ${host}:${port}`)
  337. }
  338. })
  339. loadTcpServer.listen(loadTcpPort, host, function (error) {
  340. if (error != null) {
  341. throw error
  342. }
  343. logger.debug(`Load tcp agent listening on load port ${loadTcpPort}`)
  344. })
  345. loadHttpServer.listen(loadHttpPort, host, function (error) {
  346. if (error != null) {
  347. throw error
  348. }
  349. logger.debug(`Load http agent listening on load port ${loadHttpPort}`)
  350. })
  351. }
  352. module.exports = app