LatexRunner.js 5.2 KB

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