ClsiManager.coffee 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  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. _buildRequestFromDocupdater: (project_id, options, project, projectStateHash, docUpdaterDocs, callback = (error, request) ->) ->
  169. ProjectEntityHandler.getAllDocPathsFromProject project, (error, docPath) ->
  170. return callback(error) if error?
  171. docs = {}
  172. for doc in docUpdaterDocs or []
  173. path = docPath[doc._id]
  174. docs[path] = doc
  175. # send new docs but not files as those are already on the clsi
  176. options = _.clone(options)
  177. options.syncType = "incremental"
  178. options.syncState = projectStateHash
  179. # create stub doc entries for any possible root docs, if not
  180. # present in the docupdater. This allows finaliseRequest to
  181. # identify the root doc.
  182. possibleRootDocIds = [options.rootDoc_id, project.rootDoc_id]
  183. for rootDoc_id in possibleRootDocIds when rootDoc_id? and rootDoc_id of docPath
  184. path = docPath[rootDoc_id]
  185. docs[path] ?= {_id: rootDoc_id, path: path}
  186. ClsiManager._finaliseRequest project_id, options, project, docs, [], callback
  187. _buildRequestFromMongo: (project_id, options, project, projectStateHash, callback = (error, request) ->) ->
  188. ClsiManager._getContentFromMongo project_id, (error, docs, files) ->
  189. return callback(error) if error?
  190. options = _.clone(options)
  191. options.syncType = "full"
  192. options.syncState = projectStateHash
  193. ClsiManager._finaliseRequest project_id, options, project, docs, files, callback
  194. _getContentFromMongo: (project_id, callback = (error, docs, files) ->) ->
  195. DocumentUpdaterHandler.flushProjectToMongo project_id, (error) ->
  196. return callback(error) if error?
  197. ProjectEntityHandler.getAllDocs project_id, (error, docs = {}) ->
  198. return callback(error) if error?
  199. ProjectEntityHandler.getAllFiles project_id, (error, files = {}) ->
  200. return callback(error) if error?
  201. callback(null, docs, files)
  202. _finaliseRequest: (project_id, options, project, docs, files, callback = (error, params) -> ) ->
  203. resources = []
  204. rootResourcePath = null
  205. rootResourcePathOverride = null
  206. hasMainFile = false
  207. numberOfDocsInProject = 0
  208. for path, doc of docs
  209. path = path.replace(/^\//, "") # Remove leading /
  210. numberOfDocsInProject++
  211. if doc.lines? # add doc to resources unless it is just a stub entry
  212. resources.push
  213. path: path
  214. content: doc.lines.join("\n")
  215. if project.rootDoc_id? and doc._id.toString() == project.rootDoc_id.toString()
  216. rootResourcePath = path
  217. if options.rootDoc_id? and doc._id.toString() == options.rootDoc_id.toString()
  218. rootResourcePathOverride = path
  219. if path is "main.tex"
  220. hasMainFile = true
  221. rootResourcePath = rootResourcePathOverride if rootResourcePathOverride?
  222. if !rootResourcePath?
  223. if hasMainFile
  224. logger.warn {project_id}, "no root document found, setting to main.tex"
  225. rootResourcePath = "main.tex"
  226. else if numberOfDocsInProject is 1 # only one file, must be the main document
  227. for path, doc of docs
  228. rootResourcePath = path.replace(/^\//, "") # Remove leading /
  229. logger.warn {project_id, rootResourcePath: rootResourcePath}, "no root document found, single document in project"
  230. else
  231. return callback new Error("no main file specified")
  232. for path, file of files
  233. path = path.replace(/^\//, "") # Remove leading /
  234. resources.push
  235. path: path
  236. url: "#{Settings.apis.filestore.url}/project/#{project._id}/file/#{file._id}"
  237. modified: file.created?.getTime()
  238. callback null, {
  239. compile:
  240. options:
  241. compiler: project.compiler
  242. timeout: options.timeout
  243. imageName: project.imageName
  244. draft: !!options.draft
  245. check: options.check
  246. syncType: options.syncType
  247. syncState: options.syncState
  248. rootResourcePath: rootResourcePath
  249. resources: resources
  250. }
  251. wordCount: (project_id, user_id, file, options, callback = (error, response) ->) ->
  252. ClsiManager._buildRequest project_id, options, (error, req) ->
  253. filename = file || req?.compile?.rootResourcePath
  254. wordcount_url = ClsiManager._getCompilerUrl(options?.compileGroup, project_id, user_id, "wordcount")
  255. opts =
  256. url: wordcount_url
  257. qs:
  258. file: filename
  259. image: req.compile.options.imageName
  260. method: "GET"
  261. ClsiManager._makeRequest project_id, opts, (error, response, body) ->
  262. return callback(error) if error?
  263. if 200 <= response.statusCode < 300
  264. callback null, body
  265. else
  266. error = new Error("CLSI returned non-success code: #{response.statusCode}")
  267. logger.error err: error, project_id: project_id, "CLSI returned failure code"
  268. callback error, body