app.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. // Metrics must be initialized before importing anything else
  2. import '@overleaf/metrics/initialize.js'
  3. import CompileController from './app/js/CompileController.js'
  4. import ContentController from './app/js/ContentController.js'
  5. import Settings from '@overleaf/settings'
  6. import logger from '@overleaf/logger'
  7. import LoggerSerializers from './app/js/LoggerSerializers.js'
  8. import Metrics from '@overleaf/metrics'
  9. import smokeTest from './test/smoke/js/SmokeTests.js'
  10. import ContentTypeMapper from './app/js/ContentTypeMapper.js'
  11. import Errors from './app/js/Errors.js'
  12. import OutputController from './app/js/OutputController.js'
  13. import Path from 'node:path'
  14. import ProjectPersistenceManager from './app/js/ProjectPersistenceManager.js'
  15. import OutputCacheManager from './app/js/OutputCacheManager.js'
  16. import ContentCacheManager from './app/js/ContentCacheManager.js'
  17. import express from 'express'
  18. import bodyParser from 'body-parser'
  19. import ForbidSymlinks from './app/js/StaticServerForbidSymlinks.js'
  20. import net from 'node:net'
  21. import os from 'node:os'
  22. import OError from '@overleaf/o-error'
  23. logger.initialize('clsi')
  24. logger.logger.serializers.clsiRequest = LoggerSerializers.clsiRequest
  25. Metrics.open_sockets.monitor(true)
  26. Metrics.memory.monitor(logger)
  27. Metrics.leaked_sockets.monitor(logger)
  28. ProjectPersistenceManager.init()
  29. OutputCacheManager.init()
  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. next()
  42. })
  43. app.param('project_id', function (req, res, next, projectId) {
  44. if (projectId?.match(/^[a-zA-Z0-9_-]+$/)) {
  45. next()
  46. } else {
  47. next(new Error('invalid project id'))
  48. }
  49. })
  50. app.param('user_id', function (req, res, next, userId) {
  51. if (userId?.match(/^[0-9a-f]{24}$/)) {
  52. next()
  53. } else {
  54. next(new Error('invalid user id'))
  55. }
  56. })
  57. app.param('build_id', function (req, res, next, buildId) {
  58. if (buildId?.match(OutputCacheManager.BUILD_REGEX)) {
  59. next()
  60. } else {
  61. next(new OError('invalid build id', { buildId }))
  62. }
  63. })
  64. app.param('contentId', function (req, res, next, contentId) {
  65. if (contentId?.match(OutputCacheManager.CONTENT_REGEX)) {
  66. next()
  67. } else {
  68. next(new OError('invalid content id', { contentId }))
  69. }
  70. })
  71. app.param('hash', function (req, res, next, hash) {
  72. if (hash?.match(ContentCacheManager.HASH_REGEX)) {
  73. next()
  74. } else {
  75. next(new OError('invalid hash', { hash }))
  76. }
  77. })
  78. app.post(
  79. '/project/:project_id/compile',
  80. bodyParser.json({ limit: Settings.compileSizeLimit }),
  81. CompileController.compile
  82. )
  83. app.post('/project/:project_id/compile/stop', CompileController.stopCompile)
  84. app.delete('/project/:project_id', CompileController.clearCache)
  85. app.get('/project/:project_id/sync/code', CompileController.syncFromCode)
  86. app.get('/project/:project_id/sync/pdf', CompileController.syncFromPdf)
  87. app.get('/project/:project_id/wordcount', CompileController.wordcount)
  88. app.get('/project/:project_id/status', CompileController.status)
  89. app.post('/project/:project_id/status', CompileController.status)
  90. // Per-user containers
  91. app.post(
  92. '/project/:project_id/user/:user_id/compile',
  93. bodyParser.json({ limit: Settings.compileSizeLimit }),
  94. CompileController.compile
  95. )
  96. app.post(
  97. '/project/:project_id/user/:user_id/compile/stop',
  98. CompileController.stopCompile
  99. )
  100. app.delete('/project/:project_id/user/:user_id', CompileController.clearCache)
  101. app.get(
  102. '/project/:project_id/user/:user_id/sync/code',
  103. CompileController.syncFromCode
  104. )
  105. app.get(
  106. '/project/:project_id/user/:user_id/sync/pdf',
  107. CompileController.syncFromPdf
  108. )
  109. app.get(
  110. '/project/:project_id/user/:user_id/wordcount',
  111. CompileController.wordcount
  112. )
  113. // create a static server which does not allow access to any symlinks
  114. // avoids possible mismatch of root directory between middleware check
  115. // and serving the files
  116. const staticOutputServer = ForbidSymlinks(
  117. express.static,
  118. Settings.path.outputDir,
  119. {
  120. setHeaders(res, path, stat) {
  121. if (Path.basename(path) === 'output.pdf') {
  122. // Calculate an etag in the same way as nginx
  123. // https://github.com/tj/send/issues/65
  124. const etag = (path, stat) =>
  125. `"${Math.ceil(+stat.mtime / 1000).toString(16)}` +
  126. '-' +
  127. Number(stat.size).toString(16) +
  128. '"'
  129. res.set('Etag', etag(path, stat))
  130. }
  131. res.set('Content-Type', ContentTypeMapper.map(path))
  132. },
  133. }
  134. )
  135. // This needs to be before GET /project/:project_id/build/:build_id/output/*
  136. app.get(
  137. '/project/:project_id/build/:build_id/output/output.zip',
  138. bodyParser.json(),
  139. OutputController.createOutputZip
  140. )
  141. // This needs to be before GET /project/:project_id/user/:user_id/build/:build_id/output/*
  142. app.get(
  143. '/project/:project_id/user/:user_id/build/:build_id/output/output.zip',
  144. bodyParser.json(),
  145. OutputController.createOutputZip
  146. )
  147. app.get(
  148. '/project/:project_id/user/:user_id/build/:build_id/output/*',
  149. function (req, res, next) {
  150. // for specific build get the path from the OutputCacheManager (e.g. .clsi/buildId)
  151. req.url =
  152. `/${req.params.project_id}-${req.params.user_id}/` +
  153. OutputCacheManager.path(req.params.build_id, `/${req.params[0]}`)
  154. staticOutputServer(req, res, next)
  155. }
  156. )
  157. app.get(
  158. '/project/:projectId/content/:contentId/:hash',
  159. ContentController.getPdfRange
  160. )
  161. app.get(
  162. '/project/:projectId/user/:userId/content/:contentId/:hash',
  163. ContentController.getPdfRange
  164. )
  165. app.get(
  166. '/project/:project_id/build/:build_id/output/*',
  167. function (req, res, next) {
  168. // for specific build get the path from the OutputCacheManager (e.g. .clsi/buildId)
  169. req.url =
  170. `/${req.params.project_id}/` +
  171. OutputCacheManager.path(req.params.build_id, `/${req.params[0]}`)
  172. staticOutputServer(req, res, next)
  173. }
  174. )
  175. app.get('/oops', function (req, res, next) {
  176. logger.error({ err: 'hello' }, 'test error')
  177. res.send('error\n')
  178. })
  179. app.get('/oops-internal', function (req, res, next) {
  180. setTimeout(function () {
  181. throw new Error('Test error')
  182. }, 1)
  183. })
  184. app.get('/status', (req, res, next) => res.send('CLSI is alive\n'))
  185. Settings.processTooOld = false
  186. if (Settings.processLifespanLimitMs) {
  187. // Pre-emp instances have a maximum lifespan of 24h after which they will be
  188. // shutdown, with a 30s grace period.
  189. // Spread cycling of VMs by up-to 2.4h _before_ their limit to avoid large
  190. // numbers of VMs that are temporarily unavailable (while they reboot).
  191. Settings.processLifespanLimitMs -=
  192. Settings.processLifespanLimitMs * (Math.random() / 10)
  193. logger.info(
  194. { target: new Date(Date.now() + Settings.processLifespanLimitMs) },
  195. 'Lifespan limited'
  196. )
  197. setTimeout(() => {
  198. logger.info({}, 'shutting down, process is too old')
  199. Settings.processTooOld = true
  200. }, Settings.processLifespanLimitMs)
  201. }
  202. function runSmokeTest() {
  203. if (Settings.processTooOld) return
  204. const INTERVAL = 30 * 1000
  205. if (
  206. smokeTest.lastRunSuccessful() &&
  207. CompileController.timeSinceLastSuccessfulCompile() < INTERVAL / 2
  208. ) {
  209. logger.debug('skipping smoke tests, got recent successful user compile')
  210. return setTimeout(runSmokeTest, INTERVAL / 2)
  211. }
  212. logger.debug('running smoke tests')
  213. smokeTest.triggerRun(err => {
  214. if (err) logger.error({ err }, 'smoke tests failed')
  215. setTimeout(runSmokeTest, INTERVAL)
  216. })
  217. }
  218. if (Settings.smokeTest) {
  219. runSmokeTest()
  220. }
  221. app.get('/health_check', function (req, res) {
  222. if (Settings.processTooOld) {
  223. return res.status(500).json({ processTooOld: true })
  224. }
  225. if (ProjectPersistenceManager.isAnyDiskCriticalLow()) {
  226. return res.status(500).json({ diskCritical: true })
  227. }
  228. smokeTest.sendLastResult(res)
  229. })
  230. app.get('/smoke_test_force', (req, res) => smokeTest.sendNewResult(res))
  231. app.use(function (error, req, res, next) {
  232. if (error instanceof Errors.NotFoundError) {
  233. logger.debug({ err: error, url: req.url }, 'not found error')
  234. res.sendStatus(404)
  235. } else if (error instanceof Errors.InvalidParameter) {
  236. res.status(400).send(error.message)
  237. } else if (error.code === 'EPIPE') {
  238. // inspect container returns EPIPE when shutting down
  239. res.sendStatus(503) // send 503 Unavailable response
  240. } else {
  241. logger.error({ err: error, url: req.url }, 'server error')
  242. res.sendStatus(error.statusCode || 500)
  243. }
  244. })
  245. let STATE = 'up'
  246. const loadTcpServer = net.createServer(function (socket) {
  247. socket.on('error', function (err) {
  248. if (err.code === 'ECONNRESET') {
  249. // this always comes up, we don't know why
  250. return
  251. }
  252. logger.err({ err }, 'error with socket on load check')
  253. socket.destroy()
  254. })
  255. if (STATE === 'up' && Settings.internal.load_balancer_agent.report_load) {
  256. let availableWorkingCpus
  257. const currentLoad = os.loadavg()[0]
  258. // staging clis's have 1 cpu core only
  259. if (os.cpus().length === 1) {
  260. availableWorkingCpus = 1
  261. } else {
  262. availableWorkingCpus = os.cpus().length - 1
  263. }
  264. const freeLoad = availableWorkingCpus - currentLoad
  265. let freeLoadPercentage = Math.round((freeLoad / availableWorkingCpus) * 100)
  266. if (ProjectPersistenceManager.isAnyDiskCriticalLow()) {
  267. freeLoadPercentage = 0
  268. }
  269. if (ProjectPersistenceManager.isAnyDiskLow()) {
  270. freeLoadPercentage = freeLoadPercentage / 2
  271. }
  272. if (
  273. Settings.internal.load_balancer_agent.allow_maintenance &&
  274. freeLoadPercentage <= 0
  275. ) {
  276. // When its 0 the server is set to drain implicitly.
  277. // Drain will move new projects to different servers.
  278. // Drain will keep existing projects assigned to the same server.
  279. // Maint will more existing and new projects to different servers.
  280. socket.write(`maint, 0%\n`, 'ASCII')
  281. } else {
  282. // Ready will cancel the maint state.
  283. socket.write(`up, ready, ${Math.max(freeLoadPercentage, 1)}%\n`, 'ASCII')
  284. if (freeLoadPercentage <= 0) {
  285. // This metric records how often we would have gone into maintenance mode.
  286. Metrics.inc('clsi-prevented-maint')
  287. }
  288. }
  289. socket.end()
  290. } else {
  291. socket.write(`${STATE}\n`, 'ASCII')
  292. socket.end()
  293. }
  294. })
  295. const loadHttpServer = express()
  296. loadHttpServer.post('/state/up', function (req, res, next) {
  297. STATE = 'up'
  298. logger.debug('getting message to set server to down')
  299. res.sendStatus(204)
  300. })
  301. loadHttpServer.post('/state/down', function (req, res, next) {
  302. STATE = 'down'
  303. logger.debug('getting message to set server to down')
  304. res.sendStatus(204)
  305. })
  306. loadHttpServer.post('/state/maint', function (req, res, next) {
  307. STATE = 'maint'
  308. logger.debug('getting message to set server to maint')
  309. res.sendStatus(204)
  310. })
  311. const port = Settings.internal.clsi.port
  312. const host = Settings.internal.clsi.host
  313. const loadTcpPort = Settings.internal.load_balancer_agent.load_port
  314. const loadHttpPort = Settings.internal.load_balancer_agent.local_port
  315. if (import.meta.main) {
  316. // Called directly
  317. // handle uncaught exceptions when running in production
  318. if (Settings.catchErrors) {
  319. process.removeAllListeners('uncaughtException')
  320. process.on('uncaughtException', error =>
  321. logger.error({ err: error }, 'uncaughtException')
  322. )
  323. }
  324. app.listen(port, host, error => {
  325. if (error) {
  326. logger.fatal({ error }, `Error starting CLSI on ${host}:${port}`)
  327. } else {
  328. logger.debug(`CLSI starting up, listening on ${host}:${port}`)
  329. }
  330. })
  331. loadTcpServer.listen(loadTcpPort, host, function (error) {
  332. if (error != null) {
  333. throw error
  334. }
  335. logger.debug(`Load tcp agent listening on load port ${loadTcpPort}`)
  336. })
  337. loadHttpServer.listen(loadHttpPort, host, function (error) {
  338. if (error != null) {
  339. throw error
  340. }
  341. logger.debug(`Load http agent listening on load port ${loadHttpPort}`)
  342. })
  343. }
  344. export default app