LatexRunner.js 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. const Path = require('path')
  2. const Settings = require('@overleaf/settings')
  3. const logger = require('@overleaf/logger')
  4. const CommandRunner = require('./CommandRunner')
  5. const fs = require('fs')
  6. const ProcessTable = {} // table of currently running jobs (pids or docker container names)
  7. const TIME_V_METRICS = Object.entries({
  8. 'cpu-percent': /Percent of CPU this job got: (\d+)/m,
  9. 'cpu-time': /User time.*: (\d+.\d+)/m,
  10. 'sys-time': /System time.*: (\d+.\d+)/m,
  11. })
  12. const COMPILER_FLAGS = {
  13. latex: '-pdfdvi',
  14. lualatex: '-lualatex',
  15. pdflatex: '-pdf',
  16. xelatex: '-xelatex',
  17. }
  18. function runLatex(projectId, options, callback) {
  19. const {
  20. directory,
  21. mainFile,
  22. image,
  23. environment,
  24. flags,
  25. compileGroup,
  26. stopOnFirstError,
  27. } = options
  28. const compiler = options.compiler || 'pdflatex'
  29. const timeout = options.timeout || 60000 // milliseconds
  30. logger.debug(
  31. {
  32. directory,
  33. compiler,
  34. timeout,
  35. mainFile,
  36. environment,
  37. flags,
  38. compileGroup,
  39. stopOnFirstError,
  40. },
  41. 'starting compile'
  42. )
  43. let command
  44. try {
  45. command = _buildLatexCommand(mainFile, {
  46. compiler,
  47. stopOnFirstError,
  48. flags,
  49. })
  50. } catch (err) {
  51. return callback(err)
  52. }
  53. const id = `${projectId}` // record running project under this id
  54. ProcessTable[id] = CommandRunner.run(
  55. projectId,
  56. command,
  57. directory,
  58. image,
  59. timeout,
  60. environment,
  61. compileGroup,
  62. function (error, output) {
  63. delete ProcessTable[id]
  64. if (error) {
  65. return callback(error)
  66. }
  67. const runs =
  68. output?.stderr?.match(/^Run number \d+ of .*latex/gm)?.length || 0
  69. const failed = output?.stdout?.match(/^Latexmk: Errors/m) != null ? 1 : 0
  70. // counters from latexmk output
  71. const stats = {}
  72. stats['latexmk-errors'] = failed
  73. stats['latex-runs'] = runs
  74. stats['latex-runs-with-errors'] = failed ? runs : 0
  75. stats[`latex-runs-${runs}`] = 1
  76. stats[`latex-runs-with-errors-${runs}`] = failed ? 1 : 0
  77. // timing information from /usr/bin/time
  78. const timings = {}
  79. const stderr = (output && output.stderr) || ''
  80. if (stderr.includes('Command being timed:')) {
  81. // Add metrics for runs with `$ time -v ...`
  82. for (const [timing, matcher] of TIME_V_METRICS) {
  83. const match = stderr.match(matcher)
  84. if (match) {
  85. timings[timing] = parseFloat(match[1])
  86. }
  87. }
  88. }
  89. // record output files
  90. _writeLogOutput(projectId, directory, output, () => {
  91. callback(error, output, stats, timings)
  92. })
  93. }
  94. )
  95. }
  96. function _writeLogOutput(projectId, directory, output, callback) {
  97. if (!output) {
  98. return callback()
  99. }
  100. // internal method for writing non-empty log files
  101. function _writeFile(file, content, cb) {
  102. if (content && content.length > 0) {
  103. fs.writeFile(file, content, err => {
  104. if (err) {
  105. logger.error({ projectId, file }, 'error writing log file') // don't fail on error
  106. }
  107. cb()
  108. })
  109. } else {
  110. cb()
  111. }
  112. }
  113. // write stdout and stderr, ignoring errors
  114. _writeFile(Path.join(directory, 'output.stdout'), output.stdout, () => {
  115. _writeFile(Path.join(directory, 'output.stderr'), output.stderr, () => {
  116. callback()
  117. })
  118. })
  119. }
  120. function killLatex(projectId, callback) {
  121. const id = `${projectId}`
  122. logger.debug({ id }, 'killing running compile')
  123. if (ProcessTable[id] == null) {
  124. logger.warn({ id }, 'no such project to kill')
  125. callback(null)
  126. } else {
  127. CommandRunner.kill(ProcessTable[id], callback)
  128. }
  129. }
  130. function _buildLatexCommand(mainFile, opts = {}) {
  131. const command = []
  132. if (Settings.clsi?.strace) {
  133. command.push('strace', '-o', 'strace', '-ff')
  134. }
  135. if (Settings.clsi?.latexmkCommandPrefix) {
  136. command.push(...Settings.clsi.latexmkCommandPrefix)
  137. }
  138. // Basic command and flags
  139. command.push(
  140. 'latexmk',
  141. '-cd',
  142. '-jobname=output',
  143. '-auxdir=$COMPILE_DIR',
  144. '-outdir=$COMPILE_DIR',
  145. '-synctex=1',
  146. '-interaction=batchmode'
  147. )
  148. // Stop on first error option
  149. if (opts.stopOnFirstError) {
  150. command.push('-halt-on-error')
  151. } else {
  152. // Run all passes despite errors
  153. command.push('-f')
  154. }
  155. // Extra flags
  156. if (opts.flags) {
  157. command.push(...opts.flags)
  158. }
  159. // TeX Engine selection
  160. const compilerFlag = COMPILER_FLAGS[opts.compiler]
  161. if (compilerFlag) {
  162. command.push(compilerFlag)
  163. } else {
  164. throw new Error(`unknown compiler: ${opts.compiler}`)
  165. }
  166. // We want to run latexmk on the tex file which we will automatically
  167. // generate from the Rtex/Rmd/md file.
  168. mainFile = mainFile.replace(/\.(Rtex|md|Rmd)$/, '.tex')
  169. command.push(Path.join('$COMPILE_DIR', mainFile))
  170. return command
  171. }
  172. module.exports = {
  173. runLatex,
  174. killLatex,
  175. }