app.js 9.2 KB

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