LatexRunner.js 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. /* eslint-disable
  2. camelcase,
  3. no-return-assign,
  4. no-unused-vars,
  5. */
  6. // TODO: This file was created by bulk-decaffeinate.
  7. // Fix any style issues and re-enable lint.
  8. /*
  9. * decaffeinate suggestions:
  10. * DS102: Remove unnecessary code created because of implicit returns
  11. * DS103: Rewrite code to no longer use __guard__
  12. * DS207: Consider shorter variations of null checks
  13. * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
  14. */
  15. let LatexRunner
  16. const Path = require('path')
  17. const Settings = require('@overleaf/settings')
  18. const logger = require('logger-sharelatex')
  19. const Metrics = require('./Metrics')
  20. const CommandRunner = require('./CommandRunner')
  21. const fs = require('fs')
  22. const ProcessTable = {} // table of currently running jobs (pids or docker container names)
  23. const TIME_V_METRICS = Object.entries({
  24. 'cpu-percent': /Percent of CPU this job got: (\d+)/m,
  25. 'cpu-time': /User time.*: (\d+.\d+)/m,
  26. 'sys-time': /System time.*: (\d+.\d+)/m,
  27. })
  28. module.exports = LatexRunner = {
  29. runLatex(project_id, options, callback) {
  30. let command
  31. if (callback == null) {
  32. callback = function () {}
  33. }
  34. let {
  35. directory,
  36. mainFile,
  37. compiler,
  38. timeout,
  39. image,
  40. environment,
  41. flags,
  42. compileGroup,
  43. } = options
  44. if (!compiler) {
  45. compiler = 'pdflatex'
  46. }
  47. if (!timeout) {
  48. timeout = 60000
  49. } // milliseconds
  50. logger.log(
  51. {
  52. directory,
  53. compiler,
  54. timeout,
  55. mainFile,
  56. environment,
  57. flags,
  58. compileGroup,
  59. },
  60. 'starting compile'
  61. )
  62. // We want to run latexmk on the tex file which we will automatically
  63. // generate from the Rtex/Rmd/md file.
  64. mainFile = mainFile.replace(/\.(Rtex|md|Rmd)$/, '.tex')
  65. if (compiler === 'pdflatex') {
  66. command = LatexRunner._pdflatexCommand(mainFile, flags)
  67. } else if (compiler === 'latex') {
  68. command = LatexRunner._latexCommand(mainFile, flags)
  69. } else if (compiler === 'xelatex') {
  70. command = LatexRunner._xelatexCommand(mainFile, flags)
  71. } else if (compiler === 'lualatex') {
  72. command = LatexRunner._lualatexCommand(mainFile, flags)
  73. } else {
  74. return callback(new Error(`unknown compiler: ${compiler}`))
  75. }
  76. if (Settings.clsi != null ? Settings.clsi.strace : undefined) {
  77. command = ['strace', '-o', 'strace', '-ff'].concat(command)
  78. }
  79. const id = `${project_id}` // record running project under this id
  80. return (ProcessTable[id] = CommandRunner.run(
  81. project_id,
  82. command,
  83. directory,
  84. image,
  85. timeout,
  86. environment,
  87. compileGroup,
  88. function (error, output) {
  89. delete ProcessTable[id]
  90. if (error != null) {
  91. return callback(error)
  92. }
  93. const runs =
  94. __guard__(
  95. __guard__(output != null ? output.stderr : undefined, x1 =>
  96. x1.match(/^Run number \d+ of .*latex/gm)
  97. ),
  98. x => x.length
  99. ) || 0
  100. const failed =
  101. __guard__(output != null ? output.stdout : undefined, x2 =>
  102. x2.match(/^Latexmk: Errors/m)
  103. ) != null
  104. ? 1
  105. : 0
  106. // counters from latexmk output
  107. const stats = {}
  108. stats['latexmk-errors'] = failed
  109. stats['latex-runs'] = runs
  110. stats['latex-runs-with-errors'] = failed ? runs : 0
  111. stats[`latex-runs-${runs}`] = 1
  112. stats[`latex-runs-with-errors-${runs}`] = failed ? 1 : 0
  113. // timing information from /usr/bin/time
  114. const timings = {}
  115. const stderr = (output && output.stderr) || ''
  116. if (stderr.includes('Command being timed:')) {
  117. // Add metrics for runs with `$ time -v ...`
  118. for (const [timing, matcher] of TIME_V_METRICS) {
  119. const match = stderr.match(matcher)
  120. if (match) {
  121. timings[timing] = parseFloat(match[1])
  122. }
  123. }
  124. }
  125. // record output files
  126. LatexRunner.writeLogOutput(project_id, directory, output, () => {
  127. return callback(error, output, stats, timings)
  128. })
  129. }
  130. ))
  131. },
  132. writeLogOutput(project_id, directory, output, callback) {
  133. if (!output) {
  134. return callback()
  135. }
  136. // internal method for writing non-empty log files
  137. function _writeFile(file, content, cb) {
  138. if (content && content.length > 0) {
  139. fs.writeFile(file, content, err => {
  140. if (err) {
  141. logger.error({ project_id, file }, 'error writing log file') // don't fail on error
  142. }
  143. cb()
  144. })
  145. } else {
  146. cb()
  147. }
  148. }
  149. // write stdout and stderr, ignoring errors
  150. _writeFile(Path.join(directory, 'output.stdout'), output.stdout, () => {
  151. _writeFile(Path.join(directory, 'output.stderr'), output.stderr, () => {
  152. callback()
  153. })
  154. })
  155. },
  156. killLatex(project_id, callback) {
  157. if (callback == null) {
  158. callback = function () {}
  159. }
  160. const id = `${project_id}`
  161. logger.log({ id }, 'killing running compile')
  162. if (ProcessTable[id] == null) {
  163. logger.warn({ id }, 'no such project to kill')
  164. return callback(null)
  165. } else {
  166. return CommandRunner.kill(ProcessTable[id], callback)
  167. }
  168. },
  169. _latexmkBaseCommand(flags) {
  170. let args = [
  171. 'latexmk',
  172. '-cd',
  173. '-f',
  174. '-jobname=output',
  175. '-auxdir=$COMPILE_DIR',
  176. '-outdir=$COMPILE_DIR',
  177. '-synctex=1',
  178. '-interaction=batchmode',
  179. ]
  180. if (flags) {
  181. args = args.concat(flags)
  182. }
  183. return (
  184. __guard__(
  185. Settings != null ? Settings.clsi : undefined,
  186. x => x.latexmkCommandPrefix
  187. ) || []
  188. ).concat(args)
  189. },
  190. _pdflatexCommand(mainFile, flags) {
  191. return LatexRunner._latexmkBaseCommand(flags).concat([
  192. '-pdf',
  193. Path.join('$COMPILE_DIR', mainFile),
  194. ])
  195. },
  196. _latexCommand(mainFile, flags) {
  197. return LatexRunner._latexmkBaseCommand(flags).concat([
  198. '-pdfdvi',
  199. Path.join('$COMPILE_DIR', mainFile),
  200. ])
  201. },
  202. _xelatexCommand(mainFile, flags) {
  203. return LatexRunner._latexmkBaseCommand(flags).concat([
  204. '-xelatex',
  205. Path.join('$COMPILE_DIR', mainFile),
  206. ])
  207. },
  208. _lualatexCommand(mainFile, flags) {
  209. return LatexRunner._latexmkBaseCommand(flags).concat([
  210. '-lualatex',
  211. Path.join('$COMPILE_DIR', mainFile),
  212. ])
  213. },
  214. }
  215. function __guard__(value, transform) {
  216. return typeof value !== 'undefined' && value !== null
  217. ? transform(value)
  218. : undefined
  219. }