CompileManager.coffee 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. ResourceWriter = require "./ResourceWriter"
  2. LatexRunner = require "./LatexRunner"
  3. OutputFileFinder = require "./OutputFileFinder"
  4. OutputCacheManager = require "./OutputCacheManager"
  5. Settings = require("settings-sharelatex")
  6. Path = require "path"
  7. logger = require "logger-sharelatex"
  8. Metrics = require "./Metrics"
  9. child_process = require "child_process"
  10. DraftModeManager = require "./DraftModeManager"
  11. fs = require("fs")
  12. fse = require "fs-extra"
  13. os = require("os")
  14. async = require "async"
  15. commandRunner = Settings.clsi?.commandRunner or "./CommandRunner"
  16. logger.info commandRunner:commandRunner, "selecting command runner for clsi"
  17. CommandRunner = require(commandRunner)
  18. getCompileName = (project_id, user_id) ->
  19. if user_id? then "#{project_id}-#{user_id}" else project_id
  20. getCompileDir = (project_id, user_id) ->
  21. Path.join(Settings.path.compilesDir, getCompileName(project_id, user_id))
  22. module.exports = CompileManager =
  23. doCompile: (request, callback = (error, outputFiles) ->) ->
  24. compileDir = getCompileDir(request.project_id, request.user_id)
  25. timer = new Metrics.Timer("write-to-disk")
  26. logger.log project_id: request.project_id, user_id: request.user_id, "starting compile"
  27. ResourceWriter.syncResourcesToDisk request.project_id, request.resources, compileDir, (error) ->
  28. if error?
  29. logger.err err:error, project_id: request.project_id, user_id: request.user_id, "error writing resources to disk"
  30. return callback(error)
  31. logger.log project_id: request.project_id, user_id: request.user_id, time_taken: Date.now() - timer.start, "written files to disk"
  32. timer.done()
  33. injectDraftModeIfRequired = (callback) ->
  34. if request.draft
  35. DraftModeManager.injectDraftMode Path.join(compileDir, request.rootResourcePath), callback
  36. else
  37. callback()
  38. injectDraftModeIfRequired (error) ->
  39. return callback(error) if error?
  40. timer = new Metrics.Timer("run-compile")
  41. # find the image tag to log it as a metric, e.g. 2015.1 (convert . to - for graphite)
  42. tag = request.imageName?.match(/:(.*)/)?[1]?.replace(/\./g,'-') or "default"
  43. tag = "other" if not request.project_id.match(/^[0-9a-f]{24}$/) # exclude smoke test
  44. Metrics.inc("compiles")
  45. Metrics.inc("compiles-with-image.#{tag}")
  46. compileName = getCompileName(request.project_id, request.user_id)
  47. LatexRunner.runLatex compileName, {
  48. directory: compileDir
  49. mainFile: request.rootResourcePath
  50. compiler: request.compiler
  51. timeout: request.timeout
  52. image: request.imageName
  53. }, (error, output, stats, timings) ->
  54. return callback(error) if error?
  55. Metrics.inc("compiles-succeeded")
  56. for metric_key, metric_value of stats or {}
  57. Metrics.count(metric_key, metric_value)
  58. for metric_key, metric_value of timings or {}
  59. Metrics.timing(metric_key, metric_value)
  60. loadavg = os.loadavg?()
  61. Metrics.gauge("load-avg", loadavg[0]) if loadavg?
  62. ts = timer.done()
  63. logger.log {project_id: request.project_id, user_id: request.user_id, time_taken: ts, stats:stats, timings:timings, loadavg:loadavg}, "done compile"
  64. if stats?["latex-runs"] > 0
  65. Metrics.timing("run-compile-per-pass", ts / stats["latex-runs"])
  66. if stats?["latex-runs"] > 0 and timings?["cpu-time"] > 0
  67. Metrics.timing("run-compile-cpu-time-per-pass", timings["cpu-time"] / stats["latex-runs"])
  68. OutputFileFinder.findOutputFiles request.resources, compileDir, (error, outputFiles) ->
  69. return callback(error) if error?
  70. OutputCacheManager.saveOutputFiles outputFiles, compileDir, (error, newOutputFiles) ->
  71. callback null, newOutputFiles
  72. clearProject: (project_id, user_id, _callback = (error) ->) ->
  73. callback = (error) ->
  74. _callback(error)
  75. _callback = () ->
  76. compileDir = getCompileDir(project_id, user_id)
  77. CompileManager._checkDirectory compileDir, (err, exists) ->
  78. return callback(err) if err?
  79. return callback() if not exists # skip removal if no directory present
  80. proc = child_process.spawn "rm", ["-r", compileDir]
  81. proc.on "error", callback
  82. stderr = ""
  83. proc.stderr.on "data", (chunk) -> stderr += chunk.toString()
  84. proc.on "close", (code) ->
  85. if code == 0
  86. return callback(null)
  87. else
  88. return callback(new Error("rm -r #{compileDir} failed: #{stderr}"))
  89. _findAllDirs: (callback = (error, allDirs) ->) ->
  90. root = Settings.path.compilesDir
  91. fs.readdir root, (err, files) ->
  92. return callback(err) if err?
  93. allDirs = (Path.join(root, file) for file in files)
  94. callback(null, allDirs)
  95. clearExpiredProjects: (max_cache_age_ms, callback = (error) ->) ->
  96. now = Date.now()
  97. # action for each directory
  98. expireIfNeeded = (checkDir, cb) ->
  99. fs.stat checkDir, (err, stats) ->
  100. return cb() if err? # ignore errors checking directory
  101. age = now - stats.mtime
  102. hasExpired = (age > max_cache_age_ms)
  103. if hasExpired then fse.remove(checkDir, cb) else cb()
  104. # iterate over all project directories
  105. CompileManager._findAllDirs (error, allDirs) ->
  106. return callback() if error?
  107. async.eachSeries allDirs, expireIfNeeded, callback
  108. _checkDirectory: (compileDir, callback = (error, exists) ->) ->
  109. fs.lstat compileDir, (err, stats) ->
  110. if err?.code is 'ENOENT'
  111. return callback(null, false) # directory does not exist
  112. else if err?
  113. logger.err {dir: compileDir, err:err}, "error on stat of project directory for removal"
  114. return callback(err)
  115. else if not stats?.isDirectory()
  116. logger.err {dir: compileDir, stats:stats}, "bad project directory for removal"
  117. return callback new Error("project directory is not directory")
  118. else
  119. callback(null, true) # directory exists
  120. syncFromCode: (project_id, user_id, file_name, line, column, callback = (error, pdfPositions) ->) ->
  121. # If LaTeX was run in a virtual environment, the file path that synctex expects
  122. # might not match the file path on the host. The .synctex.gz file however, will be accessed
  123. # wherever it is on the host.
  124. compileName = getCompileName(project_id, user_id)
  125. base_dir = Settings.path.synctexBaseDir(compileName)
  126. file_path = base_dir + "/" + file_name
  127. compileDir = getCompileDir(project_id, user_id)
  128. synctex_path = Path.join(compileDir, "output.pdf")
  129. CompileManager._runSynctex ["code", synctex_path, file_path, line, column], (error, stdout) ->
  130. return callback(error) if error?
  131. logger.log project_id: project_id, user_id:user_id, file_name: file_name, line: line, column: column, stdout: stdout, "synctex code output"
  132. callback null, CompileManager._parseSynctexFromCodeOutput(stdout)
  133. syncFromPdf: (project_id, user_id, page, h, v, callback = (error, filePositions) ->) ->
  134. compileName = getCompileName(project_id, user_id)
  135. base_dir = Settings.path.synctexBaseDir(compileName)
  136. compileDir = getCompileDir(project_id, user_id)
  137. synctex_path = Path.join(compileDir, "output.pdf")
  138. CompileManager._runSynctex ["pdf", synctex_path, page, h, v], (error, stdout) ->
  139. return callback(error) if error?
  140. logger.log project_id: project_id, user_id:user_id, page: page, h: h, v:v, stdout: stdout, "synctex pdf output"
  141. callback null, CompileManager._parseSynctexFromPdfOutput(stdout, base_dir)
  142. _runSynctex: (args, callback = (error, stdout) ->) ->
  143. bin_path = Path.resolve(__dirname + "/../../bin/synctex")
  144. seconds = 1000
  145. child_process.execFile bin_path, args, timeout: 10 * seconds, (error, stdout, stderr) ->
  146. if error?
  147. logger.err err:error, args:args, "error running synctex"
  148. return callback(error)
  149. callback(null, stdout)
  150. _parseSynctexFromCodeOutput: (output) ->
  151. results = []
  152. for line in output.split("\n")
  153. [node, page, h, v, width, height] = line.split("\t")
  154. if node == "NODE"
  155. results.push {
  156. page: parseInt(page, 10)
  157. h: parseFloat(h)
  158. v: parseFloat(v)
  159. height: parseFloat(height)
  160. width: parseFloat(width)
  161. }
  162. return results
  163. _parseSynctexFromPdfOutput: (output, base_dir) ->
  164. results = []
  165. for line in output.split("\n")
  166. [node, file_path, line, column] = line.split("\t")
  167. if node == "NODE"
  168. file = file_path.slice(base_dir.length + 1)
  169. results.push {
  170. file: file
  171. line: parseInt(line, 10)
  172. column: parseInt(column, 10)
  173. }
  174. return results
  175. wordcount: (project_id, user_id, file_name, image, callback = (error, pdfPositions) ->) ->
  176. logger.log project_id:project_id, user_id:user_id, file_name:file_name, image:image, "running wordcount"
  177. file_path = "$COMPILE_DIR/" + file_name
  178. command = [ "texcount", '-inc', file_path, "-out=" + file_path + ".wc"]
  179. directory = getCompileDir(project_id, user_id)
  180. timeout = 10 * 1000
  181. compileName = getCompileName(project_id, user_id)
  182. CommandRunner.run compileName, command, directory, image, timeout, (error) ->
  183. return callback(error) if error?
  184. try
  185. stdout = fs.readFileSync(directory + "/" + file_name + ".wc", "utf-8")
  186. catch err
  187. logger.err err:err, command:command, directory:directory, project_id:project_id, user_id:user_id, "error reading word count output"
  188. return callback(err)
  189. callback null, CompileManager._parseWordcountFromOutput(stdout)
  190. _parseWordcountFromOutput: (output) ->
  191. results = {
  192. encode: ""
  193. textWords: 0
  194. headWords: 0
  195. outside: 0
  196. headers: 0
  197. elements: 0
  198. mathInline: 0
  199. mathDisplay: 0
  200. }
  201. for line in output.split("\n")
  202. [data, info] = line.split(":")
  203. if data.indexOf("Encoding") > -1
  204. results['encode'] = info.trim()
  205. if data.indexOf("in text") > -1
  206. results['textWords'] = parseInt(info, 10)
  207. if data.indexOf("in head") > -1
  208. results['headWords'] = parseInt(info, 10)
  209. if data.indexOf("outside") > -1
  210. results['outside'] = parseInt(info, 10)
  211. if data.indexOf("of head") > -1
  212. results['headers'] = parseInt(info, 10)
  213. if data.indexOf("Number of floats/tables/figures") > -1
  214. results['elements'] = parseInt(info, 10)
  215. if data.indexOf("Number of math inlines") > -1
  216. results['mathInline'] = parseInt(info, 10)
  217. if data.indexOf("Number of math displayed") > -1
  218. results['mathDisplay'] = parseInt(info, 10)
  219. return results