ClsiManager.coffee 12 KB

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