app.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  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('/status', (req, res, next) => res.send('CLSI is alive\n'))
  176. Settings.processTooOld = false
  177. if (Settings.processLifespanLimitMs) {
  178. // Pre-emp instances have a maximum lifespan of 24h after which they will be
  179. // shutdown, with a 30s grace period.
  180. // Spread cycling of VMs by up-to 2.4h _before_ their limit to avoid large
  181. // numbers of VMs that are temporarily unavailable (while they reboot).
  182. Settings.processLifespanLimitMs -=
  183. Settings.processLifespanLimitMs * (Math.random() / 10)
  184. logger.info(
  185. { target: new Date(Date.now() + Settings.processLifespanLimitMs) },
  186. 'Lifespan limited'
  187. )
  188. setTimeout(() => {
  189. logger.info({}, 'shutting down, process is too old')
  190. Settings.processTooOld = true
  191. }, Settings.processLifespanLimitMs)
  192. }
  193. function runSmokeTest() {
  194. if (Settings.processTooOld) return
  195. const INTERVAL = 30 * 1000
  196. if (
  197. smokeTest.lastRunSuccessful() &&
  198. CompileController.timeSinceLastSuccessfulCompile() < INTERVAL / 2
  199. ) {
  200. logger.debug('skipping smoke tests, got recent successful user compile')
  201. return setTimeout(runSmokeTest, INTERVAL / 2)
  202. }
  203. logger.debug('running smoke tests')
  204. smokeTest.triggerRun(err => {
  205. if (err) logger.error({ err }, 'smoke tests failed')
  206. setTimeout(runSmokeTest, INTERVAL)
  207. })
  208. }
  209. if (Settings.smokeTest) {
  210. runSmokeTest()
  211. }
  212. app.get('/health_check', function (req, res) {
  213. if (Settings.processTooOld) {
  214. return res.status(500).json({ processTooOld: true })
  215. }
  216. if (ProjectPersistenceManager.isAnyDiskCriticalLow()) {
  217. return res.status(500).json({ diskCritical: true })
  218. }
  219. smokeTest.sendLastResult(res)
  220. })
  221. app.get('/smoke_test_force', (req, res) => smokeTest.sendNewResult(res))
  222. app.use(function (error, req, res, next) {
  223. if (error instanceof Errors.NotFoundError) {
  224. logger.debug({ err: error, url: req.url }, 'not found error')
  225. res.sendStatus(404)
  226. } else if (error instanceof Errors.InvalidParameter) {
  227. res.status(400).send(error.message)
  228. } else if (error.code === 'EPIPE') {
  229. // inspect container returns EPIPE when shutting down
  230. res.sendStatus(503) // send 503 Unavailable response
  231. } else {
  232. logger.error({ err: error, url: req.url }, 'server error')
  233. res.sendStatus(error.statusCode || 500)
  234. }
  235. })
  236. let STATE = 'up'
  237. const loadTcpServer = net.createServer(function (socket) {
  238. socket.on('error', function (err) {
  239. if (err.code === 'ECONNRESET') {
  240. // this always comes up, we don't know why
  241. return
  242. }
  243. logger.err({ err }, 'error with socket on load check')
  244. socket.destroy()
  245. })
  246. if (STATE === 'up' && Settings.internal.load_balancer_agent.report_load) {
  247. let availableWorkingCpus
  248. const currentLoad = os.loadavg()[0]
  249. // staging clis's have 1 cpu core only
  250. if (os.cpus().length === 1) {
  251. availableWorkingCpus = 1
  252. } else {
  253. availableWorkingCpus = os.cpus().length - 1
  254. }
  255. const freeLoad = availableWorkingCpus - currentLoad
  256. let freeLoadPercentage = Math.round((freeLoad / availableWorkingCpus) * 100)
  257. if (ProjectPersistenceManager.isAnyDiskCriticalLow()) {
  258. freeLoadPercentage = 0
  259. }
  260. if (ProjectPersistenceManager.isAnyDiskLow()) {
  261. freeLoadPercentage = freeLoadPercentage / 2
  262. }
  263. if (
  264. Settings.internal.load_balancer_agent.allow_maintenance &&
  265. freeLoadPercentage <= 0
  266. ) {
  267. // When its 0 the server is set to drain implicitly.
  268. // Drain will move new projects to different servers.
  269. // Drain will keep existing projects assigned to the same server.
  270. // Maint will more existing and new projects to different servers.
  271. socket.write(`maint, 0%\n`, 'ASCII')
  272. } else {
  273. // Ready will cancel the maint state.
  274. socket.write(`up, ready, ${Math.max(freeLoadPercentage, 1)}%\n`, 'ASCII')
  275. if (freeLoadPercentage <= 0) {
  276. // This metric records how often we would have gone into maintenance mode.
  277. Metrics.inc('clsi-prevented-maint')
  278. }
  279. }
  280. socket.end()
  281. } else {
  282. socket.write(`${STATE}\n`, 'ASCII')
  283. socket.end()
  284. }
  285. })
  286. const loadHttpServer = express()
  287. loadHttpServer.post('/state/up', function (req, res, next) {
  288. STATE = 'up'
  289. logger.debug('getting message to set server to down')
  290. res.sendStatus(204)
  291. })
  292. loadHttpServer.post('/state/down', function (req, res, next) {
  293. STATE = 'down'
  294. logger.debug('getting message to set server to down')
  295. res.sendStatus(204)
  296. })
  297. loadHttpServer.post('/state/maint', function (req, res, next) {
  298. STATE = 'maint'
  299. logger.debug('getting message to set server to maint')
  300. res.sendStatus(204)
  301. })
  302. const port = Settings.internal.clsi.port
  303. const host = Settings.internal.clsi.host
  304. const loadTcpPort = Settings.internal.load_balancer_agent.load_port
  305. const loadHttpPort = Settings.internal.load_balancer_agent.local_port
  306. if (import.meta.main) {
  307. // Called directly
  308. // handle uncaught exceptions when running in production
  309. if (Settings.catchErrors) {
  310. process.removeAllListeners('uncaughtException')
  311. process.on('uncaughtException', error =>
  312. logger.error({ err: error }, 'uncaughtException')
  313. )
  314. }
  315. app.listen(port, host, error => {
  316. if (error) {
  317. logger.fatal({ error }, `Error starting CLSI on ${host}:${port}`)
  318. } else {
  319. logger.debug(`CLSI starting up, listening on ${host}:${port}`)
  320. }
  321. })
  322. loadTcpServer.listen(loadTcpPort, host, function (error) {
  323. if (error != null) {
  324. throw error
  325. }
  326. logger.debug(`Load tcp agent listening on load port ${loadTcpPort}`)
  327. })
  328. loadHttpServer.listen(loadHttpPort, host, function (error) {
  329. if (error != null) {
  330. throw error
  331. }
  332. logger.debug(`Load http agent listening on load port ${loadHttpPort}`)
  333. })
  334. }
  335. export default app