LatexRunner.js 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. const Path = require('path')
  2. const { promisify } = require('util')
  3. const Settings = require('@overleaf/settings')
  4. const logger = require('@overleaf/logger')
  5. const CommandRunner = require('./CommandRunner')
  6. const fs = require('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. } = options
  29. const compiler = options.compiler || 'pdflatex'
  30. const timeout = options.timeout || 60000 // milliseconds
  31. logger.debug(
  32. {
  33. directory,
  34. compiler,
  35. timeout,
  36. mainFile,
  37. environment,
  38. flags,
  39. compileGroup,
  40. stopOnFirstError,
  41. },
  42. 'starting compile'
  43. )
  44. let command
  45. try {
  46. command = _buildLatexCommand(mainFile, {
  47. compiler,
  48. stopOnFirstError,
  49. flags,
  50. })
  51. } catch (err) {
  52. return callback(err)
  53. }
  54. const id = `${projectId}` // record running project under this id
  55. ProcessTable[id] = CommandRunner.run(
  56. projectId,
  57. command,
  58. directory,
  59. image,
  60. timeout,
  61. environment,
  62. compileGroup,
  63. function (error, output) {
  64. delete ProcessTable[id]
  65. if (error) {
  66. return callback(error)
  67. }
  68. const runs =
  69. output?.stderr?.match(/^Run number \d+ of .*latex/gm)?.length || 0
  70. const failed = output?.stdout?.match(/^Latexmk: Errors/m) != null ? 1 : 0
  71. // counters from latexmk output
  72. const stats = {}
  73. stats['latexmk-errors'] = failed
  74. stats['latex-runs'] = runs
  75. stats['latex-runs-with-errors'] = failed ? runs : 0
  76. stats[`latex-runs-${runs}`] = 1
  77. stats[`latex-runs-with-errors-${runs}`] = failed ? 1 : 0
  78. // timing information from /usr/bin/time
  79. const timings = {}
  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, stats, timings)
  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.writeFile(file, content, err => {
  105. if (err) {
  106. logger.error({ projectId, file }, 'error writing log file') // don't fail on error
  107. }
  108. cb()
  109. })
  110. } else {
  111. cb()
  112. }
  113. }
  114. // write stdout and stderr, ignoring errors
  115. _writeFile(Path.join(directory, 'output.stdout'), output.stdout, () => {
  116. _writeFile(Path.join(directory, 'output.stderr'), output.stderr, () => {
  117. callback()
  118. })
  119. })
  120. }
  121. function killLatex(projectId, callback) {
  122. const id = `${projectId}`
  123. logger.debug({ id }, 'killing running compile')
  124. if (ProcessTable[id] == null) {
  125. logger.warn({ id }, 'no such project to kill')
  126. callback(null)
  127. } else {
  128. CommandRunner.kill(ProcessTable[id], callback)
  129. }
  130. }
  131. function _buildLatexCommand(mainFile, opts = {}) {
  132. const command = []
  133. if (Settings.clsi?.strace) {
  134. command.push('strace', '-o', 'strace', '-ff')
  135. }
  136. if (Settings.clsi?.latexmkCommandPrefix) {
  137. command.push(...Settings.clsi.latexmkCommandPrefix)
  138. }
  139. // Basic command and flags
  140. command.push(
  141. 'latexmk',
  142. '-cd',
  143. '-jobname=output',
  144. '-auxdir=$COMPILE_DIR',
  145. '-outdir=$COMPILE_DIR',
  146. '-synctex=1',
  147. '-interaction=batchmode'
  148. )
  149. // Stop on first error option
  150. if (opts.stopOnFirstError) {
  151. command.push('-halt-on-error')
  152. } else {
  153. // Run all passes despite errors
  154. command.push('-f')
  155. }
  156. // Extra flags
  157. if (opts.flags) {
  158. command.push(...opts.flags)
  159. }
  160. // TeX Engine selection
  161. const compilerFlag = COMPILER_FLAGS[opts.compiler]
  162. if (compilerFlag) {
  163. command.push(compilerFlag)
  164. } else {
  165. throw new Error(`unknown compiler: ${opts.compiler}`)
  166. }
  167. // We want to run latexmk on the tex file which we will automatically
  168. // generate from the Rtex/Rmd/md file.
  169. mainFile = mainFile.replace(/\.(Rtex|md|Rmd)$/, '.tex')
  170. command.push(Path.join('$COMPILE_DIR', mainFile))
  171. return command
  172. }
  173. module.exports = {
  174. runLatex,
  175. killLatex,
  176. promises: {
  177. runLatex: (projectId, options) =>
  178. new Promise((resolve, reject) => {
  179. runLatex(projectId, options, (err, output, stats, timing) => {
  180. if (err) {
  181. reject(err)
  182. } else {
  183. resolve({ output, stats, timing })
  184. }
  185. })
  186. }),
  187. killLatex: promisify(killLatex),
  188. },
  189. }