app.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  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 Metrics = require('@overleaf/metrics')
  9. Metrics.initialize('clsi')
  10. const CompileController = require('./app/js/CompileController')
  11. const ContentController = require('./app/js/ContentController')
  12. const Settings = require('@overleaf/settings')
  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. const ContentCacheManager = require('./app/js/ContentCacheManager')
  27. ProjectPersistenceManager.init()
  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.param('contentId', function (req, res, next, contentId) {
  67. if (
  68. contentId != null
  69. ? contentId.match(OutputCacheManager.CONTENT_REGEX)
  70. : undefined
  71. ) {
  72. return next()
  73. } else {
  74. return next(new Error(`invalid content id ${contentId}`))
  75. }
  76. })
  77. app.param('hash', function (req, res, next, hash) {
  78. if (hash != null ? hash.match(ContentCacheManager.HASH_REGEX) : undefined) {
  79. return next()
  80. } else {
  81. return next(new Error(`invalid hash ${hash}`))
  82. }
  83. })
  84. app.post(
  85. '/project/:project_id/compile',
  86. bodyParser.json({ limit: Settings.compileSizeLimit }),
  87. CompileController.compile
  88. )
  89. app.post('/project/:project_id/compile/stop', CompileController.stopCompile)
  90. app.delete('/project/:project_id', CompileController.clearCache)
  91. app.get('/project/:project_id/sync/code', CompileController.syncFromCode)
  92. app.get('/project/:project_id/sync/pdf', CompileController.syncFromPdf)
  93. app.get('/project/:project_id/wordcount', CompileController.wordcount)
  94. app.get('/project/:project_id/status', CompileController.status)
  95. app.post('/project/:project_id/status', CompileController.status)
  96. // Per-user containers
  97. app.post(
  98. '/project/:project_id/user/:user_id/compile',
  99. bodyParser.json({ limit: Settings.compileSizeLimit }),
  100. CompileController.compile
  101. )
  102. app.post(
  103. '/project/:project_id/user/:user_id/compile/stop',
  104. CompileController.stopCompile
  105. )
  106. app.delete('/project/:project_id/user/:user_id', CompileController.clearCache)
  107. app.get(
  108. '/project/:project_id/user/:user_id/sync/code',
  109. CompileController.syncFromCode
  110. )
  111. app.get(
  112. '/project/:project_id/user/:user_id/sync/pdf',
  113. CompileController.syncFromPdf
  114. )
  115. app.get(
  116. '/project/:project_id/user/:user_id/wordcount',
  117. CompileController.wordcount
  118. )
  119. const ForbidSymlinks = require('./app/js/StaticServerForbidSymlinks')
  120. // create a static server which does not allow access to any symlinks
  121. // avoids possible mismatch of root directory between middleware check
  122. // and serving the files
  123. const staticCompileServer = ForbidSymlinks(
  124. express.static,
  125. Settings.path.compilesDir,
  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. const staticOutputServer = ForbidSymlinks(
  143. express.static,
  144. Settings.path.outputDir,
  145. {
  146. setHeaders(res, path, stat) {
  147. if (Path.basename(path) === 'output.pdf') {
  148. // Calculate an etag in the same way as nginx
  149. // https://github.com/tj/send/issues/65
  150. const etag = (path, stat) =>
  151. `"${Math.ceil(+stat.mtime / 1000).toString(16)}` +
  152. '-' +
  153. Number(stat.size).toString(16) +
  154. '"'
  155. res.set('Etag', etag(path, stat))
  156. }
  157. return res.set('Content-Type', ContentTypeMapper.map(path))
  158. },
  159. }
  160. )
  161. app.get(
  162. '/project/:project_id/user/:user_id/build/:build_id/output/*',
  163. function (req, res, next) {
  164. // for specific build get the path from the OutputCacheManager (e.g. .clsi/buildId)
  165. req.url =
  166. `/${req.params.project_id}-${req.params.user_id}/` +
  167. OutputCacheManager.path(req.params.build_id, `/${req.params[0]}`)
  168. return staticOutputServer(req, res, next)
  169. }
  170. )
  171. app.get(
  172. '/project/:projectId/content/:contentId/:hash',
  173. ContentController.getPdfRange
  174. )
  175. app.get(
  176. '/project/:projectId/user/:userId/content/:contentId/:hash',
  177. ContentController.getPdfRange
  178. )
  179. app.get(
  180. '/project/:project_id/build/:build_id/output/*',
  181. function (req, res, next) {
  182. // for specific build get the path from the OutputCacheManager (e.g. .clsi/buildId)
  183. req.url =
  184. `/${req.params.project_id}/` +
  185. OutputCacheManager.path(req.params.build_id, `/${req.params[0]}`)
  186. return staticOutputServer(req, res, next)
  187. }
  188. )
  189. app.get(
  190. '/project/:project_id/user/:user_id/output/*',
  191. function (req, res, next) {
  192. // for specific user get the path to the top level file
  193. logger.warn(
  194. { url: req.url },
  195. 'direct request for file in compile directory'
  196. )
  197. req.url = `/${req.params.project_id}-${req.params.user_id}/${req.params[0]}`
  198. return staticCompileServer(req, res, next)
  199. }
  200. )
  201. app.get('/project/:project_id/output/*', function (req, res, next) {
  202. logger.warn({ url: req.url }, 'direct request for file in compile directory')
  203. if (
  204. (req.query != null ? req.query.build : undefined) != null &&
  205. req.query.build.match(OutputCacheManager.BUILD_REGEX)
  206. ) {
  207. // for specific build get the path from the OutputCacheManager (e.g. .clsi/buildId)
  208. req.url =
  209. `/${req.params.project_id}/` +
  210. OutputCacheManager.path(req.query.build, `/${req.params[0]}`)
  211. } else {
  212. req.url = `/${req.params.project_id}/${req.params[0]}`
  213. }
  214. return staticCompileServer(req, res, next)
  215. })
  216. app.get('/oops', function (req, res, next) {
  217. logger.error({ err: 'hello' }, 'test error')
  218. return res.send('error\n')
  219. })
  220. app.get('/oops-internal', function (req, res, next) {
  221. setTimeout(function () {
  222. throw new Error('Test error')
  223. }, 1)
  224. })
  225. app.get('/status', (req, res, next) => res.send('CLSI is alive\n'))
  226. Settings.processTooOld = false
  227. if (Settings.processLifespanLimitMs) {
  228. Settings.processLifespanLimitMs +=
  229. Settings.processLifespanLimitMs * (Math.random() / 10)
  230. logger.info(
  231. 'Lifespan limited to ',
  232. Date.now() + Settings.processLifespanLimitMs
  233. )
  234. setTimeout(() => {
  235. logger.log('shutting down, process is too old')
  236. Settings.processTooOld = true
  237. }, Settings.processLifespanLimitMs)
  238. }
  239. function runSmokeTest() {
  240. if (Settings.processTooOld) return
  241. logger.log('running smoke tests')
  242. smokeTest.triggerRun(err => {
  243. if (err) logger.error({ err }, 'smoke tests failed')
  244. setTimeout(runSmokeTest, 30 * 1000)
  245. })
  246. }
  247. if (Settings.smokeTest) {
  248. runSmokeTest()
  249. }
  250. app.get('/health_check', function (req, res) {
  251. if (Settings.processTooOld) {
  252. return res.status(500).json({ processTooOld: true })
  253. }
  254. smokeTest.sendLastResult(res)
  255. })
  256. app.get('/smoke_test_force', (req, res) => smokeTest.sendNewResult(res))
  257. app.use(function (error, req, res, next) {
  258. if (error instanceof Errors.NotFoundError) {
  259. logger.log({ err: error, url: req.url }, 'not found error')
  260. return res.sendStatus(404)
  261. } else if (error.code === 'EPIPE') {
  262. // inspect container returns EPIPE when shutting down
  263. return res.sendStatus(503) // send 503 Unavailable response
  264. } else {
  265. logger.error({ err: error, url: req.url }, 'server error')
  266. return res.sendStatus((error != null ? error.statusCode : undefined) || 500)
  267. }
  268. })
  269. const net = require('net')
  270. const os = require('os')
  271. let STATE = 'up'
  272. const loadTcpServer = net.createServer(function (socket) {
  273. socket.on('error', function (err) {
  274. if (err.code === 'ECONNRESET') {
  275. // this always comes up, we don't know why
  276. return
  277. }
  278. logger.err({ err }, 'error with socket on load check')
  279. return socket.destroy()
  280. })
  281. if (STATE === 'up' && Settings.internal.load_balancer_agent.report_load) {
  282. let availableWorkingCpus
  283. const currentLoad = os.loadavg()[0]
  284. // staging clis's have 1 cpu core only
  285. if (os.cpus().length === 1) {
  286. availableWorkingCpus = 1
  287. } else {
  288. availableWorkingCpus = os.cpus().length - 1
  289. }
  290. const freeLoad = availableWorkingCpus - currentLoad
  291. const freeLoadPercentage = Math.round(
  292. (freeLoad / availableWorkingCpus) * 100
  293. )
  294. if (freeLoadPercentage <= 0) {
  295. // When its 0 the server is set to drain implicitly.
  296. // Drain will move new projects to different servers.
  297. // Drain will keep existing projects assigned to the same server.
  298. // Maint will more existing and new projects to different servers.
  299. socket.write(`maint, 0%\n`, 'ASCII')
  300. } else {
  301. // Ready will cancel the maint state.
  302. socket.write(`up, ready, ${freeLoadPercentage}%\n`, 'ASCII')
  303. }
  304. return socket.end()
  305. } else {
  306. socket.write(`${STATE}\n`, 'ASCII')
  307. return socket.end()
  308. }
  309. })
  310. const loadHttpServer = express()
  311. loadHttpServer.post('/state/up', function (req, res, next) {
  312. STATE = 'up'
  313. logger.info('getting message to set server to down')
  314. return res.sendStatus(204)
  315. })
  316. loadHttpServer.post('/state/down', function (req, res, next) {
  317. STATE = 'down'
  318. logger.info('getting message to set server to down')
  319. return res.sendStatus(204)
  320. })
  321. loadHttpServer.post('/state/maint', function (req, res, next) {
  322. STATE = 'maint'
  323. logger.info('getting message to set server to maint')
  324. return res.sendStatus(204)
  325. })
  326. const port =
  327. __guard__(
  328. Settings.internal != null ? Settings.internal.clsi : undefined,
  329. x => x.port
  330. ) || 3013
  331. const host =
  332. __guard__(
  333. Settings.internal != null ? Settings.internal.clsi : undefined,
  334. x1 => x1.host
  335. ) || 'localhost'
  336. const loadTcpPort = Settings.internal.load_balancer_agent.load_port
  337. const loadHttpPort = Settings.internal.load_balancer_agent.local_port
  338. if (!module.parent) {
  339. // Called directly
  340. // handle uncaught exceptions when running in production
  341. if (Settings.catchErrors) {
  342. process.removeAllListeners('uncaughtException')
  343. process.on('uncaughtException', error =>
  344. logger.error({ err: error }, 'uncaughtException')
  345. )
  346. }
  347. app.listen(port, host, error => {
  348. if (error) {
  349. logger.fatal({ error }, `Error starting CLSI on ${host}:${port}`)
  350. } else {
  351. logger.info(`CLSI starting up, listening on ${host}:${port}`)
  352. }
  353. })
  354. loadTcpServer.listen(loadTcpPort, host, function (error) {
  355. if (error != null) {
  356. throw error
  357. }
  358. return logger.info(`Load tcp agent listening on load port ${loadTcpPort}`)
  359. })
  360. loadHttpServer.listen(loadHttpPort, host, function (error) {
  361. if (error != null) {
  362. throw error
  363. }
  364. return logger.info(`Load http agent listening on load port ${loadHttpPort}`)
  365. })
  366. }
  367. module.exports = app
  368. function __guard__(value, transform) {
  369. return typeof value !== 'undefined' && value !== null
  370. ? transform(value)
  371. : undefined
  372. }