app.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  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('@overleaf/settings')
  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. const ContentCacheManager = require('./app/js/ContentCacheManager')
  28. require('./app/js/db').sync()
  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.info(
  232. 'Lifespan limited to ',
  233. Date.now() + Settings.processLifespanLimitMs
  234. )
  235. setTimeout(() => {
  236. logger.log('shutting down, process is too old')
  237. Settings.processTooOld = true
  238. }, Settings.processLifespanLimitMs)
  239. }
  240. function runSmokeTest() {
  241. if (Settings.processTooOld) return
  242. logger.log('running smoke tests')
  243. smokeTest.triggerRun(err => {
  244. if (err) logger.error({ err }, 'smoke tests failed')
  245. setTimeout(runSmokeTest, 30 * 1000)
  246. })
  247. }
  248. if (Settings.smokeTest) {
  249. runSmokeTest()
  250. }
  251. app.get('/health_check', function (req, res) {
  252. if (Settings.processTooOld) {
  253. return res.status(500).json({ processTooOld: true })
  254. }
  255. smokeTest.sendLastResult(res)
  256. })
  257. app.get('/smoke_test_force', (req, res) => smokeTest.sendNewResult(res))
  258. app.use(function (error, req, res, next) {
  259. if (error instanceof Errors.NotFoundError) {
  260. logger.log({ err: error, url: req.url }, 'not found error')
  261. return res.sendStatus(404)
  262. } else if (error.code === 'EPIPE') {
  263. // inspect container returns EPIPE when shutting down
  264. return res.sendStatus(503) // send 503 Unavailable response
  265. } else {
  266. logger.error({ err: error, url: req.url }, 'server error')
  267. return res.sendStatus((error != null ? error.statusCode : undefined) || 500)
  268. }
  269. })
  270. const net = require('net')
  271. const os = require('os')
  272. let STATE = 'up'
  273. const loadTcpServer = net.createServer(function (socket) {
  274. socket.on('error', function (err) {
  275. if (err.code === 'ECONNRESET') {
  276. // this always comes up, we don't know why
  277. return
  278. }
  279. logger.err({ err }, 'error with socket on load check')
  280. return socket.destroy()
  281. })
  282. if (STATE === 'up' && Settings.internal.load_balancer_agent.report_load) {
  283. let availableWorkingCpus
  284. const currentLoad = os.loadavg()[0]
  285. // staging clis's have 1 cpu core only
  286. if (os.cpus().length === 1) {
  287. availableWorkingCpus = 1
  288. } else {
  289. availableWorkingCpus = os.cpus().length - 1
  290. }
  291. const freeLoad = availableWorkingCpus - currentLoad
  292. let freeLoadPercentage = Math.round((freeLoad / availableWorkingCpus) * 100)
  293. if (freeLoadPercentage <= 0) {
  294. freeLoadPercentage = 0 // when its 0 the server is set to drain and will move projects to different servers
  295. }
  296. socket.write(`up, ${freeLoadPercentage}%\n`, 'ASCII')
  297. return socket.end()
  298. } else {
  299. socket.write(`${STATE}\n`, 'ASCII')
  300. return socket.end()
  301. }
  302. })
  303. const loadHttpServer = express()
  304. loadHttpServer.post('/state/up', function (req, res, next) {
  305. STATE = 'up'
  306. logger.info('getting message to set server to down')
  307. return res.sendStatus(204)
  308. })
  309. loadHttpServer.post('/state/down', function (req, res, next) {
  310. STATE = 'down'
  311. logger.info('getting message to set server to down')
  312. return res.sendStatus(204)
  313. })
  314. loadHttpServer.post('/state/maint', function (req, res, next) {
  315. STATE = 'maint'
  316. logger.info('getting message to set server to maint')
  317. return res.sendStatus(204)
  318. })
  319. const port =
  320. __guard__(
  321. Settings.internal != null ? Settings.internal.clsi : undefined,
  322. x => x.port
  323. ) || 3013
  324. const host =
  325. __guard__(
  326. Settings.internal != null ? Settings.internal.clsi : undefined,
  327. x1 => x1.host
  328. ) || 'localhost'
  329. const loadTcpPort = Settings.internal.load_balancer_agent.load_port
  330. const loadHttpPort = Settings.internal.load_balancer_agent.local_port
  331. if (!module.parent) {
  332. // Called directly
  333. // handle uncaught exceptions when running in production
  334. if (Settings.catchErrors) {
  335. process.removeAllListeners('uncaughtException')
  336. process.on('uncaughtException', error =>
  337. logger.error({ err: error }, 'uncaughtException')
  338. )
  339. }
  340. app.listen(port, host, error => {
  341. if (error) {
  342. logger.fatal({ error }, `Error starting CLSI on ${host}:${port}`)
  343. } else {
  344. logger.info(`CLSI starting up, listening on ${host}:${port}`)
  345. }
  346. })
  347. loadTcpServer.listen(loadTcpPort, host, function (error) {
  348. if (error != null) {
  349. throw error
  350. }
  351. return logger.info(`Load tcp agent listening on load port ${loadTcpPort}`)
  352. })
  353. loadHttpServer.listen(loadHttpPort, host, function (error) {
  354. if (error != null) {
  355. throw error
  356. }
  357. return logger.info(`Load http agent listening on load port ${loadHttpPort}`)
  358. })
  359. }
  360. module.exports = app
  361. setInterval(() => {
  362. ProjectPersistenceManager.refreshExpiryTimeout(() => {
  363. ProjectPersistenceManager.clearExpiredProjects()
  364. })
  365. }, tenMinutes)
  366. function __guard__(value, transform) {
  367. return typeof value !== 'undefined' && value !== null
  368. ? transform(value)
  369. : undefined
  370. }