app.js 12 KB

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