app.js 11 KB

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