app.js 10 KB

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