app.js 9.6 KB

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