LatexRunner.js 4.9 KB

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