app.js 12 KB

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