app.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. /*
  2. * decaffeinate suggestions:
  3. * DS102: Remove unnecessary code created because of implicit returns
  4. * DS103: Rewrite code to no longer use __guard__
  5. * DS207: Consider shorter variations of null checks
  6. * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
  7. */
  8. let tenMinutes
  9. const Metrics = require('metrics-sharelatex')
  10. Metrics.initialize('clsi')
  11. const CompileController = require('./app/js/CompileController')
  12. const Settings = require('settings-sharelatex')
  13. const logger = require('logger-sharelatex')
  14. logger.initialize('clsi')
  15. if ((Settings.sentry != null ? Settings.sentry.dsn : undefined) != null) {
  16. logger.initializeErrorReporting(Settings.sentry.dsn)
  17. }
  18. const smokeTest = require('smoke-test-sharelatex')
  19. const ContentTypeMapper = require('./app/js/ContentTypeMapper')
  20. const Errors = require('./app/js/Errors')
  21. const Path = require('path')
  22. Metrics.open_sockets.monitor(logger)
  23. Metrics.memory.monitor(logger)
  24. const ProjectPersistenceManager = require('./app/js/ProjectPersistenceManager')
  25. const OutputCacheManager = require('./app/js/OutputCacheManager')
  26. require('./app/js/db').sync()
  27. const express = require('express')
  28. const bodyParser = require('body-parser')
  29. const app = express()
  30. Metrics.injectMetricsRoute(app)
  31. app.use(Metrics.http.monitor(logger))
  32. // Compile requests can take longer than the default two
  33. // minutes (including file download time), so bump up the
  34. // timeout a bit.
  35. const TIMEOUT = 10 * 60 * 1000
  36. app.use(function(req, res, next) {
  37. req.setTimeout(TIMEOUT)
  38. res.setTimeout(TIMEOUT)
  39. res.removeHeader('X-Powered-By')
  40. return next()
  41. })
  42. app.param('project_id', function(req, res, next, project_id) {
  43. if (project_id != null ? project_id.match(/^[a-zA-Z0-9_-]+$/) : undefined) {
  44. return next()
  45. } else {
  46. return next(new Error('invalid project id'))
  47. }
  48. })
  49. app.param('user_id', function(req, res, next, user_id) {
  50. if (user_id != null ? user_id.match(/^[0-9a-f]{24}$/) : undefined) {
  51. return next()
  52. } else {
  53. return next(new Error('invalid user id'))
  54. }
  55. })
  56. app.param('build_id', function(req, res, next, build_id) {
  57. if (
  58. build_id != null
  59. ? build_id.match(OutputCacheManager.BUILD_REGEX)
  60. : undefined
  61. ) {
  62. return next()
  63. } else {
  64. return next(new Error(`invalid build id ${build_id}`))
  65. }
  66. })
  67. app.post(
  68. '/project/:project_id/compile',
  69. bodyParser.json({ limit: Settings.compileSizeLimit }),
  70. CompileController.compile
  71. )
  72. app.post('/project/:project_id/compile/stop', CompileController.stopCompile)
  73. app.delete('/project/:project_id', CompileController.clearCache)
  74. app.get('/project/:project_id/sync/code', CompileController.syncFromCode)
  75. app.get('/project/:project_id/sync/pdf', CompileController.syncFromPdf)
  76. app.get('/project/:project_id/wordcount', CompileController.wordcount)
  77. app.get('/project/:project_id/status', CompileController.status)
  78. // Per-user containers
  79. app.post(
  80. '/project/:project_id/user/:user_id/compile',
  81. bodyParser.json({ limit: Settings.compileSizeLimit }),
  82. CompileController.compile
  83. )
  84. app.post(
  85. '/project/:project_id/user/:user_id/compile/stop',
  86. CompileController.stopCompile
  87. )
  88. app.delete('/project/:project_id/user/:user_id', CompileController.clearCache)
  89. app.get(
  90. '/project/:project_id/user/:user_id/sync/code',
  91. CompileController.syncFromCode
  92. )
  93. app.get(
  94. '/project/:project_id/user/:user_id/sync/pdf',
  95. CompileController.syncFromPdf
  96. )
  97. app.get(
  98. '/project/:project_id/user/:user_id/wordcount',
  99. CompileController.wordcount
  100. )
  101. const ForbidSymlinks = require('./app/js/StaticServerForbidSymlinks')
  102. // create a static server which does not allow access to any symlinks
  103. // avoids possible mismatch of root directory between middleware check
  104. // and serving the files
  105. const staticServer = ForbidSymlinks(express.static, Settings.path.compilesDir, {
  106. setHeaders(res, path, stat) {
  107. if (Path.basename(path) === 'output.pdf') {
  108. // Calculate an etag in the same way as nginx
  109. // https://github.com/tj/send/issues/65
  110. const etag = (path, stat) =>
  111. `"${Math.ceil(+stat.mtime / 1000).toString(16)}` +
  112. '-' +
  113. Number(stat.size).toString(16) +
  114. '"'
  115. res.set('Etag', etag(path, stat))
  116. }
  117. return res.set('Content-Type', ContentTypeMapper.map(path))
  118. }
  119. })
  120. app.get('/project/:project_id/user/:user_id/build/:build_id/output/*', function(
  121. req,
  122. res,
  123. next
  124. ) {
  125. // for specific build get the path from the OutputCacheManager (e.g. .clsi/buildId)
  126. req.url =
  127. `/${req.params.project_id}-${req.params.user_id}/` +
  128. OutputCacheManager.path(req.params.build_id, `/${req.params[0]}`)
  129. return staticServer(req, res, next)
  130. })
  131. app.get('/project/:project_id/build/:build_id/output/*', function(
  132. req,
  133. res,
  134. next
  135. ) {
  136. // for specific build get the path from the OutputCacheManager (e.g. .clsi/buildId)
  137. req.url =
  138. `/${req.params.project_id}/` +
  139. OutputCacheManager.path(req.params.build_id, `/${req.params[0]}`)
  140. return staticServer(req, res, next)
  141. })
  142. app.get('/project/:project_id/user/:user_id/output/*', function(
  143. req,
  144. res,
  145. next
  146. ) {
  147. // for specific user get the path to the top level file
  148. req.url = `/${req.params.project_id}-${req.params.user_id}/${req.params[0]}`
  149. return staticServer(req, res, next)
  150. })
  151. app.get('/project/:project_id/output/*', function(req, res, next) {
  152. if (
  153. (req.query != null ? req.query.build : undefined) != null &&
  154. req.query.build.match(OutputCacheManager.BUILD_REGEX)
  155. ) {
  156. // for specific build get the path from the OutputCacheManager (e.g. .clsi/buildId)
  157. req.url =
  158. `/${req.params.project_id}/` +
  159. OutputCacheManager.path(req.query.build, `/${req.params[0]}`)
  160. } else {
  161. req.url = `/${req.params.project_id}/${req.params[0]}`
  162. }
  163. return staticServer(req, res, next)
  164. })
  165. app.get('/oops', function(req, res, next) {
  166. logger.error({ err: 'hello' }, 'test error')
  167. return res.send('error\n')
  168. })
  169. app.get('/status', (req, res, next) => res.send('CLSI is alive\n'))
  170. const resCacher = {
  171. contentType(setContentType) {
  172. this.setContentType = setContentType
  173. },
  174. send(code, body) {
  175. this.code = code
  176. this.body = body
  177. },
  178. // default the server to be down
  179. code: 500,
  180. body: {},
  181. setContentType: 'application/json'
  182. }
  183. const startupTime = Date.now()
  184. const checkIfProcessIsTooOld = function(cont) {
  185. if (typeof Settings.processLifespanLimitMs === 'string') {
  186. Settings.processLifespanLimitMs = parseInt(Settings.processLifespanLimitMs)
  187. Settings.processLifespanLimitMs +=
  188. Settings.processLifespanLimitMs * (Math.random() / 10)
  189. }
  190. if (
  191. Settings.processLifespanLimitMs &&
  192. startupTime + Settings.processLifespanLimitMs < Date.now()
  193. ) {
  194. logger.log('shutting down, process is too old')
  195. resCacher.send = function() {}
  196. resCacher.code = 500
  197. resCacher.body = { processToOld: true }
  198. } else {
  199. cont()
  200. }
  201. }
  202. if (Settings.smokeTest) {
  203. const runSmokeTest = function() {
  204. checkIfProcessIsTooOld(function() {
  205. logger.log('running smoke tests')
  206. smokeTest.run(
  207. require.resolve(__dirname + '/test/smoke/js/SmokeTests.js')
  208. )({}, resCacher)
  209. return setTimeout(runSmokeTest, 30 * 1000)
  210. })
  211. }
  212. runSmokeTest()
  213. }
  214. app.get('/health_check', function(req, res) {
  215. res.contentType(resCacher.setContentType)
  216. return res.status(resCacher.code).send(resCacher.body)
  217. })
  218. app.get('/smoke_test_force', (req, res) =>
  219. smokeTest.run(require.resolve(__dirname + '/test/smoke/js/SmokeTests.js'))(
  220. req,
  221. res
  222. )
  223. )
  224. app.use(function(error, req, res, next) {
  225. if (error instanceof Errors.NotFoundError) {
  226. logger.warn({ err: error, url: req.url }, 'not found error')
  227. return res.sendStatus(404)
  228. } else {
  229. logger.error({ err: error, url: req.url }, 'server error')
  230. return res.sendStatus((error != null ? error.statusCode : undefined) || 500)
  231. }
  232. })
  233. const net = require('net')
  234. const os = require('os')
  235. let STATE = 'up'
  236. const loadTcpServer = net.createServer(function(socket) {
  237. socket.on('error', function(err) {
  238. if (err.code === 'ECONNRESET') {
  239. // this always comes up, we don't know why
  240. return
  241. }
  242. logger.err({ err }, 'error with socket on load check')
  243. return socket.destroy()
  244. })
  245. if (STATE === 'up' && Settings.internal.load_balancer_agent.report_load) {
  246. let availableWorkingCpus
  247. const currentLoad = os.loadavg()[0]
  248. // staging clis's have 1 cpu core only
  249. if (os.cpus().length === 1) {
  250. availableWorkingCpus = 1
  251. } else {
  252. availableWorkingCpus = os.cpus().length - 1
  253. }
  254. const freeLoad = availableWorkingCpus - currentLoad
  255. let freeLoadPercentage = Math.round((freeLoad / availableWorkingCpus) * 100)
  256. if (freeLoadPercentage <= 0) {
  257. freeLoadPercentage = 1 // when its 0 the server is set to drain and will move projects to different servers
  258. }
  259. socket.write(`up, ${freeLoadPercentage}%\n`, 'ASCII')
  260. return socket.end()
  261. } else {
  262. socket.write(`${STATE}\n`, 'ASCII')
  263. return socket.end()
  264. }
  265. })
  266. const loadHttpServer = express()
  267. loadHttpServer.post('/state/up', function(req, res, next) {
  268. STATE = 'up'
  269. logger.info('getting message to set server to down')
  270. return res.sendStatus(204)
  271. })
  272. loadHttpServer.post('/state/down', function(req, res, next) {
  273. STATE = 'down'
  274. logger.info('getting message to set server to down')
  275. return res.sendStatus(204)
  276. })
  277. loadHttpServer.post('/state/maint', function(req, res, next) {
  278. STATE = 'maint'
  279. logger.info('getting message to set server to maint')
  280. return res.sendStatus(204)
  281. })
  282. const port =
  283. __guard__(
  284. Settings.internal != null ? Settings.internal.clsi : undefined,
  285. x => x.port
  286. ) || 3013
  287. const host =
  288. __guard__(
  289. Settings.internal != null ? Settings.internal.clsi : undefined,
  290. x1 => x1.host
  291. ) || 'localhost'
  292. const load_tcp_port = Settings.internal.load_balancer_agent.load_port
  293. const load_http_port = Settings.internal.load_balancer_agent.local_port
  294. if (!module.parent) {
  295. // Called directly
  296. app.listen(port, host, error =>
  297. logger.info(`CLSI starting up, listening on ${host}:${port}`)
  298. )
  299. loadTcpServer.listen(load_tcp_port, host, function(error) {
  300. if (error != null) {
  301. throw error
  302. }
  303. return logger.info(`Load tcp agent listening on load port ${load_tcp_port}`)
  304. })
  305. loadHttpServer.listen(load_http_port, host, function(error) {
  306. if (error != null) {
  307. throw error
  308. }
  309. return logger.info(
  310. `Load http agent listening on load port ${load_http_port}`
  311. )
  312. })
  313. }
  314. module.exports = app
  315. setInterval(
  316. () => ProjectPersistenceManager.clearExpiredProjects(),
  317. (tenMinutes = 10 * 60 * 1000)
  318. )
  319. function __guard__(value, transform) {
  320. return typeof value !== 'undefined' && value !== null
  321. ? transform(value)
  322. : undefined
  323. }