app.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  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. const tenMinutes = 10 * 60 * 1000
  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('./test/smoke/js/SmokeTests')
  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, projectId) {
  43. if (projectId != null ? projectId.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, userId) {
  50. if (userId != null ? userId.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, buildId) {
  57. if (
  58. buildId != null ? buildId.match(OutputCacheManager.BUILD_REGEX) : undefined
  59. ) {
  60. return next()
  61. } else {
  62. return next(new Error(`invalid build id ${buildId}`))
  63. }
  64. })
  65. app.post(
  66. '/project/:project_id/compile',
  67. bodyParser.json({ limit: Settings.compileSizeLimit }),
  68. CompileController.compile
  69. )
  70. app.post('/project/:project_id/compile/stop', CompileController.stopCompile)
  71. app.delete('/project/:project_id', CompileController.clearCache)
  72. app.get('/project/:project_id/sync/code', CompileController.syncFromCode)
  73. app.get('/project/:project_id/sync/pdf', CompileController.syncFromPdf)
  74. app.get('/project/:project_id/wordcount', CompileController.wordcount)
  75. app.get('/project/:project_id/status', CompileController.status)
  76. // Per-user containers
  77. app.post(
  78. '/project/:project_id/user/:user_id/compile',
  79. bodyParser.json({ limit: Settings.compileSizeLimit }),
  80. CompileController.compile
  81. )
  82. app.post(
  83. '/project/:project_id/user/:user_id/compile/stop',
  84. CompileController.stopCompile
  85. )
  86. app.delete('/project/:project_id/user/:user_id', CompileController.clearCache)
  87. app.get(
  88. '/project/:project_id/user/:user_id/sync/code',
  89. CompileController.syncFromCode
  90. )
  91. app.get(
  92. '/project/:project_id/user/:user_id/sync/pdf',
  93. CompileController.syncFromPdf
  94. )
  95. app.get(
  96. '/project/:project_id/user/:user_id/wordcount',
  97. CompileController.wordcount
  98. )
  99. const ForbidSymlinks = require('./app/js/StaticServerForbidSymlinks')
  100. // create a static server which does not allow access to any symlinks
  101. // avoids possible mismatch of root directory between middleware check
  102. // and serving the files
  103. const staticServer = ForbidSymlinks(express.static, Settings.path.compilesDir, {
  104. setHeaders(res, path, stat) {
  105. if (Path.basename(path) === 'output.pdf') {
  106. // Calculate an etag in the same way as nginx
  107. // https://github.com/tj/send/issues/65
  108. const etag = (path, stat) =>
  109. `"${Math.ceil(+stat.mtime / 1000).toString(16)}` +
  110. '-' +
  111. Number(stat.size).toString(16) +
  112. '"'
  113. res.set('Etag', etag(path, stat))
  114. }
  115. return res.set('Content-Type', ContentTypeMapper.map(path))
  116. }
  117. })
  118. app.get(
  119. '/project/:project_id/user/:user_id/build/:build_id/output/*',
  120. function (req, res, next) {
  121. // for specific build get the path from the OutputCacheManager (e.g. .clsi/buildId)
  122. req.url =
  123. `/${req.params.project_id}-${req.params.user_id}/` +
  124. OutputCacheManager.path(req.params.build_id, `/${req.params[0]}`)
  125. return staticServer(req, res, next)
  126. }
  127. )
  128. app.get('/project/:project_id/build/:build_id/output/*', function (
  129. req,
  130. res,
  131. next
  132. ) {
  133. // for specific build get the path from the OutputCacheManager (e.g. .clsi/buildId)
  134. req.url =
  135. `/${req.params.project_id}/` +
  136. OutputCacheManager.path(req.params.build_id, `/${req.params[0]}`)
  137. return staticServer(req, res, next)
  138. })
  139. app.get('/project/:project_id/user/:user_id/output/*', function (
  140. req,
  141. res,
  142. next
  143. ) {
  144. // for specific user get the path to the top level file
  145. req.url = `/${req.params.project_id}-${req.params.user_id}/${req.params[0]}`
  146. return staticServer(req, res, next)
  147. })
  148. app.get('/project/:project_id/output/*', function (req, res, next) {
  149. if (
  150. (req.query != null ? req.query.build : undefined) != null &&
  151. req.query.build.match(OutputCacheManager.BUILD_REGEX)
  152. ) {
  153. // for specific build get the path from the OutputCacheManager (e.g. .clsi/buildId)
  154. req.url =
  155. `/${req.params.project_id}/` +
  156. OutputCacheManager.path(req.query.build, `/${req.params[0]}`)
  157. } else {
  158. req.url = `/${req.params.project_id}/${req.params[0]}`
  159. }
  160. return staticServer(req, res, next)
  161. })
  162. app.get('/oops', function (req, res, next) {
  163. logger.error({ err: 'hello' }, 'test error')
  164. return res.send('error\n')
  165. })
  166. app.get('/status', (req, res, next) => res.send('CLSI is alive\n'))
  167. Settings.processTooOld = false
  168. if (Settings.processLifespanLimitMs) {
  169. Settings.processLifespanLimitMs +=
  170. Settings.processLifespanLimitMs * (Math.random() / 10)
  171. logger.info(
  172. 'Lifespan limited to ',
  173. Date.now() + Settings.processLifespanLimitMs
  174. )
  175. setTimeout(() => {
  176. logger.log('shutting down, process is too old')
  177. Settings.processTooOld = true
  178. }, Settings.processLifespanLimitMs)
  179. }
  180. function runSmokeTest() {
  181. if (Settings.processTooOld) return
  182. logger.log('running smoke tests')
  183. smokeTest.triggerRun((err) => {
  184. if (err) logger.error({ err }, 'smoke tests failed')
  185. setTimeout(runSmokeTest, 30 * 1000)
  186. })
  187. }
  188. if (Settings.smokeTest) {
  189. runSmokeTest()
  190. }
  191. app.get('/health_check', function (req, res) {
  192. if (Settings.processTooOld) {
  193. return res.status(500).json({ processTooOld: true })
  194. }
  195. smokeTest.sendLastResult(res)
  196. })
  197. app.get('/smoke_test_force', (req, res) => smokeTest.sendNewResult(res))
  198. app.use(function (error, req, res, next) {
  199. if (error instanceof Errors.NotFoundError) {
  200. logger.log({ err: error, url: req.url }, 'not found error')
  201. return res.sendStatus(404)
  202. } else if (error.code === 'EPIPE') {
  203. // inspect container returns EPIPE when shutting down
  204. return res.sendStatus(503) // send 503 Unavailable response
  205. } else {
  206. logger.error({ err: error, url: req.url }, 'server error')
  207. return res.sendStatus((error != null ? error.statusCode : undefined) || 500)
  208. }
  209. })
  210. const net = require('net')
  211. const os = require('os')
  212. let STATE = 'up'
  213. const loadTcpServer = net.createServer(function (socket) {
  214. socket.on('error', function (err) {
  215. if (err.code === 'ECONNRESET') {
  216. // this always comes up, we don't know why
  217. return
  218. }
  219. logger.err({ err }, 'error with socket on load check')
  220. return socket.destroy()
  221. })
  222. if (STATE === 'up' && Settings.internal.load_balancer_agent.report_load) {
  223. let availableWorkingCpus
  224. const currentLoad = os.loadavg()[0]
  225. // staging clis's have 1 cpu core only
  226. if (os.cpus().length === 1) {
  227. availableWorkingCpus = 1
  228. } else {
  229. availableWorkingCpus = os.cpus().length - 1
  230. }
  231. const freeLoad = availableWorkingCpus - currentLoad
  232. let freeLoadPercentage = Math.round((freeLoad / availableWorkingCpus) * 100)
  233. if (freeLoadPercentage <= 0) {
  234. freeLoadPercentage = 1 // when its 0 the server is set to drain and will move projects to different servers
  235. }
  236. socket.write(`up, ${freeLoadPercentage}%\n`, 'ASCII')
  237. return socket.end()
  238. } else {
  239. socket.write(`${STATE}\n`, 'ASCII')
  240. return socket.end()
  241. }
  242. })
  243. const loadHttpServer = express()
  244. loadHttpServer.post('/state/up', function (req, res, next) {
  245. STATE = 'up'
  246. logger.info('getting message to set server to down')
  247. return res.sendStatus(204)
  248. })
  249. loadHttpServer.post('/state/down', function (req, res, next) {
  250. STATE = 'down'
  251. logger.info('getting message to set server to down')
  252. return res.sendStatus(204)
  253. })
  254. loadHttpServer.post('/state/maint', function (req, res, next) {
  255. STATE = 'maint'
  256. logger.info('getting message to set server to maint')
  257. return res.sendStatus(204)
  258. })
  259. const port =
  260. __guard__(
  261. Settings.internal != null ? Settings.internal.clsi : undefined,
  262. (x) => x.port
  263. ) || 3013
  264. const host =
  265. __guard__(
  266. Settings.internal != null ? Settings.internal.clsi : undefined,
  267. (x1) => x1.host
  268. ) || 'localhost'
  269. const loadTcpPort = Settings.internal.load_balancer_agent.load_port
  270. const loadHttpPort = Settings.internal.load_balancer_agent.local_port
  271. if (!module.parent) {
  272. // Called directly
  273. app.listen(port, host, (error) => {
  274. if (error) {
  275. logger.fatal({ error }, `Error starting CLSI on ${host}:${port}`)
  276. } else {
  277. logger.info(`CLSI starting up, listening on ${host}:${port}`)
  278. }
  279. })
  280. loadTcpServer.listen(loadTcpPort, host, function (error) {
  281. if (error != null) {
  282. throw error
  283. }
  284. return logger.info(`Load tcp agent listening on load port ${loadTcpPort}`)
  285. })
  286. loadHttpServer.listen(loadHttpPort, host, function (error) {
  287. if (error != null) {
  288. throw error
  289. }
  290. return logger.info(`Load http agent listening on load port ${loadHttpPort}`)
  291. })
  292. }
  293. module.exports = app
  294. setInterval(() => {
  295. ProjectPersistenceManager.refreshExpiryTimeout()
  296. ProjectPersistenceManager.clearExpiredProjects()
  297. }, tenMinutes)
  298. function __guard__(value, transform) {
  299. return typeof value !== 'undefined' && value !== null
  300. ? transform(value)
  301. : undefined
  302. }