app.coffee 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. CompileController = require "./app/js/CompileController"
  2. Settings = require "settings-sharelatex"
  3. logger = require "logger-sharelatex"
  4. logger.initialize("clsi")
  5. if Settings.sentry?.dsn?
  6. logger.initializeErrorReporting(Settings.sentry.dsn)
  7. smokeTest = require "smoke-test-sharelatex"
  8. ContentTypeMapper = require "./app/js/ContentTypeMapper"
  9. Errors = require './app/js/Errors'
  10. Path = require "path"
  11. fs = require "fs"
  12. Metrics = require "metrics-sharelatex"
  13. Metrics.initialize("clsi")
  14. Metrics.open_sockets.monitor(logger)
  15. Metrics.memory.monitor(logger)
  16. ProjectPersistenceManager = require "./app/js/ProjectPersistenceManager"
  17. OutputCacheManager = require "./app/js/OutputCacheManager"
  18. require("./app/js/db").sync()
  19. express = require "express"
  20. bodyParser = require "body-parser"
  21. app = express()
  22. app.use Metrics.http.monitor(logger)
  23. # Compile requests can take longer than the default two
  24. # minutes (including file download time), so bump up the
  25. # timeout a bit.
  26. TIMEOUT = 6 * 60 * 1000
  27. app.use (req, res, next) ->
  28. req.setTimeout TIMEOUT
  29. res.setTimeout TIMEOUT
  30. next()
  31. app.param 'project_id', (req, res, next, project_id) ->
  32. if project_id?.match /^[a-zA-Z0-9_-]+$/
  33. next()
  34. else
  35. next new Error("invalid project id")
  36. app.param 'user_id', (req, res, next, user_id) ->
  37. if user_id?.match /^[0-9a-f]{24}$/
  38. next()
  39. else
  40. next new Error("invalid user id")
  41. app.param 'build_id', (req, res, next, build_id) ->
  42. if build_id?.match OutputCacheManager.BUILD_REGEX
  43. next()
  44. else
  45. next new Error("invalid build id #{build_id}")
  46. app.post "/project/:project_id/compile", bodyParser.json(limit: "5mb"), CompileController.compile
  47. app.post "/project/:project_id/compile/stop", CompileController.stopCompile
  48. app.delete "/project/:project_id", CompileController.clearCache
  49. app.get "/project/:project_id/sync/code", CompileController.syncFromCode
  50. app.get "/project/:project_id/sync/pdf", CompileController.syncFromPdf
  51. app.get "/project/:project_id/wordcount", CompileController.wordcount
  52. app.get "/project/:project_id/status", CompileController.status
  53. # Per-user containers
  54. app.post "/project/:project_id/user/:user_id/compile", bodyParser.json(limit: "5mb"), CompileController.compile
  55. app.post "/project/:project_id/user/:user_id/compile/stop", CompileController.stopCompile
  56. app.delete "/project/:project_id/user/:user_id", CompileController.clearCache
  57. app.get "/project/:project_id/user/:user_id/sync/code", CompileController.syncFromCode
  58. app.get "/project/:project_id/user/:user_id/sync/pdf", CompileController.syncFromPdf
  59. app.get "/project/:project_id/user/:user_id/wordcount", CompileController.wordcount
  60. ForbidSymlinks = require "./app/js/StaticServerForbidSymlinks"
  61. # create a static server which does not allow access to any symlinks
  62. # avoids possible mismatch of root directory between middleware check
  63. # and serving the files
  64. staticServer = ForbidSymlinks express.static, Settings.path.compilesDir, setHeaders: (res, path, stat) ->
  65. if Path.basename(path) == "output.pdf"
  66. # Calculate an etag in the same way as nginx
  67. # https://github.com/tj/send/issues/65
  68. etag = (path, stat) ->
  69. '"' + Math.ceil(+stat.mtime / 1000).toString(16) +
  70. '-' + Number(stat.size).toString(16) + '"'
  71. res.set("Etag", etag(path, stat))
  72. res.set("Content-Type", ContentTypeMapper.map(path))
  73. app.get "/project/:project_id/user/:user_id/build/:build_id/output/*", (req, res, next) ->
  74. # for specific build get the path from the OutputCacheManager (e.g. .clsi/buildId)
  75. req.url = "/#{req.params.project_id}-#{req.params.user_id}/" + OutputCacheManager.path(req.params.build_id, "/#{req.params[0]}")
  76. staticServer(req, res, next)
  77. app.get "/project/:project_id/build/:build_id/output/*", (req, res, next) ->
  78. # for specific build get the path from the OutputCacheManager (e.g. .clsi/buildId)
  79. req.url = "/#{req.params.project_id}/" + OutputCacheManager.path(req.params.build_id, "/#{req.params[0]}")
  80. staticServer(req, res, next)
  81. app.get "/project/:project_id/user/:user_id/output/*", (req, res, next) ->
  82. # for specific user get the path to the top level file
  83. req.url = "/#{req.params.project_id}-#{req.params.user_id}/#{req.params[0]}"
  84. staticServer(req, res, next)
  85. app.get "/project/:project_id/output/*", (req, res, next) ->
  86. if req.query?.build? && req.query.build.match(OutputCacheManager.BUILD_REGEX)
  87. # for specific build get the path from the OutputCacheManager (e.g. .clsi/buildId)
  88. req.url = "/#{req.params.project_id}/" + OutputCacheManager.path(req.query.build, "/#{req.params[0]}")
  89. else
  90. req.url = "/#{req.params.project_id}/#{req.params[0]}"
  91. staticServer(req, res, next)
  92. app.get "/oops", (req, res, next) ->
  93. logger.error {err: "hello"}, "test error"
  94. res.send "error\n"
  95. app.get "/status", (req, res, next) ->
  96. res.send "CLSI is alive\n"
  97. resCacher =
  98. contentType:(@setContentType)->
  99. send:(@code, @body)->
  100. #default the server to be down
  101. code:500
  102. body:{}
  103. setContentType:"application/json"
  104. if Settings.smokeTest
  105. do runSmokeTest = ->
  106. logger.log("running smoke tests")
  107. smokeTest.run(require.resolve(__dirname + "/test/smoke/js/SmokeTests.js"))({}, resCacher)
  108. setTimeout(runSmokeTest, 30 * 1000)
  109. app.get "/health_check", (req, res)->
  110. res.contentType(resCacher?.setContentType)
  111. res.status(resCacher?.code).send(resCacher?.body)
  112. profiler = require "v8-profiler"
  113. app.get "/profile", (req, res) ->
  114. time = parseInt(req.query.time || "1000")
  115. profiler.startProfiling("test")
  116. setTimeout () ->
  117. profile = profiler.stopProfiling("test")
  118. res.json(profile)
  119. , time
  120. app.get "/heapdump", (req, res)->
  121. require('heapdump').writeSnapshot '/tmp/' + Date.now() + '.clsi.heapsnapshot', (err, filename)->
  122. res.send filename
  123. app.use (error, req, res, next) ->
  124. if error instanceof Errors.NotFoundError
  125. logger.warn {err: error, url: req.url}, "not found error"
  126. return res.sendStatus(404)
  127. else
  128. logger.error {err: error, url: req.url}, "server error"
  129. res.sendStatus(error?.statusCode || 500)
  130. app.listen port = (Settings.internal?.clsi?.port or 3013), host = (Settings.internal?.clsi?.host or "localhost"), (error) ->
  131. logger.info "CLSI starting up, listening on #{host}:#{port}"
  132. setInterval () ->
  133. ProjectPersistenceManager.clearExpiredProjects()
  134. , tenMinutes = 10 * 60 * 1000