LatexRunner.js 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  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. null,
  68. function (error, output) {
  69. delete ProcessTable[id]
  70. if (error) {
  71. return callback(error)
  72. }
  73. if (stats.latexmk) {
  74. try {
  75. addLatexMkMetrics(output, stats)
  76. } catch (err) {
  77. logger.error({ err, projectId }, 'error adding latexmk metrics')
  78. }
  79. }
  80. // number of latex runs and whether there were errors
  81. const runs =
  82. output?.stdout?.match(/^Run number \d+ of .*latex/gm)?.length || // TeXLive 2022 and later
  83. output?.stderr?.match(/^Run number \d+ of .*latex/gm)?.length || // TeXLive 2021 and earlier
  84. 0
  85. const failed = output?.stdout?.match(/^Latexmk: Errors/m) != null ? 1 : 0
  86. // counters from latexmk output
  87. stats['latexmk-errors'] = failed
  88. stats['latex-runs'] = runs
  89. stats['latex-runs-with-errors'] = failed ? runs : 0
  90. stats[`latex-runs-${runs}`] = 1
  91. stats[`latex-runs-with-errors-${runs}`] = failed ? 1 : 0
  92. // timing information from /usr/bin/time
  93. const stderr = (output && output.stderr) || ''
  94. if (stderr.includes('Command being timed:')) {
  95. // Add metrics for runs with `$ time -v ...`
  96. for (const [timing, matcher] of TIME_V_METRICS) {
  97. const match = stderr.match(matcher)
  98. if (match) {
  99. timings[timing] = parseFloat(match[1])
  100. }
  101. }
  102. }
  103. // record output files
  104. _writeLogOutput(projectId, directory, output, () => {
  105. callback(error, output)
  106. })
  107. }
  108. )
  109. }
  110. function _writeLogOutput(projectId, directory, output, callback) {
  111. if (!output) {
  112. return callback()
  113. }
  114. // internal method for writing non-empty log files
  115. function _writeFile(file, content, cb) {
  116. if (content && content.length > 0) {
  117. fs.unlink(file, () => {
  118. fs.writeFile(file, content, { flag: 'wx' }, err => {
  119. if (err) {
  120. // don't fail on error
  121. logger.error({ err, projectId, file }, 'error writing log file')
  122. }
  123. cb()
  124. })
  125. })
  126. } else {
  127. cb()
  128. }
  129. }
  130. // write stdout and stderr, ignoring errors
  131. _writeFile(Path.join(directory, 'output.stdout'), output.stdout, () => {
  132. _writeFile(Path.join(directory, 'output.stderr'), output.stderr, () => {
  133. callback()
  134. })
  135. })
  136. }
  137. function isRunning(projectId) {
  138. const id = `${projectId}`
  139. return ProcessTable[id] != null
  140. }
  141. function killLatex(projectId, callback) {
  142. const id = `${projectId}`
  143. logger.debug({ id }, 'killing running compile')
  144. if (!isRunning(projectId)) {
  145. logger.warn({ id }, 'no such project to kill')
  146. callback(null)
  147. } else {
  148. CommandRunner.kill(ProcessTable[id], callback)
  149. }
  150. }
  151. function _buildLatexCommand(mainFile, opts = {}) {
  152. const command = []
  153. if (Settings.clsi?.strace) {
  154. command.push('strace', '-o', 'strace', '-ff')
  155. }
  156. if (Settings.clsi?.latexmkCommandPrefix) {
  157. command.push(...Settings.clsi.latexmkCommandPrefix)
  158. }
  159. // Basic command and flags
  160. command.push(
  161. 'latexmk',
  162. '-cd',
  163. '-jobname=output',
  164. '-auxdir=$COMPILE_DIR',
  165. '-outdir=$COMPILE_DIR',
  166. '-synctex=1',
  167. '-interaction=batchmode',
  168. '-time'
  169. )
  170. // Stop on first error option
  171. if (opts.stopOnFirstError) {
  172. command.push('-halt-on-error')
  173. } else {
  174. // Run all passes despite errors
  175. command.push('-f')
  176. }
  177. // Extra flags
  178. if (opts.flags) {
  179. command.push(...opts.flags)
  180. }
  181. // TeX Engine selection
  182. const compilerFlag = COMPILER_FLAGS[opts.compiler]
  183. if (compilerFlag) {
  184. command.push(compilerFlag)
  185. } else {
  186. throw new Error(`unknown compiler: ${opts.compiler}`)
  187. }
  188. // We want to run latexmk on the tex file which we will automatically
  189. // generate from the Rtex/Rmd/md file.
  190. mainFile = mainFile.replace(/\.(Rtex|md|Rmd|Rnw)$/, '.tex')
  191. command.push(Path.join('$COMPILE_DIR', mainFile))
  192. return command
  193. }
  194. export default {
  195. isRunning,
  196. runLatex,
  197. killLatex,
  198. promises: {
  199. runLatex: promisify(runLatex),
  200. killLatex: promisify(killLatex),
  201. },
  202. }