app.js 12 KB

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