app.js 13 KB

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