ClsiManager.coffee 12 KB

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