app.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  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. 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('/project/:project_id/build/:build_id/output/*', function (
  181. req,
  182. res,
  183. next
  184. ) {
  185. // for specific build get the path from the OutputCacheManager (e.g. .clsi/buildId)
  186. req.url =
  187. `/${req.params.project_id}/` +
  188. OutputCacheManager.path(req.params.build_id, `/${req.params[0]}`)
  189. return staticOutputServer(req, res, next)
  190. })
  191. app.get('/project/:project_id/user/:user_id/output/*', function (
  192. req,
  193. res,
  194. next
  195. ) {
  196. // for specific user get the path to the top level file
  197. logger.warn({ url: req.url }, 'direct request for file in compile directory')
  198. req.url = `/${req.params.project_id}-${req.params.user_id}/${req.params[0]}`
  199. return staticCompileServer(req, res, next)
  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. let freeLoadPercentage = Math.round((freeLoad / availableWorkingCpus) * 100)
  292. if (freeLoadPercentage <= 0) {
  293. freeLoadPercentage = 1 // when its 0 the server is set to drain and will move projects to different servers
  294. }
  295. socket.write(`up, ${freeLoadPercentage}%\n`, 'ASCII')
  296. return socket.end()
  297. } else {
  298. socket.write(`${STATE}\n`, 'ASCII')
  299. return socket.end()
  300. }
  301. })
  302. const loadHttpServer = express()
  303. loadHttpServer.post('/state/up', function (req, res, next) {
  304. STATE = 'up'
  305. logger.info('getting message to set server to down')
  306. return res.sendStatus(204)
  307. })
  308. loadHttpServer.post('/state/down', function (req, res, next) {
  309. STATE = 'down'
  310. logger.info('getting message to set server to down')
  311. return res.sendStatus(204)
  312. })
  313. loadHttpServer.post('/state/maint', function (req, res, next) {
  314. STATE = 'maint'
  315. logger.info('getting message to set server to maint')
  316. return res.sendStatus(204)
  317. })
  318. const port =
  319. __guard__(
  320. Settings.internal != null ? Settings.internal.clsi : undefined,
  321. (x) => x.port
  322. ) || 3013
  323. const host =
  324. __guard__(
  325. Settings.internal != null ? Settings.internal.clsi : undefined,
  326. (x1) => x1.host
  327. ) || 'localhost'
  328. const loadTcpPort = Settings.internal.load_balancer_agent.load_port
  329. const loadHttpPort = Settings.internal.load_balancer_agent.local_port
  330. if (!module.parent) {
  331. // Called directly
  332. // handle uncaught exceptions when running in production
  333. if (Settings.catchErrors) {
  334. process.removeAllListeners('uncaughtException')
  335. process.on('uncaughtException', (error) =>
  336. logger.error({ err: error }, 'uncaughtException')
  337. )
  338. }
  339. app.listen(port, host, (error) => {
  340. if (error) {
  341. logger.fatal({ error }, `Error starting CLSI on ${host}:${port}`)
  342. } else {
  343. logger.info(`CLSI starting up, listening on ${host}:${port}`)
  344. }
  345. })
  346. loadTcpServer.listen(loadTcpPort, host, function (error) {
  347. if (error != null) {
  348. throw error
  349. }
  350. return logger.info(`Load tcp agent listening on load port ${loadTcpPort}`)
  351. })
  352. loadHttpServer.listen(loadHttpPort, host, function (error) {
  353. if (error != null) {
  354. throw error
  355. }
  356. return logger.info(`Load http agent listening on load port ${loadHttpPort}`)
  357. })
  358. }
  359. module.exports = app
  360. setInterval(() => {
  361. ProjectPersistenceManager.refreshExpiryTimeout()
  362. ProjectPersistenceManager.clearExpiredProjects()
  363. }, tenMinutes)
  364. function __guard__(value, transform) {
  365. return typeof value !== 'undefined' && value !== null
  366. ? transform(value)
  367. : undefined
  368. }