app.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  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 Settings from '@overleaf/settings'
  5. import logger from '@overleaf/logger'
  6. import LoggerSerializers from './app/js/LoggerSerializers.js'
  7. import Metrics from '@overleaf/metrics'
  8. import smokeTest from './test/smoke/js/SmokeTests.js'
  9. import Errors from './app/js/Errors.js'
  10. import OutputController from './app/js/OutputController.js'
  11. import ProjectPersistenceManager from './app/js/ProjectPersistenceManager.js'
  12. import OutputCacheManager from './app/js/OutputCacheManager.js'
  13. import express from 'express'
  14. import bodyParser from 'body-parser'
  15. import net from 'node:net'
  16. import os from 'node:os'
  17. import OError from '@overleaf/o-error'
  18. import ConversionController from './app/js/ConversionController.js'
  19. import FileUploadMiddleware from './app/js/FileUploadMiddleware.js'
  20. logger.initialize('clsi')
  21. logger.logger.serializers.clsiRequest = LoggerSerializers.clsiRequest
  22. Metrics.open_sockets.monitor(true)
  23. Metrics.memory.monitor(logger)
  24. Metrics.leaked_sockets.monitor(logger)
  25. ProjectPersistenceManager.init()
  26. OutputCacheManager.init()
  27. const app = express()
  28. Metrics.injectMetricsRoute(app)
  29. app.use(Metrics.http.monitor(logger))
  30. // Compile requests can take longer than the default two
  31. // minutes (including file download time), so bump up the
  32. // timeout a bit.
  33. const TIMEOUT = 630 * 1000 // 10.5 minutes - 30 seconds download allowance
  34. app.use(function (req, res, next) {
  35. req.setTimeout(TIMEOUT)
  36. res.setTimeout(TIMEOUT)
  37. res.removeHeader('X-Powered-By')
  38. next()
  39. })
  40. app.param('project_id', function (req, res, next, projectId) {
  41. if (projectId?.match(/^[a-zA-Z0-9_-]+$/)) {
  42. next()
  43. } else {
  44. next(new Error('invalid project id'))
  45. }
  46. })
  47. app.param('user_id', function (req, res, next, userId) {
  48. if (userId?.match(/^[0-9a-f]{24}$/)) {
  49. next()
  50. } else {
  51. next(new Error('invalid user id'))
  52. }
  53. })
  54. app.param('build_id', function (req, res, next, buildId) {
  55. if (buildId?.match(OutputCacheManager.BUILD_REGEX)) {
  56. next()
  57. } else {
  58. next(new OError('invalid build id', { buildId }))
  59. }
  60. })
  61. app.post(
  62. '/project/:project_id/compile',
  63. bodyParser.json({ limit: Settings.compileSizeLimit }),
  64. CompileController.compile
  65. )
  66. app.post('/project/:project_id/compile/stop', CompileController.stopCompile)
  67. app.delete('/project/:project_id', CompileController.clearCache)
  68. app.get('/project/:project_id/sync/code', CompileController.syncFromCode)
  69. app.get('/project/:project_id/sync/pdf', CompileController.syncFromPdf)
  70. app.get('/project/:project_id/wordcount', CompileController.wordcount)
  71. app.get('/project/:project_id/status', CompileController.status)
  72. app.post('/project/:project_id/status', CompileController.status)
  73. // Per-user containers
  74. app.post(
  75. '/project/:project_id/user/:user_id/compile',
  76. bodyParser.json({ limit: Settings.compileSizeLimit }),
  77. CompileController.compile
  78. )
  79. app.post(
  80. '/project/:project_id/user/:user_id/compile/stop',
  81. CompileController.stopCompile
  82. )
  83. app.delete('/project/:project_id/user/:user_id', CompileController.clearCache)
  84. app.get(
  85. '/project/:project_id/user/:user_id/sync/code',
  86. CompileController.syncFromCode
  87. )
  88. app.get(
  89. '/project/:project_id/user/:user_id/sync/pdf',
  90. CompileController.syncFromPdf
  91. )
  92. app.get(
  93. '/project/:project_id/user/:user_id/wordcount',
  94. CompileController.wordcount
  95. )
  96. // This needs to be before GET /project/:project_id/build/:build_id/output/*
  97. app.get(
  98. '/project/:project_id/build/:build_id/output/output.zip',
  99. bodyParser.json(),
  100. OutputController.createOutputZip
  101. )
  102. // This needs to be before GET /project/:project_id/user/:user_id/build/:build_id/output/*
  103. app.get(
  104. '/project/:project_id/user/:user_id/build/:build_id/output/output.zip',
  105. bodyParser.json(),
  106. OutputController.createOutputZip
  107. )
  108. // Conversion endpoints
  109. // Keep old route for backwards compatibility during CLSI/web deploy transition
  110. app.post(
  111. '/convert/docx-to-latex',
  112. FileUploadMiddleware.multerMiddleware,
  113. (req, res, next) => {
  114. req.query.type = 'docx'
  115. next()
  116. },
  117. ConversionController.convertDocumentToLaTeX
  118. )
  119. app.post(
  120. '/convert/document-to-latex',
  121. FileUploadMiddleware.multerMiddleware,
  122. ConversionController.convertDocumentToLaTeX
  123. )
  124. app.post(
  125. '/project/:project_id/user/:user_id/download/project-to-document',
  126. bodyParser.json({ limit: Settings.compileSizeLimit }),
  127. ConversionController.convertProjectToDocument
  128. )
  129. if (process.env.NODE_ENV === 'development' && global.__coverage__) {
  130. app.get('/coverage', (req, res) => {
  131. const coverage = {}
  132. for (const [key, value] of Object.entries(global.__coverage__)) {
  133. coverage[key] = {
  134. ...value,
  135. path: value.path.replace('/overleaf/', '/workspace/'),
  136. }
  137. }
  138. res.json({ coverage })
  139. })
  140. }
  141. app.get('/status', (req, res, next) => res.send('CLSI is alive\n'))
  142. Settings.processTooOld = false
  143. if (Settings.processLifespanLimitMs) {
  144. // Pre-emp instances have a maximum lifespan of 24h after which they will be
  145. // shutdown, with a 30s grace period.
  146. // Spread cycling of VMs by up-to 2.4h _before_ their limit to avoid large
  147. // numbers of VMs that are temporarily unavailable (while they reboot).
  148. Settings.processLifespanLimitMs -=
  149. Settings.processLifespanLimitMs * (Math.random() / 10)
  150. logger.info(
  151. { target: new Date(Date.now() + Settings.processLifespanLimitMs) },
  152. 'Lifespan limited'
  153. )
  154. setTimeout(() => {
  155. logger.info({}, 'shutting down, process is too old')
  156. Settings.processTooOld = true
  157. }, Settings.processLifespanLimitMs)
  158. }
  159. function runSmokeTest() {
  160. if (Settings.processTooOld) return
  161. const INTERVAL = 30 * 1000
  162. if (
  163. smokeTest.lastRunSuccessful() &&
  164. CompileController.timeSinceLastSuccessfulCompile() < INTERVAL / 2
  165. ) {
  166. logger.debug('skipping smoke tests, got recent successful user compile')
  167. return setTimeout(runSmokeTest, INTERVAL / 2)
  168. }
  169. logger.debug('running smoke tests')
  170. smokeTest.triggerRun(err => {
  171. if (err) logger.error({ err }, 'smoke tests failed')
  172. setTimeout(runSmokeTest, INTERVAL)
  173. })
  174. }
  175. if (Settings.smokeTest) {
  176. runSmokeTest()
  177. }
  178. app.get('/health_check', function (req, res) {
  179. if (Settings.processTooOld) {
  180. return res.status(500).json({ processTooOld: true })
  181. }
  182. if (ProjectPersistenceManager.isAnyDiskCriticalLow()) {
  183. return res.status(500).json({ diskCritical: true })
  184. }
  185. smokeTest.sendLastResult(res)
  186. })
  187. app.get('/smoke_test_force', (req, res) => smokeTest.sendNewResult(res))
  188. app.use(function (error, req, res, next) {
  189. if (error instanceof Errors.NotFoundError) {
  190. logger.debug({ err: error, url: req.url }, 'not found error')
  191. res.sendStatus(404)
  192. } else if (error instanceof Errors.InvalidParameter) {
  193. res.status(400).send(error.message)
  194. } else if (error.code === 'EPIPE') {
  195. // inspect container returns EPIPE when shutting down
  196. res.sendStatus(503) // send 503 Unavailable response
  197. } else {
  198. logger.error({ err: error, url: req.url }, 'server error')
  199. res.sendStatus(error.statusCode || 500)
  200. }
  201. })
  202. let STATE = 'up'
  203. const loadTcpServer = net.createServer(function (socket) {
  204. socket.on('error', function (err) {
  205. if (err.code === 'ECONNRESET') {
  206. // this always comes up, we don't know why
  207. return
  208. }
  209. logger.err({ err }, 'error with socket on load check')
  210. socket.destroy()
  211. })
  212. if (STATE === 'up' && Settings.internal.load_balancer_agent.report_load) {
  213. let availableWorkingCpus
  214. const currentLoad = os.loadavg()[0]
  215. // staging clis's have 1 cpu core only
  216. if (os.cpus().length === 1) {
  217. availableWorkingCpus = 1
  218. } else {
  219. availableWorkingCpus = os.cpus().length - 1
  220. }
  221. const freeLoad = availableWorkingCpus - currentLoad
  222. let freeLoadPercentage = Math.round((freeLoad / availableWorkingCpus) * 100)
  223. if (ProjectPersistenceManager.isAnyDiskCriticalLow()) {
  224. freeLoadPercentage = 0
  225. }
  226. if (ProjectPersistenceManager.isAnyDiskLow()) {
  227. freeLoadPercentage = freeLoadPercentage / 2
  228. }
  229. if (
  230. Settings.internal.load_balancer_agent.allow_maintenance &&
  231. freeLoadPercentage <= 0
  232. ) {
  233. // When its 0 the server is set to drain implicitly.
  234. // Drain will move new projects to different servers.
  235. // Drain will keep existing projects assigned to the same server.
  236. // Maint will more existing and new projects to different servers.
  237. socket.write(`maint, 0%\n`, 'ASCII')
  238. } else {
  239. // Ready will cancel the maint state.
  240. socket.write(`up, ready, ${Math.max(freeLoadPercentage, 1)}%\n`, 'ASCII')
  241. if (freeLoadPercentage <= 0) {
  242. // This metric records how often we would have gone into maintenance mode.
  243. Metrics.inc('clsi-prevented-maint')
  244. }
  245. }
  246. socket.end()
  247. } else {
  248. socket.write(`${STATE}\n`, 'ASCII')
  249. socket.end()
  250. }
  251. })
  252. const loadHttpServer = express()
  253. loadHttpServer.post('/state/up', function (req, res, next) {
  254. STATE = 'up'
  255. logger.debug('getting message to set server to down')
  256. res.sendStatus(204)
  257. })
  258. loadHttpServer.post('/state/down', function (req, res, next) {
  259. STATE = 'down'
  260. logger.debug('getting message to set server to down')
  261. res.sendStatus(204)
  262. })
  263. loadHttpServer.post('/state/maint', function (req, res, next) {
  264. STATE = 'maint'
  265. logger.debug('getting message to set server to maint')
  266. res.sendStatus(204)
  267. })
  268. const port = Settings.internal.clsi.port
  269. const host = Settings.internal.clsi.host
  270. const loadTcpPort = Settings.internal.load_balancer_agent.load_port
  271. const loadHttpPort = Settings.internal.load_balancer_agent.local_port
  272. if (import.meta.main) {
  273. // Called directly
  274. // handle uncaught exceptions when running in production
  275. if (Settings.catchErrors) {
  276. process.removeAllListeners('uncaughtException')
  277. process.on('uncaughtException', error =>
  278. logger.error({ err: error }, 'uncaughtException')
  279. )
  280. }
  281. app.listen(port, host, error => {
  282. if (error) {
  283. logger.fatal({ error }, `Error starting CLSI on ${host}:${port}`)
  284. } else {
  285. logger.debug(`CLSI starting up, listening on ${host}:${port}`)
  286. }
  287. })
  288. loadTcpServer.listen(loadTcpPort, host, function (error) {
  289. if (error != null) {
  290. throw error
  291. }
  292. logger.debug(`Load tcp agent listening on load port ${loadTcpPort}`)
  293. })
  294. loadHttpServer.listen(loadHttpPort, host, function (error) {
  295. if (error != null) {
  296. throw error
  297. }
  298. logger.debug(`Load http agent listening on load port ${loadHttpPort}`)
  299. })
  300. }
  301. export default app