LatexRunner.js 5.2 KB

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