ClsiManager.coffee 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  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. Errors = require ('../Errors/Errors')
  18. module.exports = ClsiManager =
  19. sendRequest: (project_id, user_id, options = {}, callback) ->
  20. ClsiManager.sendRequestOnce project_id, user_id, options, (error, status, result...) ->
  21. return callback(error) if error?
  22. if status is 'conflict'
  23. options = _.clone(options)
  24. options.syncType = "full" # force full compile
  25. ClsiManager.sendRequestOnce project_id, user_id, options, callback # try again
  26. else
  27. callback(error, status, result...)
  28. sendRequestOnce: (project_id, user_id, options = {}, callback = (error, status, outputFiles, clsiServerId, validationProblems) ->) ->
  29. ClsiManager._buildRequest project_id, options, (error, req) ->
  30. if error?
  31. if error.message is "no main file specified"
  32. return callback(null, "validation-problems", null, null, {mainFile:error.message})
  33. else
  34. return callback(error)
  35. logger.log project_id: project_id, "sending compile to CLSI"
  36. ClsiManager._sendBuiltRequest project_id, user_id, req, options, (error, status, result...) ->
  37. return callback(error) if error?
  38. callback(error, status, result...)
  39. # for public API requests where there is no project id
  40. sendExternalRequest: (submission_id, clsi_request, options = {}, callback = (error, status, outputFiles, clsiServerId, validationProblems) ->) ->
  41. logger.log submission_id: submission_id, "sending external compile to CLSI", clsi_request
  42. ClsiManager._sendBuiltRequest submission_id, null, clsi_request, options, (error, status, result...) ->
  43. return callback(error) if error?
  44. callback(error, status, result...)
  45. stopCompile: (project_id, user_id, options, callback = (error) ->) ->
  46. compilerUrl = @_getCompilerUrl(options?.compileGroup, project_id, user_id, "compile/stop")
  47. opts =
  48. url:compilerUrl
  49. method:"POST"
  50. ClsiManager._makeRequest project_id, opts, callback
  51. deleteAuxFiles: (project_id, user_id, options, callback = (error) ->) ->
  52. compilerUrl = @_getCompilerUrl(options?.compileGroup, project_id, user_id)
  53. opts =
  54. url:compilerUrl
  55. method:"DELETE"
  56. ClsiManager._makeRequest project_id, opts, (clsiError) ->
  57. # always clear the project state from the docupdater, even if there
  58. # was a problem with the request to the clsi
  59. DocumentUpdaterHandler.clearProjectState project_id, (docUpdaterError) ->
  60. error = clsiError or docUpdaterError
  61. return callback(error) if error?
  62. callback()
  63. _sendBuiltRequest: (project_id, user_id, req, options = {}, callback = (error, status, outputFiles, clsiServerId, validationProblems) ->) ->
  64. ClsiFormatChecker.checkRecoursesForProblems req.compile?.resources, (err, validationProblems)->
  65. if err?
  66. logger.err err, project_id, "could not check resources for potential problems before sending to clsi"
  67. return callback(err)
  68. if validationProblems?
  69. logger.log project_id:project_id, validationProblems:validationProblems, "problems with users latex before compile was attempted"
  70. return callback(null, "validation-problems", null, null, validationProblems)
  71. ClsiManager._postToClsi project_id, user_id, req, options.compileGroup, (error, response) ->
  72. if error?
  73. logger.err err:error, project_id:project_id, "error sending request to clsi"
  74. return callback(error)
  75. logger.log project_id: project_id, outputFilesLength: response?.outputFiles?.length, status: response?.status, compile_status: response?.compile?.status, "received compile response from CLSI"
  76. ClsiCookieManager._getServerId project_id, (err, clsiServerId)->
  77. if err?
  78. logger.err err:err, project_id:project_id, "error getting server id"
  79. return callback(err)
  80. outputFiles = ClsiManager._parseOutputFiles(project_id, response?.compile?.outputFiles)
  81. callback(null, response?.compile?.status, outputFiles, clsiServerId)
  82. _makeRequest: (project_id, opts, callback)->
  83. ClsiCookieManager.getCookieJar project_id, (err, jar)->
  84. if err?
  85. logger.err err:err, "error getting cookie jar for clsi request"
  86. return callback(err)
  87. opts.jar = jar
  88. request opts, (err, response, body)->
  89. if err?
  90. logger.err err:err, project_id:project_id, url:opts?.url, "error making request to clsi"
  91. return callback(err)
  92. ClsiCookieManager.setServerId project_id, response, (err)->
  93. if err?
  94. logger.warn err:err, project_id:project_id, "error setting server id"
  95. return callback err, response, body
  96. _getCompilerUrl: (compileGroup, project_id, user_id, action) ->
  97. host = Settings.apis.clsi.url
  98. path = "/project/#{project_id}"
  99. path += "/user/#{user_id}" if user_id?
  100. path += "/#{action}" if action?
  101. return "#{host}#{path}"
  102. _postToClsi: (project_id, user_id, req, compileGroup, callback = (error, response) ->) ->
  103. compileUrl = @_getCompilerUrl(compileGroup, project_id, user_id, "compile")
  104. opts =
  105. url: compileUrl
  106. json: req
  107. method: "POST"
  108. ClsiManager._makeRequest project_id, opts, (error, response, body) ->
  109. return callback(error) if error?
  110. if 200 <= response.statusCode < 300
  111. callback null, body
  112. else if response.statusCode == 413
  113. callback null, compile:status:"project-too-large"
  114. else if response.statusCode == 409
  115. callback null, compile:status:"conflict"
  116. else if response.statusCode == 423
  117. callback null, compile:status:"compile-in-progress"
  118. else
  119. error = new Error("CLSI returned non-success code: #{response.statusCode}")
  120. logger.error err: error, project_id: project_id, "CLSI returned failure code"
  121. callback error, body
  122. _parseOutputFiles: (project_id, rawOutputFiles = []) ->
  123. outputFiles = []
  124. for file in rawOutputFiles
  125. outputFiles.push
  126. path: file.path # the clsi is now sending this to web
  127. url: Url.parse(file.url).path # the location of the file on the clsi, excluding the host part
  128. type: file.type
  129. build: file.build
  130. return outputFiles
  131. VALID_COMPILERS: ["pdflatex", "latex", "xelatex", "lualatex"]
  132. _buildRequest: (project_id, options={}, callback = (error, request) ->) ->
  133. ProjectGetter.getProject project_id, {compiler: 1, rootDoc_id: 1, imageName: 1, rootFolder:1}, (error, project) ->
  134. return callback(error) if error?
  135. return callback(new Errors.NotFoundError("project does not exist: #{project_id}")) if !project?
  136. if project.compiler not in ClsiManager.VALID_COMPILERS
  137. project.compiler = "pdflatex"
  138. if options.incrementalCompilesEnabled or options.syncType? # new way, either incremental or full
  139. timer = new Metrics.Timer("editor.compile-getdocs-redis")
  140. ClsiManager.getContentFromDocUpdaterIfMatch project_id, project, options, (error, projectStateHash, docUpdaterDocs) ->
  141. timer.done()
  142. if error?
  143. logger.error err: error, project_id: project_id, "error checking project state"
  144. # note: we don't bail out when there's an error getting
  145. # incremental files from the docupdater, we just fall back
  146. # to a normal compile below
  147. else
  148. logger.log project_id: project_id, projectStateHash: projectStateHash, docs: docUpdaterDocs?, "checked project state"
  149. # see if we can send an incremental update to the CLSI
  150. if docUpdaterDocs? and (options.syncType isnt "full") and not error?
  151. Metrics.inc "compile-from-redis"
  152. ClsiManager._buildRequestFromDocupdater project_id, options, project, projectStateHash, docUpdaterDocs, callback
  153. else
  154. Metrics.inc "compile-from-mongo"
  155. ClsiManager._buildRequestFromMongo project_id, options, project, projectStateHash, callback
  156. else # old way, always from mongo
  157. timer = new Metrics.Timer("editor.compile-getdocs-mongo")
  158. ClsiManager._getContentFromMongo project_id, (error, docs, files) ->
  159. timer.done()
  160. return callback(error) if error?
  161. ClsiManager._finaliseRequest project_id, options, project, docs, files, callback
  162. getContentFromDocUpdaterIfMatch: (project_id, project, options, callback = (error, projectStateHash, docs) ->) ->
  163. ClsiStateManager.computeHash project, options, (error, projectStateHash) ->
  164. return callback(error) if error?
  165. DocumentUpdaterHandler.getProjectDocsIfMatch project_id, projectStateHash, (error, docs) ->
  166. return callback(error) if error?
  167. callback(null, projectStateHash, docs)
  168. getOutputFileStream: (project_id, user_id, build_id, output_file_path, callback=(err, readStream)->) ->
  169. url = "#{Settings.apis.clsi.url}/project/#{project_id}/user/#{user_id}/build/#{build_id}/output/#{output_file_path}"
  170. ClsiCookieManager.getCookieJar project_id, (err, jar)->
  171. return callback(err) if err?
  172. options = { url: url, method: "GET", timeout: 60 * 1000, jar : jar }
  173. readStream = request(options)
  174. callback(null, readStream)
  175. _buildRequestFromDocupdater: (project_id, options, project, projectStateHash, docUpdaterDocs, callback = (error, request) ->) ->
  176. ProjectEntityHandler.getAllDocPathsFromProject project, (error, docPath) ->
  177. return callback(error) if error?
  178. docs = {}
  179. for doc in docUpdaterDocs or []
  180. path = docPath[doc._id]
  181. docs[path] = doc
  182. # send new docs but not files as those are already on the clsi
  183. options = _.clone(options)
  184. options.syncType = "incremental"
  185. options.syncState = projectStateHash
  186. # create stub doc entries for any possible root docs, if not
  187. # present in the docupdater. This allows finaliseRequest to
  188. # identify the root doc.
  189. possibleRootDocIds = [options.rootDoc_id, project.rootDoc_id]
  190. for rootDoc_id in possibleRootDocIds when rootDoc_id? and rootDoc_id of docPath
  191. path = docPath[rootDoc_id]
  192. docs[path] ?= {_id: rootDoc_id, path: path}
  193. ClsiManager._finaliseRequest project_id, options, project, docs, [], callback
  194. _buildRequestFromMongo: (project_id, options, project, projectStateHash, callback = (error, request) ->) ->
  195. ClsiManager._getContentFromMongo project_id, (error, docs, files) ->
  196. return callback(error) if error?
  197. options = _.clone(options)
  198. options.syncType = "full"
  199. options.syncState = projectStateHash
  200. ClsiManager._finaliseRequest project_id, options, project, docs, files, callback
  201. _getContentFromMongo: (project_id, callback = (error, docs, files) ->) ->
  202. DocumentUpdaterHandler.flushProjectToMongo project_id, (error) ->
  203. return callback(error) if error?
  204. ProjectEntityHandler.getAllDocs project_id, (error, docs = {}) ->
  205. return callback(error) if error?
  206. ProjectEntityHandler.getAllFiles project_id, (error, files = {}) ->
  207. return callback(error) if error?
  208. callback(null, docs, files)
  209. _finaliseRequest: (project_id, options, project, docs, files, callback = (error, params) -> ) ->
  210. resources = []
  211. rootResourcePath = null
  212. rootResourcePathOverride = null
  213. hasMainFile = false
  214. numberOfDocsInProject = 0
  215. for path, doc of docs
  216. path = path.replace(/^\//, "") # Remove leading /
  217. numberOfDocsInProject++
  218. if doc.lines? # add doc to resources unless it is just a stub entry
  219. resources.push
  220. path: path
  221. content: doc.lines.join("\n")
  222. if project.rootDoc_id? and doc._id.toString() == project.rootDoc_id.toString()
  223. rootResourcePath = path
  224. if options.rootDoc_id? and doc._id.toString() == options.rootDoc_id.toString()
  225. rootResourcePathOverride = path
  226. if path is "main.tex"
  227. hasMainFile = true
  228. rootResourcePath = rootResourcePathOverride if rootResourcePathOverride?
  229. if !rootResourcePath?
  230. if hasMainFile
  231. logger.warn {project_id}, "no root document found, setting to main.tex"
  232. rootResourcePath = "main.tex"
  233. else if numberOfDocsInProject is 1 # only one file, must be the main document
  234. for path, doc of docs
  235. rootResourcePath = path.replace(/^\//, "") # Remove leading /
  236. logger.warn {project_id, rootResourcePath: rootResourcePath}, "no root document found, single document in project"
  237. else
  238. return callback new Error("no main file specified")
  239. for path, file of files
  240. path = path.replace(/^\//, "") # Remove leading /
  241. resources.push
  242. path: path
  243. url: "#{Settings.apis.filestore.url}/project/#{project._id}/file/#{file._id}"
  244. modified: file.created?.getTime()
  245. callback null, {
  246. compile:
  247. options:
  248. compiler: project.compiler
  249. timeout: options.timeout
  250. imageName: project.imageName
  251. draft: !!options.draft
  252. check: options.check
  253. syncType: options.syncType
  254. syncState: options.syncState
  255. rootResourcePath: rootResourcePath
  256. resources: resources
  257. }
  258. wordCount: (project_id, user_id, file, options, callback = (error, response) ->) ->
  259. ClsiManager._buildRequest project_id, options, (error, req) ->
  260. filename = file || req?.compile?.rootResourcePath
  261. wordcount_url = ClsiManager._getCompilerUrl(options?.compileGroup, project_id, user_id, "wordcount")
  262. opts =
  263. url: wordcount_url
  264. qs:
  265. file: filename
  266. image: req.compile.options.imageName
  267. method: "GET"
  268. ClsiManager._makeRequest project_id, opts, (error, response, body) ->
  269. return callback(error) if error?
  270. if 200 <= response.statusCode < 300
  271. callback null, body
  272. else
  273. error = new Error("CLSI returned non-success code: #{response.statusCode}")
  274. logger.error err: error, project_id: project_id, "CLSI returned failure code"
  275. callback error, body