ClsiManager.coffee 15 KB

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