ClsiManager.coffee 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  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")(Settings.apis.clsi?.backendGroupName)
  11. NewBackendCloudClsiCookieManager = require("./ClsiCookieManager")(Settings.apis.clsi_new?.backendGroupName)
  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. Metrics.inc "compile.currentBackend.response.#{response?.statusCode}"
  96. if err?
  97. logger.err err:err, project_id:project_id, url:opts?.url, "error making request to clsi"
  98. return callback(err)
  99. ClsiCookieManager.setServerId project_id, response, (err)->
  100. if err?
  101. logger.warn err:err, project_id:project_id, "error setting server id"
  102. callback err, response, body #return as soon as the standard compile has returned
  103. cb(err, {response:response, body:body, finishTime:new Date() - startTime })
  104. newBackend: (cb)->
  105. startTime = new Date()
  106. ClsiManager._makeNewBackendRequest project_id, opts, (err, response, body)->
  107. Metrics.inc "compile.newBackend.response.#{response?.statusCode}"
  108. cb(err, {response:response, body:body, finishTime:new Date() - startTime})
  109. }, (err, results)->
  110. timeDifference = results.newBackend?.finishTime - results.currentBackend?.finishTime
  111. statusCodeSame = results.newBackend?.response?.statusCode == results.currentBackend?.response?.statusCode
  112. currentCompileTime = results.currentBackend?.finishTime
  113. newBackendCompileTime = results.newBackend?.finishTime
  114. logger.log {statusCodeSame, timeDifference, currentCompileTime, newBackendCompileTime, project_id}, "both clsi requests returned"
  115. _makeNewBackendRequest: (project_id, baseOpts, callback)->
  116. if !Settings.apis.clsi_new?.url?
  117. return callback()
  118. opts = _.clone(baseOpts)
  119. opts.url = opts.url.replace(Settings.apis.clsi.url, Settings.apis.clsi_new?.url)
  120. NewBackendCloudClsiCookieManager.getCookieJar project_id, (err, jar)->
  121. if err?
  122. logger.err err:err, "error getting cookie jar for clsi request"
  123. return callback(err)
  124. opts.jar = jar
  125. timer = new Metrics.Timer("compile.newBackend")
  126. request opts, (err, response, body)->
  127. timer.done()
  128. if err?
  129. logger.warn err:err, project_id:project_id, url:opts?.url, "error making request to new clsi"
  130. return callback(err)
  131. NewBackendCloudClsiCookieManager.setServerId project_id, response, (err)->
  132. if err?
  133. logger.warn err:err, project_id:project_id, "error setting server id new backend"
  134. return callback err, response, body
  135. _getCompilerUrl: (compileGroup, project_id, user_id, action) ->
  136. host = Settings.apis.clsi.url
  137. path = "/project/#{project_id}"
  138. path += "/user/#{user_id}" if user_id?
  139. path += "/#{action}" if action?
  140. return "#{host}#{path}"
  141. _postToClsi: (project_id, user_id, req, compileGroup, callback = (error, response) ->) ->
  142. compileUrl = @_getCompilerUrl(compileGroup, project_id, user_id, "compile")
  143. opts =
  144. url: compileUrl
  145. json: req
  146. method: "POST"
  147. ClsiManager._makeRequest project_id, opts, (error, response, body) ->
  148. return callback(error) if error?
  149. if 200 <= response.statusCode < 300
  150. callback null, body
  151. else if response.statusCode == 413
  152. callback null, compile:status:"project-too-large"
  153. else if response.statusCode == 409
  154. callback null, compile:status:"conflict"
  155. else if response.statusCode == 423
  156. callback null, compile:status:"compile-in-progress"
  157. else
  158. error = new Error("CLSI returned non-success code: #{response.statusCode}")
  159. logger.error err: error, project_id: project_id, "CLSI returned failure code"
  160. callback error, body
  161. _parseOutputFiles: (project_id, rawOutputFiles = []) ->
  162. outputFiles = []
  163. for file in rawOutputFiles
  164. outputFiles.push
  165. path: file.path # the clsi is now sending this to web
  166. url: Url.parse(file.url).path # the location of the file on the clsi, excluding the host part
  167. type: file.type
  168. build: file.build
  169. return outputFiles
  170. VALID_COMPILERS: ["pdflatex", "latex", "xelatex", "lualatex"]
  171. _buildRequest: (project_id, options={}, callback = (error, request) ->) ->
  172. ProjectGetter.getProject project_id, {compiler: 1, rootDoc_id: 1, imageName: 1, rootFolder:1}, (error, project) ->
  173. return callback(error) if error?
  174. return callback(new Errors.NotFoundError("project does not exist: #{project_id}")) if !project?
  175. if project.compiler not in ClsiManager.VALID_COMPILERS
  176. project.compiler = "pdflatex"
  177. if options.incrementalCompilesEnabled or options.syncType? # new way, either incremental or full
  178. timer = new Metrics.Timer("editor.compile-getdocs-redis")
  179. ClsiManager.getContentFromDocUpdaterIfMatch project_id, project, options, (error, projectStateHash, docUpdaterDocs) ->
  180. timer.done()
  181. if error?
  182. logger.error err: error, project_id: project_id, "error checking project state"
  183. # note: we don't bail out when there's an error getting
  184. # incremental files from the docupdater, we just fall back
  185. # to a normal compile below
  186. else
  187. logger.log project_id: project_id, projectStateHash: projectStateHash, docs: docUpdaterDocs?, "checked project state"
  188. # see if we can send an incremental update to the CLSI
  189. if docUpdaterDocs? and (options.syncType isnt "full") and not error?
  190. Metrics.inc "compile-from-redis"
  191. ClsiManager._buildRequestFromDocupdater project_id, options, project, projectStateHash, docUpdaterDocs, callback
  192. else
  193. Metrics.inc "compile-from-mongo"
  194. ClsiManager._buildRequestFromMongo project_id, options, project, projectStateHash, callback
  195. else # old way, always from mongo
  196. timer = new Metrics.Timer("editor.compile-getdocs-mongo")
  197. ClsiManager._getContentFromMongo project_id, (error, docs, files) ->
  198. timer.done()
  199. return callback(error) if error?
  200. ClsiManager._finaliseRequest project_id, options, project, docs, files, callback
  201. getContentFromDocUpdaterIfMatch: (project_id, project, options, callback = (error, projectStateHash, docs) ->) ->
  202. ClsiStateManager.computeHash project, options, (error, projectStateHash) ->
  203. return callback(error) if error?
  204. DocumentUpdaterHandler.getProjectDocsIfMatch project_id, projectStateHash, (error, docs) ->
  205. return callback(error) if error?
  206. callback(null, projectStateHash, docs)
  207. getOutputFileStream: (project_id, user_id, build_id, output_file_path, callback=(err, readStream)->) ->
  208. url = "#{Settings.apis.clsi.url}/project/#{project_id}/user/#{user_id}/build/#{build_id}/output/#{output_file_path}"
  209. ClsiCookieManager.getCookieJar project_id, (err, jar)->
  210. return callback(err) if err?
  211. options = { url: url, method: "GET", timeout: 60 * 1000, jar : jar }
  212. readStream = request(options)
  213. callback(null, readStream)
  214. _buildRequestFromDocupdater: (project_id, options, project, projectStateHash, docUpdaterDocs, callback = (error, request) ->) ->
  215. ProjectEntityHandler.getAllDocPathsFromProject project, (error, docPath) ->
  216. return callback(error) if error?
  217. docs = {}
  218. for doc in docUpdaterDocs or []
  219. path = docPath[doc._id]
  220. docs[path] = doc
  221. # send new docs but not files as those are already on the clsi
  222. options = _.clone(options)
  223. options.syncType = "incremental"
  224. options.syncState = projectStateHash
  225. # create stub doc entries for any possible root docs, if not
  226. # present in the docupdater. This allows finaliseRequest to
  227. # identify the root doc.
  228. possibleRootDocIds = [options.rootDoc_id, project.rootDoc_id]
  229. for rootDoc_id in possibleRootDocIds when rootDoc_id? and rootDoc_id of docPath
  230. path = docPath[rootDoc_id]
  231. docs[path] ?= {_id: rootDoc_id, path: path}
  232. ClsiManager._finaliseRequest project_id, options, project, docs, [], callback
  233. _buildRequestFromMongo: (project_id, options, project, projectStateHash, callback = (error, request) ->) ->
  234. ClsiManager._getContentFromMongo project_id, (error, docs, files) ->
  235. return callback(error) if error?
  236. options = _.clone(options)
  237. options.syncType = "full"
  238. options.syncState = projectStateHash
  239. ClsiManager._finaliseRequest project_id, options, project, docs, files, callback
  240. _getContentFromMongo: (project_id, callback = (error, docs, files) ->) ->
  241. DocumentUpdaterHandler.flushProjectToMongo project_id, (error) ->
  242. return callback(error) if error?
  243. ProjectEntityHandler.getAllDocs project_id, (error, docs = {}) ->
  244. return callback(error) if error?
  245. ProjectEntityHandler.getAllFiles project_id, (error, files = {}) ->
  246. return callback(error) if error?
  247. callback(null, docs, files)
  248. _finaliseRequest: (project_id, options, project, docs, files, callback = (error, params) -> ) ->
  249. resources = []
  250. rootResourcePath = null
  251. rootResourcePathOverride = null
  252. hasMainFile = false
  253. numberOfDocsInProject = 0
  254. for path, doc of docs
  255. path = path.replace(/^\//, "") # Remove leading /
  256. numberOfDocsInProject++
  257. if doc.lines? # add doc to resources unless it is just a stub entry
  258. resources.push
  259. path: path
  260. content: doc.lines.join("\n")
  261. if project.rootDoc_id? and doc._id.toString() == project.rootDoc_id.toString()
  262. rootResourcePath = path
  263. if options.rootDoc_id? and doc._id.toString() == options.rootDoc_id.toString()
  264. rootResourcePathOverride = path
  265. if path is "main.tex"
  266. hasMainFile = true
  267. rootResourcePath = rootResourcePathOverride if rootResourcePathOverride?
  268. if !rootResourcePath?
  269. if hasMainFile
  270. logger.warn {project_id}, "no root document found, setting to main.tex"
  271. rootResourcePath = "main.tex"
  272. else if numberOfDocsInProject is 1 # only one file, must be the main document
  273. for path, doc of docs
  274. rootResourcePath = path.replace(/^\//, "") # Remove leading /
  275. logger.warn {project_id, rootResourcePath: rootResourcePath}, "no root document found, single document in project"
  276. else
  277. return callback new Error("no main file specified")
  278. for path, file of files
  279. path = path.replace(/^\//, "") # Remove leading /
  280. resources.push
  281. path: path
  282. url: "#{Settings.apis.filestore.url}/project/#{project._id}/file/#{file._id}"
  283. modified: file.created?.getTime()
  284. callback null, {
  285. compile:
  286. options:
  287. compiler: project.compiler
  288. timeout: options.timeout
  289. imageName: project.imageName
  290. draft: !!options.draft
  291. check: options.check
  292. syncType: options.syncType
  293. syncState: options.syncState
  294. rootResourcePath: rootResourcePath
  295. resources: resources
  296. }
  297. wordCount: (project_id, user_id, file, options, callback = (error, response) ->) ->
  298. ClsiManager._buildRequest project_id, options, (error, req) ->
  299. filename = file || req?.compile?.rootResourcePath
  300. wordcount_url = ClsiManager._getCompilerUrl(options?.compileGroup, project_id, user_id, "wordcount")
  301. opts =
  302. url: wordcount_url
  303. qs:
  304. file: filename
  305. image: req.compile.options.imageName
  306. method: "GET"
  307. ClsiManager._makeRequest project_id, opts, (error, response, body) ->
  308. return callback(error) if error?
  309. if 200 <= response.statusCode < 300
  310. callback null, body
  311. else
  312. error = new Error("CLSI returned non-success code: #{response.statusCode}")
  313. logger.error err: error, project_id: project_id, "CLSI returned failure code"
  314. callback error, body