ClsiManager.coffee 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. Path = require "path"
  2. async = require "async"
  3. Settings = require "settings-sharelatex"
  4. request = require('request')
  5. Project = require("../../models/Project").Project
  6. ProjectGetter = require("../Project/ProjectGetter")
  7. ProjectEntityHandler = require("../Project/ProjectEntityHandler")
  8. logger = require "logger-sharelatex"
  9. Url = require("url")
  10. ClsiCookieManager = require("./ClsiCookieManager")
  11. ClsiStateManager = require("./ClsiStateManager")
  12. _ = require("underscore")
  13. async = require("async")
  14. ClsiFormatChecker = require("./ClsiFormatChecker")
  15. DocumentUpdaterHandler = require "../DocumentUpdater/DocumentUpdaterHandler"
  16. Metrics = require('metrics-sharelatex')
  17. module.exports = ClsiManager =
  18. sendRequest: (project_id, user_id, options = {}, callback) ->
  19. ClsiManager.sendRequestOnce project_id, user_id, options, (error, status, result...) ->
  20. return callback(error) if error?
  21. if status is 'conflict'
  22. options = _.clone(options)
  23. options.syncType = "full" # force full compile
  24. ClsiManager.sendRequestOnce project_id, user_id, options, callback # try again
  25. else
  26. callback(error, status, result...)
  27. sendRequestOnce: (project_id, user_id, options = {}, callback = (error, status, outputFiles, clsiServerId, validationProblems) ->) ->
  28. ClsiManager._buildRequest project_id, options, (error, req) ->
  29. return callback(error) if error?
  30. logger.log project_id: project_id, "sending compile to CLSI"
  31. ClsiFormatChecker.checkRecoursesForProblems req.compile?.resources, (err, validationProblems)->
  32. if err?
  33. logger.err err, project_id, "could not check resources for potential problems before sending to clsi"
  34. return callback(err)
  35. if validationProblems?
  36. logger.log project_id:project_id, validationProblems:validationProblems, "problems with users latex before compile was attempted"
  37. return callback(null, "validation-problems", null, null, validationProblems)
  38. ClsiManager._postToClsi project_id, user_id, req, options.compileGroup, (error, response) ->
  39. if error?
  40. logger.err err:error, project_id:project_id, "error sending request to clsi"
  41. return callback(error)
  42. logger.log project_id: project_id, outputFilesLength: response?.outputFiles?.length, status: response?.status, compile_status: response?.compile?.status, "received compile response from CLSI"
  43. ClsiCookieManager._getServerId project_id, (err, clsiServerId)->
  44. if err?
  45. logger.err err:err, project_id:project_id, "error getting server id"
  46. return callback(err)
  47. outputFiles = ClsiManager._parseOutputFiles(project_id, response?.compile?.outputFiles)
  48. callback(null, response?.compile?.status, outputFiles, clsiServerId)
  49. stopCompile: (project_id, user_id, options, callback = (error) ->) ->
  50. compilerUrl = @_getCompilerUrl(options?.compileGroup, project_id, user_id, "compile/stop")
  51. opts =
  52. url:compilerUrl
  53. method:"POST"
  54. ClsiManager._makeRequest project_id, opts, callback
  55. deleteAuxFiles: (project_id, user_id, options, callback = (error) ->) ->
  56. compilerUrl = @_getCompilerUrl(options?.compileGroup, project_id, user_id)
  57. opts =
  58. url:compilerUrl
  59. method:"DELETE"
  60. ClsiManager._makeRequest project_id, opts, callback
  61. _makeRequest: (project_id, opts, callback)->
  62. ClsiCookieManager.getCookieJar project_id, (err, jar)->
  63. if err?
  64. logger.err err:err, "error getting cookie jar for clsi request"
  65. return callback(err)
  66. opts.jar = jar
  67. request opts, (err, response, body)->
  68. if err?
  69. logger.err err:err, project_id:project_id, url:opts?.url, "error making request to clsi"
  70. return callback(err)
  71. ClsiCookieManager.setServerId project_id, response, (err)->
  72. if err?
  73. logger.warn err:err, project_id:project_id, "error setting server id"
  74. return callback err, response, body
  75. _getCompilerUrl: (compileGroup, project_id, user_id, action) ->
  76. host = Settings.apis.clsi.url
  77. path = "/project/#{project_id}"
  78. path += "/user/#{user_id}" if user_id?
  79. path += "/#{action}" if action?
  80. return "#{host}#{path}"
  81. _postToClsi: (project_id, user_id, req, compileGroup, callback = (error, response) ->) ->
  82. compileUrl = @_getCompilerUrl(compileGroup, project_id, user_id, "compile")
  83. opts =
  84. url: compileUrl
  85. json: req
  86. method: "POST"
  87. ClsiManager._makeRequest project_id, opts, (error, response, body) ->
  88. return callback(error) if error?
  89. if 200 <= response.statusCode < 300
  90. callback null, body
  91. else if response.statusCode == 413
  92. callback null, compile:status:"project-too-large"
  93. else if response.statusCode == 409
  94. callback null, compile:status:"conflict"
  95. else
  96. error = new Error("CLSI returned non-success code: #{response.statusCode}")
  97. logger.error err: error, project_id: project_id, "CLSI returned failure code"
  98. callback error, body
  99. _parseOutputFiles: (project_id, rawOutputFiles = []) ->
  100. outputFiles = []
  101. for file in rawOutputFiles
  102. outputFiles.push
  103. path: file.path # the clsi is now sending this to web
  104. url: Url.parse(file.url).path # the location of the file on the clsi, excluding the host part
  105. type: file.type
  106. build: file.build
  107. return outputFiles
  108. VALID_COMPILERS: ["pdflatex", "latex", "xelatex", "lualatex"]
  109. _buildRequest: (project_id, options={}, callback = (error, request) ->) ->
  110. ProjectGetter.getProject project_id, {compiler: 1, rootDoc_id: 1, imageName: 1, rootFolder:1}, (error, project) ->
  111. return callback(error) if error?
  112. return callback(new Errors.NotFoundError("project does not exist: #{project_id}")) if !project?
  113. if project.compiler not in ClsiManager.VALID_COMPILERS
  114. project.compiler = "pdflatex"
  115. if options.incrementalCompilesEnabled or options.syncType? # new way, either incremental or full
  116. timer = new Metrics.Timer("editor.compile-getdocs-redis")
  117. ClsiManager.getContentFromDocUpdaterIfMatch project_id, project, (error, projectStateHash, docUpdaterDocs) ->
  118. timer.done()
  119. return callback(error) if error?
  120. logger.log project_id: project_id, projectStateHash: projectStateHash, docs: docUpdaterDocs?, "checked project state"
  121. # see if we can send an incremental update to the CLSI
  122. if docUpdaterDocs? and options.syncType isnt "full"
  123. # Workaround: for now, always flush project to mongo on compile
  124. # until we have automatic periodic flushing on the docupdater
  125. # side, to prevent documents staying in redis too long.
  126. DocumentUpdaterHandler.flushProjectToMongo project_id, (error) ->
  127. return callback(error) if error?
  128. Metrics.inc "compile-from-redis"
  129. ClsiManager._buildRequestFromDocupdater project_id, options, project, projectStateHash, docUpdaterDocs, callback
  130. else
  131. Metrics.inc "compile-from-mongo"
  132. ClsiManager._buildRequestFromMongo project_id, options, project, projectStateHash, callback
  133. else # old way, always from mongo
  134. timer = new Metrics.Timer("editor.compile-getdocs-mongo")
  135. ClsiManager._getContentFromMongo project_id, (error, docs, files) ->
  136. timer.done()
  137. return callback(error) if error?
  138. ClsiManager._finaliseRequest project_id, options, project, docs, files, callback
  139. getContentFromDocUpdaterIfMatch: (project_id, project, callback = (error, projectStateHash, docs) ->) ->
  140. ClsiStateManager.computeHash project, (error, projectStateHash) ->
  141. return callback(error) if error?
  142. DocumentUpdaterHandler.getProjectDocsIfMatch project_id, projectStateHash, (error, docs) ->
  143. return callback(error) if error?
  144. callback(null, projectStateHash, docs)
  145. _buildRequestFromDocupdater: (project_id, options, project, projectStateHash, docUpdaterDocs, callback = (error, request) ->) ->
  146. ProjectEntityHandler.getAllDocPathsFromProject project, (error, docPath) ->
  147. return callback(error) if error?
  148. docs = {}
  149. for doc in docUpdaterDocs or []
  150. path = docPath[doc._id]
  151. docs[path] = doc
  152. # send new docs but not files as those are already on the clsi
  153. options = _.clone(options)
  154. options.syncType = "incremental"
  155. options.syncState = projectStateHash
  156. ClsiManager._finaliseRequest project_id, options, project, docs, [], callback
  157. _buildRequestFromMongo: (project_id, options, project, projectStateHash, callback = (error, request) ->) ->
  158. ClsiManager._getContentFromMongo project_id, (error, docs, files) ->
  159. return callback(error) if error?
  160. options = _.clone(options)
  161. options.syncType = "full"
  162. options.syncState = projectStateHash
  163. ClsiManager._finaliseRequest project_id, options, project, docs, files, callback
  164. _getContentFromMongo: (project_id, callback = (error, docs, files) ->) ->
  165. DocumentUpdaterHandler.flushProjectToMongo project_id, (error) ->
  166. return callback(error) if error?
  167. ProjectEntityHandler.getAllDocs project_id, (error, docs = {}) ->
  168. return callback(error) if error?
  169. ProjectEntityHandler.getAllFiles project_id, (error, files = {}) ->
  170. return callback(error) if error?
  171. callback(null, docs, files)
  172. _finaliseRequest: (project_id, options, project, docs, files, callback = (error, params) -> ) ->
  173. resources = []
  174. rootResourcePath = null
  175. rootResourcePathOverride = null
  176. for path, doc of docs
  177. path = path.replace(/^\//, "") # Remove leading /
  178. resources.push
  179. path: path
  180. content: doc.lines.join("\n")
  181. if project.rootDoc_id? and doc._id.toString() == project.rootDoc_id.toString()
  182. rootResourcePath = path
  183. if options.rootDoc_id? and doc._id.toString() == options.rootDoc_id.toString()
  184. rootResourcePathOverride = path
  185. rootResourcePath = rootResourcePathOverride if rootResourcePathOverride?
  186. if !rootResourcePath?
  187. logger.warn {project_id}, "no root document found, setting to main.tex"
  188. rootResourcePath = "main.tex"
  189. for path, file of files
  190. path = path.replace(/^\//, "") # Remove leading /
  191. resources.push
  192. path: path
  193. url: "#{Settings.apis.filestore.url}/project/#{project._id}/file/#{file._id}"
  194. modified: file.created?.getTime()
  195. callback null, {
  196. compile:
  197. options:
  198. compiler: project.compiler
  199. timeout: options.timeout
  200. imageName: project.imageName
  201. draft: !!options.draft
  202. check: options.check
  203. syncType: options.syncType
  204. syncState: options.syncState
  205. rootResourcePath: rootResourcePath
  206. resources: resources
  207. }
  208. wordCount: (project_id, user_id, file, options, callback = (error, response) ->) ->
  209. ClsiManager._buildRequest project_id, options, (error, req) ->
  210. filename = file || req?.compile?.rootResourcePath
  211. wordcount_url = ClsiManager._getCompilerUrl(options?.compileGroup, project_id, user_id, "wordcount")
  212. opts =
  213. url: wordcount_url
  214. qs:
  215. file: filename
  216. image: req.compile.options.imageName
  217. method: "GET"
  218. ClsiManager._makeRequest project_id, opts, (error, response, body) ->
  219. return callback(error) if error?
  220. if 200 <= response.statusCode < 300
  221. callback null, body
  222. else
  223. error = new Error("CLSI returned non-success code: #{response.statusCode}")
  224. logger.error err: error, project_id: project_id, "CLSI returned failure code"
  225. callback error, body