app.js 12 KB

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