app.js 12 KB

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