app.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. // Metrics must be initialized before importing anything else
  2. require('@overleaf/metrics/initialize')
  3. const CompileController = require('./app/js/CompileController')
  4. const ContentController = require('./app/js/ContentController')
  5. const Settings = require('@overleaf/settings')
  6. const logger = require('@overleaf/logger')
  7. logger.initialize('clsi')
  8. const Metrics = require('@overleaf/metrics')
  9. const smokeTest = require('./test/smoke/js/SmokeTests')
  10. const ContentTypeMapper = require('./app/js/ContentTypeMapper')
  11. const Errors = require('./app/js/Errors')
  12. const { createOutputZip } = require('./app/js/OutputController')
  13. const Path = require('node:path')
  14. Metrics.open_sockets.monitor(true)
  15. Metrics.memory.monitor(logger)
  16. Metrics.leaked_sockets.monitor(logger)
  17. const ProjectPersistenceManager = require('./app/js/ProjectPersistenceManager')
  18. const OutputCacheManager = require('./app/js/OutputCacheManager')
  19. const ContentCacheManager = require('./app/js/ContentCacheManager')
  20. ProjectPersistenceManager.init()
  21. OutputCacheManager.init()
  22. const express = require('express')
  23. const bodyParser = require('body-parser')
  24. const app = express()
  25. Metrics.injectMetricsRoute(app)
  26. app.use(Metrics.http.monitor(logger))
  27. // Compile requests can take longer than the default two
  28. // minutes (including file download time), so bump up the
  29. // timeout a bit.
  30. const TIMEOUT = 10 * 60 * 1000
  31. app.use(function (req, res, next) {
  32. req.setTimeout(TIMEOUT)
  33. res.setTimeout(TIMEOUT)
  34. res.removeHeader('X-Powered-By')
  35. next()
  36. })
  37. app.param('project_id', function (req, res, next, projectId) {
  38. if (projectId?.match(/^[a-zA-Z0-9_-]+$/)) {
  39. next()
  40. } else {
  41. next(new Error('invalid project id'))
  42. }
  43. })
  44. app.param('user_id', function (req, res, next, userId) {
  45. if (userId?.match(/^[0-9a-f]{24}$/)) {
  46. next()
  47. } else {
  48. next(new Error('invalid user id'))
  49. }
  50. })
  51. app.param('build_id', function (req, res, next, buildId) {
  52. if (buildId?.match(OutputCacheManager.BUILD_REGEX)) {
  53. next()
  54. } else {
  55. next(new Error(`invalid build id ${buildId}`))
  56. }
  57. })
  58. app.param('contentId', function (req, res, next, contentId) {
  59. if (contentId?.match(OutputCacheManager.CONTENT_REGEX)) {
  60. next()
  61. } else {
  62. next(new Error(`invalid content id ${contentId}`))
  63. }
  64. })
  65. app.param('hash', function (req, res, next, hash) {
  66. if (hash?.match(ContentCacheManager.HASH_REGEX)) {
  67. next()
  68. } else {
  69. next(new Error(`invalid hash ${hash}`))
  70. }
  71. })
  72. app.post(
  73. '/project/:project_id/compile',
  74. bodyParser.json({ limit: Settings.compileSizeLimit }),
  75. CompileController.compile
  76. )
  77. app.post('/project/:project_id/compile/stop', CompileController.stopCompile)
  78. app.delete('/project/:project_id', CompileController.clearCache)
  79. app.get('/project/:project_id/sync/code', CompileController.syncFromCode)
  80. app.get('/project/:project_id/sync/pdf', CompileController.syncFromPdf)
  81. app.get('/project/:project_id/wordcount', CompileController.wordcount)
  82. app.get('/project/:project_id/status', CompileController.status)
  83. app.post('/project/:project_id/status', CompileController.status)
  84. // Per-user containers
  85. app.post(
  86. '/project/:project_id/user/:user_id/compile',
  87. bodyParser.json({ limit: Settings.compileSizeLimit }),
  88. CompileController.compile
  89. )
  90. app.post(
  91. '/project/:project_id/user/:user_id/compile/stop',
  92. CompileController.stopCompile
  93. )
  94. app.delete('/project/:project_id/user/:user_id', CompileController.clearCache)
  95. app.get(
  96. '/project/:project_id/user/:user_id/sync/code',
  97. CompileController.syncFromCode
  98. )
  99. app.get(
  100. '/project/:project_id/user/:user_id/sync/pdf',
  101. CompileController.syncFromPdf
  102. )
  103. app.get(
  104. '/project/:project_id/user/:user_id/wordcount',
  105. CompileController.wordcount
  106. )
  107. const ForbidSymlinks = require('./app/js/StaticServerForbidSymlinks')
  108. // create a static server which does not allow access to any symlinks
  109. // avoids possible mismatch of root directory between middleware check
  110. // and serving the files
  111. const staticCompileServer = ForbidSymlinks(
  112. express.static,
  113. Settings.path.compilesDir,
  114. {
  115. setHeaders(res, path, stat) {
  116. if (Path.basename(path) === 'output.pdf') {
  117. // Calculate an etag in the same way as nginx
  118. // https://github.com/tj/send/issues/65
  119. const etag = (path, stat) =>
  120. `"${Math.ceil(+stat.mtime / 1000).toString(16)}` +
  121. '-' +
  122. Number(stat.size).toString(16) +
  123. '"'
  124. res.set('Etag', etag(path, stat))
  125. }
  126. res.set('Content-Type', ContentTypeMapper.map(path))
  127. },
  128. }
  129. )
  130. const staticOutputServer = ForbidSymlinks(
  131. express.static,
  132. Settings.path.outputDir,
  133. {
  134. setHeaders(res, path, stat) {
  135. if (Path.basename(path) === 'output.pdf') {
  136. // Calculate an etag in the same way as nginx
  137. // https://github.com/tj/send/issues/65
  138. const etag = (path, stat) =>
  139. `"${Math.ceil(+stat.mtime / 1000).toString(16)}` +
  140. '-' +
  141. Number(stat.size).toString(16) +
  142. '"'
  143. res.set('Etag', etag(path, stat))
  144. }
  145. res.set('Content-Type', ContentTypeMapper.map(path))
  146. },
  147. }
  148. )
  149. // This needs to be before GET /project/:project_id/build/:build_id/output/*
  150. app.get(
  151. '/project/:project_id/build/:build_id/output/output.zip',
  152. bodyParser.json(),
  153. createOutputZip
  154. )
  155. // This needs to be before GET /project/:project_id/user/:user_id/build/:build_id/output/*
  156. app.get(
  157. '/project/:project_id/user/:user_id/build/:build_id/output/output.zip',
  158. bodyParser.json(),
  159. createOutputZip
  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. 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. 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. 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 (req.query?.build?.match(OutputCacheManager.BUILD_REGEX)) {
  204. // for specific build get the path from the OutputCacheManager (e.g. .clsi/buildId)
  205. req.url =
  206. `/${req.params.project_id}/` +
  207. OutputCacheManager.path(req.query.build, `/${req.params[0]}`)
  208. } else {
  209. req.url = `/${req.params.project_id}/${req.params[0]}`
  210. }
  211. staticCompileServer(req, res, next)
  212. })
  213. app.get('/oops', function (req, res, next) {
  214. logger.error({ err: 'hello' }, 'test error')
  215. res.send('error\n')
  216. })
  217. app.get('/oops-internal', function (req, res, next) {
  218. setTimeout(function () {
  219. throw new Error('Test error')
  220. }, 1)
  221. })
  222. app.get('/status', (req, res, next) => res.send('CLSI is alive\n'))
  223. Settings.processTooOld = false
  224. if (Settings.processLifespanLimitMs) {
  225. // Pre-emp instances have a maximum lifespan of 24h after which they will be
  226. // shutdown, with a 30s grace period.
  227. // Spread cycling of VMs by up-to 2.4h _before_ their limit to avoid large
  228. // numbers of VMs that are temporarily unavailable (while they reboot).
  229. Settings.processLifespanLimitMs -=
  230. Settings.processLifespanLimitMs * (Math.random() / 10)
  231. logger.info(
  232. { target: new Date(Date.now() + Settings.processLifespanLimitMs) },
  233. 'Lifespan limited'
  234. )
  235. setTimeout(() => {
  236. logger.info({}, '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. CompileController.timeSinceLastSuccessfulCompile() < 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. res.sendStatus(404)
  270. } else if (error.code === 'EPIPE') {
  271. // inspect container returns EPIPE when shutting down
  272. res.sendStatus(503) // send 503 Unavailable response
  273. } else {
  274. logger.error({ err: error, url: req.url }, 'server error')
  275. res.sendStatus(error.statusCode || 500)
  276. }
  277. })
  278. const net = require('node:net')
  279. const os = require('node: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. 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. socket.end()
  314. } else {
  315. socket.write(`${STATE}\n`, 'ASCII')
  316. 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. 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. 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. res.sendStatus(204)
  334. })
  335. const port = Settings.internal.clsi.port
  336. const host = Settings.internal.clsi.host
  337. const loadTcpPort = Settings.internal.load_balancer_agent.load_port
  338. const loadHttpPort = Settings.internal.load_balancer_agent.local_port
  339. if (!module.parent) {
  340. // Called directly
  341. // handle uncaught exceptions when running in production
  342. if (Settings.catchErrors) {
  343. process.removeAllListeners('uncaughtException')
  344. process.on('uncaughtException', error =>
  345. logger.error({ err: error }, 'uncaughtException')
  346. )
  347. }
  348. app.listen(port, host, error => {
  349. if (error) {
  350. logger.fatal({ error }, `Error starting CLSI on ${host}:${port}`)
  351. } else {
  352. logger.debug(`CLSI starting up, listening on ${host}:${port}`)
  353. }
  354. })
  355. loadTcpServer.listen(loadTcpPort, host, function (error) {
  356. if (error != null) {
  357. throw error
  358. }
  359. logger.debug(`Load tcp agent listening on load port ${loadTcpPort}`)
  360. })
  361. loadHttpServer.listen(loadHttpPort, host, function (error) {
  362. if (error != null) {
  363. throw error
  364. }
  365. logger.debug(`Load http agent listening on load port ${loadHttpPort}`)
  366. })
  367. }
  368. module.exports = app