app.js 12 KB

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