app.js 10 KB

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