app.coffee 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  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. console.log(__dirname, __filename)
  108. smokeTest.run(require.resolve(__dirname + "/test/smoke/js/SmokeTests.js"))({}, resCacher)
  109. setTimeout(runSmokeTest, 30 * 1000)
  110. app.get "/health_check", (req, res)->
  111. res.contentType(resCacher?.setContentType)
  112. res.status(resCacher?.code).send(resCacher?.body)
  113. app.get "/smoke_test_force", (req, res)->
  114. smokeTest.run(require.resolve(__dirname + "/test/smoke/js/SmokeTests.js"))(req, res)
  115. #TODO delete this
  116. app.get "/settings", (req, res)->
  117. res.json(Settings)
  118. profiler = require "v8-profiler"
  119. app.get "/profile", (req, res) ->
  120. time = parseInt(req.query.time || "1000")
  121. profiler.startProfiling("test")
  122. setTimeout () ->
  123. profile = profiler.stopProfiling("test")
  124. res.json(profile)
  125. , time
  126. app.get "/heapdump", (req, res)->
  127. require('heapdump').writeSnapshot '/tmp/' + Date.now() + '.clsi.heapsnapshot', (err, filename)->
  128. res.send filename
  129. app.use (error, req, res, next) ->
  130. if error instanceof Errors.NotFoundError
  131. logger.warn {err: error, url: req.url}, "not found error"
  132. return res.sendStatus(404)
  133. else
  134. logger.error {err: error, url: req.url}, "server error"
  135. res.sendStatus(error?.statusCode || 500)
  136. net = require "net"
  137. os = require "os"
  138. STATE = "up"
  139. server = net.createServer (socket) ->
  140. socket.on "error", (err)->
  141. if err.code == "ECONNRESET"
  142. # this always comes up, we don't know why
  143. return
  144. logger.err err:err, "error with socket on load check"
  145. socket.destroy()
  146. if STATE == "up" and settings.load_balancer_agent.report_load
  147. currentLoad = os.loadavg()[0]
  148. # staging clis's have 1 cpu core only
  149. if os.cpus().length == 1
  150. availableWorkingCpus = 1
  151. else
  152. availableWorkingCpus = os.cpus().length - 1
  153. freeLoad = availableWorkingCpus - currentLoad
  154. freeLoadPercentage = Math.round((freeLoad / availableWorkingCpus) * 100)
  155. if freeLoadPercentage <= 0
  156. freeLoadPercentage = 1 # when its 0 the server is set to drain and will move projects to different servers
  157. socket.write("up, #{freeLoadPercentage}%\n", "ASCII")
  158. socket.end()
  159. else
  160. socket.write("#{STATE}\n", "ASCII")
  161. socket.end()
  162. port = (Settings.internal?.clsi?.port or 3013)
  163. host = (Settings.internal?.clsi?.host or "localhost")
  164. load_port = settings.internal.clsi.load_port or 3048
  165. if !module.parent # Called directly
  166. app.listen port, host, (error) ->
  167. logger.info "CLSI starting up, listening on #{host}:#{port}"
  168. server.listen load_port, host, (error) ->
  169. throw error if error?
  170. logger.info "Load agent listening on load port #{load_port}"
  171. module.exports = app
  172. setInterval () ->
  173. ProjectPersistenceManager.clearExpiredProjects()
  174. , tenMinutes = 10 * 60 * 1000