app.js 10 KB

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