app.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. // Metrics must be initialized before importing anything else
  2. require('@overleaf/metrics/initialize')
  3. const CompileController = require('./app/js/CompileController')
  4. const ContentController = require('./app/js/ContentController')
  5. const Settings = require('@overleaf/settings')
  6. const logger = require('@overleaf/logger')
  7. logger.initialize('clsi')
  8. const Metrics = require('@overleaf/metrics')
  9. const smokeTest = require('./test/smoke/js/SmokeTests')
  10. const ContentTypeMapper = require('./app/js/ContentTypeMapper')
  11. const Errors = require('./app/js/Errors')
  12. const { createOutputZip } = require('./app/js/OutputController')
  13. const Path = require('node:path')
  14. Metrics.open_sockets.monitor(true)
  15. Metrics.memory.monitor(logger)
  16. Metrics.leaked_sockets.monitor(logger)
  17. const ProjectPersistenceManager = require('./app/js/ProjectPersistenceManager')
  18. const OutputCacheManager = require('./app/js/OutputCacheManager')
  19. const ContentCacheManager = require('./app/js/ContentCacheManager')
  20. ProjectPersistenceManager.init()
  21. OutputCacheManager.init()
  22. const express = require('express')
  23. const bodyParser = require('body-parser')
  24. const app = express()
  25. Metrics.injectMetricsRoute(app)
  26. app.use(Metrics.http.monitor(logger))
  27. // Compile requests can take longer than the default two
  28. // minutes (including file download time), so bump up the
  29. // timeout a bit.
  30. const TIMEOUT = 10 * 60 * 1000
  31. app.use(function (req, res, next) {
  32. req.setTimeout(TIMEOUT)
  33. res.setTimeout(TIMEOUT)
  34. res.removeHeader('X-Powered-By')
  35. next()
  36. })
  37. app.param('project_id', function (req, res, next, projectId) {
  38. if (projectId?.match(/^[a-zA-Z0-9_-]+$/)) {
  39. next()
  40. } else {
  41. next(new Error('invalid project id'))
  42. }
  43. })
  44. app.param('user_id', function (req, res, next, userId) {
  45. if (userId?.match(/^[0-9a-f]{24}$/)) {
  46. next()
  47. } else {
  48. next(new Error('invalid user id'))
  49. }
  50. })
  51. app.param('build_id', function (req, res, next, buildId) {
  52. if (buildId?.match(OutputCacheManager.BUILD_REGEX)) {
  53. next()
  54. } else {
  55. next(new Error(`invalid build id ${buildId}`))
  56. }
  57. })
  58. app.param('contentId', function (req, res, next, contentId) {
  59. if (contentId?.match(OutputCacheManager.CONTENT_REGEX)) {
  60. next()
  61. } else {
  62. next(new Error(`invalid content id ${contentId}`))
  63. }
  64. })
  65. app.param('hash', function (req, res, next, hash) {
  66. if (hash?.match(ContentCacheManager.HASH_REGEX)) {
  67. next()
  68. } else {
  69. next(new Error(`invalid hash ${hash}`))
  70. }
  71. })
  72. app.post(
  73. '/project/:project_id/compile',
  74. bodyParser.json({ limit: Settings.compileSizeLimit }),
  75. CompileController.compile
  76. )
  77. app.post('/project/:project_id/compile/stop', CompileController.stopCompile)
  78. app.delete('/project/:project_id', CompileController.clearCache)
  79. app.get('/project/:project_id/sync/code', CompileController.syncFromCode)
  80. app.get('/project/:project_id/sync/pdf', CompileController.syncFromPdf)
  81. app.get('/project/:project_id/wordcount', CompileController.wordcount)
  82. app.get('/project/:project_id/status', CompileController.status)
  83. app.post('/project/:project_id/status', CompileController.status)
  84. // Per-user containers
  85. app.post(
  86. '/project/:project_id/user/:user_id/compile',
  87. bodyParser.json({ limit: Settings.compileSizeLimit }),
  88. CompileController.compile
  89. )
  90. app.post(
  91. '/project/:project_id/user/:user_id/compile/stop',
  92. CompileController.stopCompile
  93. )
  94. app.delete('/project/:project_id/user/:user_id', CompileController.clearCache)
  95. app.get(
  96. '/project/:project_id/user/:user_id/sync/code',
  97. CompileController.syncFromCode
  98. )
  99. app.get(
  100. '/project/:project_id/user/:user_id/sync/pdf',
  101. CompileController.syncFromPdf
  102. )
  103. app.get(
  104. '/project/:project_id/user/:user_id/wordcount',
  105. CompileController.wordcount
  106. )
  107. const ForbidSymlinks = require('./app/js/StaticServerForbidSymlinks')
  108. // create a static server which does not allow access to any symlinks
  109. // avoids possible mismatch of root directory between middleware check
  110. // and serving the files
  111. const staticOutputServer = ForbidSymlinks(
  112. express.static,
  113. Settings.path.outputDir,
  114. {
  115. setHeaders(res, path, stat) {
  116. if (Path.basename(path) === 'output.pdf') {
  117. // Calculate an etag in the same way as nginx
  118. // https://github.com/tj/send/issues/65
  119. const etag = (path, stat) =>
  120. `"${Math.ceil(+stat.mtime / 1000).toString(16)}` +
  121. '-' +
  122. Number(stat.size).toString(16) +
  123. '"'
  124. res.set('Etag', etag(path, stat))
  125. }
  126. res.set('Content-Type', ContentTypeMapper.map(path))
  127. },
  128. }
  129. )
  130. // This needs to be before GET /project/:project_id/build/:build_id/output/*
  131. app.get(
  132. '/project/:project_id/build/:build_id/output/output.zip',
  133. bodyParser.json(),
  134. createOutputZip
  135. )
  136. // This needs to be before GET /project/:project_id/user/:user_id/build/:build_id/output/*
  137. app.get(
  138. '/project/:project_id/user/:user_id/build/:build_id/output/output.zip',
  139. bodyParser.json(),
  140. createOutputZip
  141. )
  142. app.get(
  143. '/project/:project_id/user/:user_id/build/:build_id/output/*',
  144. function (req, res, next) {
  145. // for specific build get the path from the OutputCacheManager (e.g. .clsi/buildId)
  146. req.url =
  147. `/${req.params.project_id}-${req.params.user_id}/` +
  148. OutputCacheManager.path(req.params.build_id, `/${req.params[0]}`)
  149. staticOutputServer(req, res, next)
  150. }
  151. )
  152. app.get(
  153. '/project/:projectId/content/:contentId/:hash',
  154. ContentController.getPdfRange
  155. )
  156. app.get(
  157. '/project/:projectId/user/:userId/content/:contentId/:hash',
  158. ContentController.getPdfRange
  159. )
  160. app.get(
  161. '/project/:project_id/build/:build_id/output/*',
  162. function (req, res, next) {
  163. // for specific build get the path from the OutputCacheManager (e.g. .clsi/buildId)
  164. req.url =
  165. `/${req.params.project_id}/` +
  166. OutputCacheManager.path(req.params.build_id, `/${req.params[0]}`)
  167. staticOutputServer(req, res, next)
  168. }
  169. )
  170. app.get('/oops', function (req, res, next) {
  171. logger.error({ err: 'hello' }, 'test error')
  172. res.send('error\n')
  173. })
  174. app.get('/oops-internal', function (req, res, next) {
  175. setTimeout(function () {
  176. throw new Error('Test error')
  177. }, 1)
  178. })
  179. app.get('/status', (req, res, next) => res.send('CLSI is alive\n'))
  180. Settings.processTooOld = false
  181. if (Settings.processLifespanLimitMs) {
  182. // Pre-emp instances have a maximum lifespan of 24h after which they will be
  183. // shutdown, with a 30s grace period.
  184. // Spread cycling of VMs by up-to 2.4h _before_ their limit to avoid large
  185. // numbers of VMs that are temporarily unavailable (while they reboot).
  186. Settings.processLifespanLimitMs -=
  187. Settings.processLifespanLimitMs * (Math.random() / 10)
  188. logger.info(
  189. { target: new Date(Date.now() + Settings.processLifespanLimitMs) },
  190. 'Lifespan limited'
  191. )
  192. setTimeout(() => {
  193. logger.info({}, 'shutting down, process is too old')
  194. Settings.processTooOld = true
  195. }, Settings.processLifespanLimitMs)
  196. }
  197. function runSmokeTest() {
  198. if (Settings.processTooOld) return
  199. const INTERVAL = 30 * 1000
  200. if (
  201. smokeTest.lastRunSuccessful() &&
  202. CompileController.timeSinceLastSuccessfulCompile() < INTERVAL / 2
  203. ) {
  204. logger.debug('skipping smoke tests, got recent successful user compile')
  205. return setTimeout(runSmokeTest, INTERVAL / 2)
  206. }
  207. logger.debug('running smoke tests')
  208. smokeTest.triggerRun(err => {
  209. if (err) logger.error({ err }, 'smoke tests failed')
  210. setTimeout(runSmokeTest, INTERVAL)
  211. })
  212. }
  213. if (Settings.smokeTest) {
  214. runSmokeTest()
  215. }
  216. app.get('/health_check', function (req, res) {
  217. if (Settings.processTooOld) {
  218. return res.status(500).json({ processTooOld: true })
  219. }
  220. if (ProjectPersistenceManager.isAnyDiskCriticalLow()) {
  221. return res.status(500).json({ diskCritical: true })
  222. }
  223. smokeTest.sendLastResult(res)
  224. })
  225. app.get('/smoke_test_force', (req, res) => smokeTest.sendNewResult(res))
  226. app.use(function (error, req, res, next) {
  227. if (error instanceof Errors.NotFoundError) {
  228. logger.debug({ err: error, url: req.url }, 'not found error')
  229. res.sendStatus(404)
  230. } else if (error instanceof Errors.InvalidParameter) {
  231. res.status(400).send(error.message)
  232. } else if (error.code === 'EPIPE') {
  233. // inspect container returns EPIPE when shutting down
  234. res.sendStatus(503) // send 503 Unavailable response
  235. } else {
  236. logger.error({ err: error, url: req.url }, 'server error')
  237. res.sendStatus(error.statusCode || 500)
  238. }
  239. })
  240. const net = require('node:net')
  241. const os = require('node:os')
  242. let STATE = 'up'
  243. const loadTcpServer = net.createServer(function (socket) {
  244. socket.on('error', function (err) {
  245. if (err.code === 'ECONNRESET') {
  246. // this always comes up, we don't know why
  247. return
  248. }
  249. logger.err({ err }, 'error with socket on load check')
  250. socket.destroy()
  251. })
  252. if (STATE === 'up' && Settings.internal.load_balancer_agent.report_load) {
  253. let availableWorkingCpus
  254. const currentLoad = os.loadavg()[0]
  255. // staging clis's have 1 cpu core only
  256. if (os.cpus().length === 1) {
  257. availableWorkingCpus = 1
  258. } else {
  259. availableWorkingCpus = os.cpus().length - 1
  260. }
  261. const freeLoad = availableWorkingCpus - currentLoad
  262. let freeLoadPercentage = Math.round((freeLoad / availableWorkingCpus) * 100)
  263. if (ProjectPersistenceManager.isAnyDiskCriticalLow()) {
  264. freeLoadPercentage = 0
  265. }
  266. if (ProjectPersistenceManager.isAnyDiskLow()) {
  267. freeLoadPercentage = freeLoadPercentage / 2
  268. }
  269. if (
  270. Settings.internal.load_balancer_agent.allow_maintenance &&
  271. freeLoadPercentage <= 0
  272. ) {
  273. // When its 0 the server is set to drain implicitly.
  274. // Drain will move new projects to different servers.
  275. // Drain will keep existing projects assigned to the same server.
  276. // Maint will more existing and new projects to different servers.
  277. socket.write(`maint, 0%\n`, 'ASCII')
  278. } else {
  279. // Ready will cancel the maint state.
  280. socket.write(`up, ready, ${Math.max(freeLoadPercentage, 1)}%\n`, 'ASCII')
  281. if (freeLoadPercentage <= 0) {
  282. // This metric records how often we would have gone into maintenance mode.
  283. Metrics.inc('clsi-prevented-maint')
  284. }
  285. }
  286. socket.end()
  287. } else {
  288. socket.write(`${STATE}\n`, 'ASCII')
  289. socket.end()
  290. }
  291. })
  292. const loadHttpServer = express()
  293. loadHttpServer.post('/state/up', function (req, res, next) {
  294. STATE = 'up'
  295. logger.debug('getting message to set server to down')
  296. res.sendStatus(204)
  297. })
  298. loadHttpServer.post('/state/down', function (req, res, next) {
  299. STATE = 'down'
  300. logger.debug('getting message to set server to down')
  301. res.sendStatus(204)
  302. })
  303. loadHttpServer.post('/state/maint', function (req, res, next) {
  304. STATE = 'maint'
  305. logger.debug('getting message to set server to maint')
  306. res.sendStatus(204)
  307. })
  308. const port = Settings.internal.clsi.port
  309. const host = Settings.internal.clsi.host
  310. const loadTcpPort = Settings.internal.load_balancer_agent.load_port
  311. const loadHttpPort = Settings.internal.load_balancer_agent.local_port
  312. if (!module.parent) {
  313. // Called directly
  314. // handle uncaught exceptions when running in production
  315. if (Settings.catchErrors) {
  316. process.removeAllListeners('uncaughtException')
  317. process.on('uncaughtException', error =>
  318. logger.error({ err: error }, 'uncaughtException')
  319. )
  320. }
  321. app.listen(port, host, error => {
  322. if (error) {
  323. logger.fatal({ error }, `Error starting CLSI on ${host}:${port}`)
  324. } else {
  325. logger.debug(`CLSI starting up, listening on ${host}:${port}`)
  326. }
  327. })
  328. loadTcpServer.listen(loadTcpPort, host, function (error) {
  329. if (error != null) {
  330. throw error
  331. }
  332. logger.debug(`Load tcp agent listening on load port ${loadTcpPort}`)
  333. })
  334. loadHttpServer.listen(loadHttpPort, host, function (error) {
  335. if (error != null) {
  336. throw error
  337. }
  338. logger.debug(`Load http agent listening on load port ${loadHttpPort}`)
  339. })
  340. }
  341. module.exports = app