LatexRunner.js 5.5 KB

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