CompileManager.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627
  1. const childProcess = require('child_process')
  2. const fsPromises = require('fs/promises')
  3. const os = require('os')
  4. const Path = require('path')
  5. const { callbackify, promisify } = require('util')
  6. const Settings = require('@overleaf/settings')
  7. const logger = require('@overleaf/logger')
  8. const OError = require('@overleaf/o-error')
  9. const ResourceWriter = require('./ResourceWriter')
  10. const LatexRunner = require('./LatexRunner')
  11. const OutputFileFinder = require('./OutputFileFinder')
  12. const OutputCacheManager = require('./OutputCacheManager')
  13. const Metrics = require('./Metrics')
  14. const DraftModeManager = require('./DraftModeManager')
  15. const TikzManager = require('./TikzManager')
  16. const LockManager = require('./LockManager')
  17. const Errors = require('./Errors')
  18. const CommandRunner = require('./CommandRunner')
  19. const { emitPdfStats } = require('./ContentCacheMetrics')
  20. const SynctexOutputParser = require('./SynctexOutputParser')
  21. const execFile = promisify(childProcess.execFile)
  22. const COMPILE_TIME_BUCKETS = [
  23. // NOTE: These buckets are locked in per metric name.
  24. // If you want to change them, you will need to rename metrics.
  25. 0, 1, 2, 3, 4, 6, 8, 11, 15, 22, 31, 43, 61, 86, 121, 170, 240,
  26. ].map(seconds => seconds * 1000)
  27. function getCompileName(projectId, userId) {
  28. if (userId != null) {
  29. return `${projectId}-${userId}`
  30. } else {
  31. return projectId
  32. }
  33. }
  34. function getCompileDir(projectId, userId) {
  35. return Path.join(Settings.path.compilesDir, getCompileName(projectId, userId))
  36. }
  37. function getOutputDir(projectId, userId) {
  38. return Path.join(Settings.path.outputDir, getCompileName(projectId, userId))
  39. }
  40. async function doCompileWithLock(request) {
  41. const compileDir = getCompileDir(request.project_id, request.user_id)
  42. // use a .project-lock file in the compile directory to prevent
  43. // simultaneous compiles
  44. const lockFile = Path.join(compileDir, '.project-lock')
  45. await fsPromises.mkdir(compileDir, { recursive: true })
  46. const lock = await LockManager.acquire(lockFile)
  47. try {
  48. return await doCompile(request)
  49. } finally {
  50. await lock.release()
  51. }
  52. }
  53. async function doCompile(request) {
  54. const compileDir = getCompileDir(request.project_id, request.user_id)
  55. const stats = {}
  56. const timings = {}
  57. const timerE2E = new Metrics.Timer(
  58. 'compile-e2e-v2',
  59. 1,
  60. request.metricsOpts,
  61. COMPILE_TIME_BUCKETS
  62. )
  63. const writeToDiskTimer = new Metrics.Timer(
  64. 'write-to-disk',
  65. 1,
  66. request.metricsOpts
  67. )
  68. logger.debug(
  69. { projectId: request.project_id, userId: request.user_id },
  70. 'syncing resources to disk'
  71. )
  72. let resourceList
  73. try {
  74. // NOTE: resourceList is insecure, it should only be used to exclude files from the output list
  75. resourceList = await ResourceWriter.promises.syncResourcesToDisk(
  76. request,
  77. compileDir
  78. )
  79. } catch (error) {
  80. if (error instanceof Errors.FilesOutOfSyncError) {
  81. OError.tag(error, 'files out of sync, please retry', {
  82. projectId: request.project_id,
  83. userId: request.user_id,
  84. })
  85. } else {
  86. OError.tag(error, 'error writing resources to disk', {
  87. projectId: request.project_id,
  88. userId: request.user_id,
  89. })
  90. }
  91. throw error
  92. }
  93. logger.debug(
  94. {
  95. projectId: request.project_id,
  96. userId: request.user_id,
  97. timeTaken: Date.now() - writeToDiskTimer.start,
  98. },
  99. 'written files to disk'
  100. )
  101. timings.sync = writeToDiskTimer.done()
  102. // set up environment variables for chktex
  103. const env = {}
  104. if (Settings.texliveOpenoutAny && Settings.texliveOpenoutAny !== '') {
  105. // override default texlive openout_any environment variable
  106. env.openout_any = Settings.texliveOpenoutAny
  107. }
  108. if (Settings.texliveMaxPrintLine && Settings.texliveMaxPrintLine !== '') {
  109. // override default texlive max_print_line environment variable
  110. env.max_print_line = Settings.texliveMaxPrintLine
  111. }
  112. // only run chktex on LaTeX files (not knitr .Rtex files or any others)
  113. const isLaTeXFile = request.rootResourcePath?.match(/\.tex$/i)
  114. if (request.check != null && isLaTeXFile) {
  115. env.CHKTEX_OPTIONS = '-nall -e9 -e10 -w15 -w16'
  116. env.CHKTEX_ULIMIT_OPTIONS = '-t 5 -v 64000'
  117. if (request.check === 'error') {
  118. env.CHKTEX_EXIT_ON_ERROR = 1
  119. }
  120. if (request.check === 'validate') {
  121. env.CHKTEX_VALIDATE = 1
  122. }
  123. }
  124. // apply a series of file modifications/creations for draft mode and tikz
  125. if (request.draft) {
  126. await DraftModeManager.promises.injectDraftMode(
  127. Path.join(compileDir, request.rootResourcePath)
  128. )
  129. }
  130. const needsMainFile = await TikzManager.promises.checkMainFile(
  131. compileDir,
  132. request.rootResourcePath,
  133. resourceList
  134. )
  135. if (needsMainFile) {
  136. await TikzManager.promises.injectOutputFile(
  137. compileDir,
  138. request.rootResourcePath
  139. )
  140. }
  141. const compileTimer = new Metrics.Timer('run-compile', 1, request.metricsOpts)
  142. // find the image tag to log it as a metric, e.g. 2015.1 (convert . to - for graphite)
  143. let tag = 'default'
  144. if (request.imageName != null) {
  145. const match = request.imageName.match(/:(.*)/)
  146. if (match != null) {
  147. tag = match[1].replace(/\./g, '-')
  148. }
  149. }
  150. // exclude smoke test
  151. if (!request.project_id.match(/^[0-9a-f]{24}$/)) {
  152. tag = 'other'
  153. }
  154. Metrics.inc('compiles', 1, request.metricsOpts)
  155. Metrics.inc(`compiles-with-image.${tag}`, 1, request.metricsOpts)
  156. const compileName = getCompileName(request.project_id, request.user_id)
  157. try {
  158. await LatexRunner.promises.runLatex(compileName, {
  159. directory: compileDir,
  160. mainFile: request.rootResourcePath,
  161. compiler: request.compiler,
  162. timeout: request.timeout,
  163. image: request.imageName,
  164. flags: request.flags,
  165. environment: env,
  166. compileGroup: request.compileGroup,
  167. stopOnFirstError: request.stopOnFirstError,
  168. stats,
  169. timings,
  170. })
  171. // We use errors to return the validation state. It would be nice to use a
  172. // more appropriate mechanism.
  173. if (request.check === 'validate') {
  174. const validationError = new Error('validation')
  175. validationError.validate = 'pass'
  176. throw validationError
  177. }
  178. } catch (originalError) {
  179. let error = originalError
  180. // request was for validation only
  181. if (request.check === 'validate' && !error.validate) {
  182. error = new Error('validation')
  183. error.validate = originalError.code ? 'fail' : 'pass'
  184. }
  185. // request was for compile, and failed on validation
  186. if (request.check === 'error' && originalError.message === 'exited') {
  187. error = new Error('compilation')
  188. error.validate = 'fail'
  189. }
  190. // record timeout errors as a separate counter, success is recorded later
  191. if (error.timedout) {
  192. Metrics.inc('compiles-timeout', 1, request.metricsOpts)
  193. }
  194. const outputFiles = await _saveOutputFiles({
  195. request,
  196. compileDir,
  197. resourceList,
  198. stats,
  199. timings,
  200. })
  201. error.outputFiles = outputFiles // return output files so user can check logs
  202. // Clear project if this compile was abruptly terminated
  203. if (error.terminated || error.timedout) {
  204. await clearProject(request.project_id, request.user_id)
  205. }
  206. throw error
  207. }
  208. // compile completed normally
  209. Metrics.inc('compiles-succeeded', 1, request.metricsOpts)
  210. for (const metricKey in stats) {
  211. const metricValue = stats[metricKey]
  212. Metrics.count(metricKey, metricValue, 1, request.metricsOpts)
  213. }
  214. for (const metricKey in timings) {
  215. const metricValue = timings[metricKey]
  216. Metrics.timing(metricKey, metricValue, 1, request.metricsOpts)
  217. }
  218. const loadavg = typeof os.loadavg === 'function' ? os.loadavg() : undefined
  219. if (loadavg != null) {
  220. Metrics.gauge('load-avg', loadavg[0])
  221. }
  222. const ts = compileTimer.done()
  223. logger.debug(
  224. {
  225. projectId: request.project_id,
  226. userId: request.user_id,
  227. timeTaken: ts,
  228. stats,
  229. timings,
  230. loadavg,
  231. },
  232. 'done compile'
  233. )
  234. if (stats['latex-runs'] > 0) {
  235. Metrics.histogram(
  236. 'avg-compile-per-pass-v2',
  237. ts / stats['latex-runs'],
  238. COMPILE_TIME_BUCKETS,
  239. request.metricsOpts
  240. )
  241. Metrics.timing(
  242. 'avg-compile-per-pass-v2',
  243. ts / stats['latex-runs'],
  244. 1,
  245. request.metricsOpts
  246. )
  247. }
  248. if (stats['latex-runs'] > 0 && timings['cpu-time'] > 0) {
  249. Metrics.timing(
  250. 'run-compile-cpu-time-per-pass',
  251. timings['cpu-time'] / stats['latex-runs'],
  252. 1,
  253. request.metricsOpts
  254. )
  255. }
  256. // Emit compile time.
  257. timings.compile = ts
  258. const outputFiles = await _saveOutputFiles({
  259. request,
  260. compileDir,
  261. resourceList,
  262. stats,
  263. timings,
  264. })
  265. // Emit e2e compile time.
  266. timings.compileE2E = timerE2E.done()
  267. Metrics.timing('compile-e2e-v2', timings.compileE2E, 1, request.metricsOpts)
  268. if (stats['pdf-size']) {
  269. emitPdfStats(stats, timings, request)
  270. }
  271. return { outputFiles, stats, timings }
  272. }
  273. async function _saveOutputFiles({
  274. request,
  275. compileDir,
  276. resourceList,
  277. stats,
  278. timings,
  279. }) {
  280. const timer = new Metrics.Timer(
  281. 'process-output-files',
  282. 1,
  283. request.metricsOpts
  284. )
  285. const outputDir = getOutputDir(request.project_id, request.user_id)
  286. let { outputFiles } = await OutputFileFinder.promises.findOutputFiles(
  287. resourceList,
  288. compileDir
  289. )
  290. try {
  291. outputFiles = await OutputCacheManager.promises.saveOutputFiles(
  292. { request, stats, timings },
  293. outputFiles,
  294. compileDir,
  295. outputDir
  296. )
  297. } catch (err) {
  298. const { project_id: projectId, user_id: userId } = request
  299. logger.err({ projectId, userId, err }, 'failed to save output files')
  300. }
  301. timings.output = timer.done()
  302. return outputFiles
  303. }
  304. async function stopCompile(projectId, userId) {
  305. const compileName = getCompileName(projectId, userId)
  306. await LatexRunner.promises.killLatex(compileName)
  307. }
  308. async function clearProject(projectId, userId) {
  309. const compileDir = getCompileDir(projectId, userId)
  310. const exists = await _checkDirectory(compileDir)
  311. if (!exists) {
  312. // skip removal if no directory present
  313. return
  314. }
  315. try {
  316. await execFile('rm', ['-r', '-f', '--', compileDir])
  317. } catch (err) {
  318. OError.tag(err, `rm -r failed`, { compileDir, stderr: err.stderr })
  319. throw err
  320. }
  321. }
  322. async function _findAllDirs() {
  323. const root = Settings.path.compilesDir
  324. const files = await fsPromises.readdir(root)
  325. const allDirs = files.map(file => Path.join(root, file))
  326. return allDirs
  327. }
  328. async function clearExpiredProjects(maxCacheAgeMs) {
  329. const now = Date.now()
  330. const dirs = await _findAllDirs()
  331. for (const dir of dirs) {
  332. let stats
  333. try {
  334. stats = await fsPromises.stat(dir)
  335. } catch (err) {
  336. // ignore errors checking directory
  337. continue
  338. }
  339. const age = now - stats.mtime
  340. const hasExpired = age > maxCacheAgeMs
  341. if (hasExpired) {
  342. await fsPromises.rm(dir, { force: true, recursive: true })
  343. }
  344. }
  345. }
  346. async function _checkDirectory(compileDir) {
  347. let stats
  348. try {
  349. stats = await fsPromises.lstat(compileDir)
  350. } catch (err) {
  351. if (err.code === 'ENOENT') {
  352. // directory does not exist
  353. return false
  354. }
  355. OError.tag(err, 'error on stat of project directory for removal', {
  356. dir: compileDir,
  357. })
  358. throw err
  359. }
  360. if (!stats.isDirectory()) {
  361. throw new OError('project directory is not directory', {
  362. dir: compileDir,
  363. stats,
  364. })
  365. }
  366. return true
  367. }
  368. async function syncFromCode(
  369. projectId,
  370. userId,
  371. filename,
  372. line,
  373. column,
  374. imageName
  375. ) {
  376. // If LaTeX was run in a virtual environment, the file path that synctex expects
  377. // might not match the file path on the host. The .synctex.gz file however, will be accessed
  378. // wherever it is on the host.
  379. const compileName = getCompileName(projectId, userId)
  380. const baseDir = Settings.path.synctexBaseDir(compileName)
  381. const inputFilePath = Path.join(baseDir, filename)
  382. const outputFilePath = Path.join(baseDir, 'output.pdf')
  383. const command = [
  384. 'synctex',
  385. 'view',
  386. '-i',
  387. `${line}:${column}:${inputFilePath}`,
  388. '-o',
  389. outputFilePath,
  390. ]
  391. const stdout = await _runSynctex(projectId, userId, command, imageName)
  392. logger.debug(
  393. { projectId, userId, filename, line, column, command, stdout },
  394. 'synctex code output'
  395. )
  396. return SynctexOutputParser.parseViewOutput(stdout)
  397. }
  398. async function syncFromPdf(projectId, userId, page, h, v, imageName) {
  399. const compileName = getCompileName(projectId, userId)
  400. const baseDir = Settings.path.synctexBaseDir(compileName)
  401. const outputFilePath = `${baseDir}/output.pdf`
  402. const command = [
  403. 'synctex',
  404. 'edit',
  405. '-o',
  406. `${page}:${h}:${v}:${outputFilePath}`,
  407. ]
  408. const stdout = await _runSynctex(projectId, userId, command, imageName)
  409. logger.debug({ projectId, userId, page, h, v, stdout }, 'synctex pdf output')
  410. return SynctexOutputParser.parseEditOutput(stdout, baseDir)
  411. }
  412. async function _checkFileExists(dir, filename) {
  413. try {
  414. await fsPromises.stat(dir)
  415. } catch (error) {
  416. if (error.code === 'ENOENT') {
  417. throw new Errors.NotFoundError('no output directory')
  418. }
  419. throw error
  420. }
  421. const file = Path.join(dir, filename)
  422. let stats
  423. try {
  424. stats = await fsPromises.stat(file)
  425. } catch (error) {
  426. if (error.code === 'ENOENT') {
  427. throw new Errors.NotFoundError('no output file')
  428. }
  429. }
  430. if (!stats.isFile()) {
  431. throw new Error('not a file')
  432. }
  433. }
  434. async function _runSynctex(projectId, userId, command, imageName) {
  435. const directory = getCompileDir(projectId, userId)
  436. const timeout = 60 * 1000 // increased to allow for large projects
  437. const compileName = getCompileName(projectId, userId)
  438. const compileGroup = 'synctex'
  439. const defaultImageName =
  440. Settings.clsi && Settings.clsi.docker && Settings.clsi.docker.image
  441. await _checkFileExists(directory, 'output.synctex.gz')
  442. try {
  443. const output = await CommandRunner.promises.run(
  444. compileName,
  445. command,
  446. directory,
  447. imageName || defaultImageName,
  448. timeout,
  449. {},
  450. compileGroup
  451. )
  452. return output.stdout
  453. } catch (error) {
  454. throw OError.tag(error, 'error running synctex', {
  455. command,
  456. projectId,
  457. userId,
  458. })
  459. }
  460. }
  461. async function wordcount(projectId, userId, filename, image) {
  462. logger.debug({ projectId, userId, filename, image }, 'running wordcount')
  463. const filePath = `$COMPILE_DIR/${filename}`
  464. const command = [
  465. 'texcount',
  466. '-nocol',
  467. '-inc',
  468. filePath,
  469. `-out=${filePath}.wc`,
  470. ]
  471. const compileDir = getCompileDir(projectId, userId)
  472. const timeout = 60 * 1000
  473. const compileName = getCompileName(projectId, userId)
  474. const compileGroup = 'wordcount'
  475. try {
  476. await fsPromises.mkdir(compileDir, { recursive: true })
  477. } catch (err) {
  478. throw OError.tag(err, 'error ensuring dir for wordcount', {
  479. projectId,
  480. userId,
  481. filename,
  482. })
  483. }
  484. await CommandRunner.promises.run(
  485. compileName,
  486. command,
  487. compileDir,
  488. image,
  489. timeout,
  490. {},
  491. compileGroup
  492. )
  493. let stdout
  494. try {
  495. stdout = await fsPromises.readFile(
  496. compileDir + '/' + filename + '.wc',
  497. 'utf-8'
  498. )
  499. } catch (err) {
  500. throw OError.tag(err, 'error reading word count output', {
  501. command,
  502. compileDir,
  503. projectId,
  504. userId,
  505. })
  506. }
  507. const results = _parseWordcountFromOutput(stdout)
  508. logger.debug({ projectId, userId, wordcount: results }, 'word count results')
  509. return results
  510. }
  511. function _parseWordcountFromOutput(output) {
  512. const results = {
  513. encode: '',
  514. textWords: 0,
  515. headWords: 0,
  516. outside: 0,
  517. headers: 0,
  518. elements: 0,
  519. mathInline: 0,
  520. mathDisplay: 0,
  521. errors: 0,
  522. messages: '',
  523. }
  524. for (const line of output.split('\n')) {
  525. const [data, info] = line.split(':')
  526. if (data.indexOf('Encoding') > -1) {
  527. results.encode = info.trim()
  528. }
  529. if (data.indexOf('in text') > -1) {
  530. results.textWords = parseInt(info, 10)
  531. }
  532. if (data.indexOf('in head') > -1) {
  533. results.headWords = parseInt(info, 10)
  534. }
  535. if (data.indexOf('outside') > -1) {
  536. results.outside = parseInt(info, 10)
  537. }
  538. if (data.indexOf('of head') > -1) {
  539. results.headers = parseInt(info, 10)
  540. }
  541. if (data.indexOf('Number of floats/tables/figures') > -1) {
  542. results.elements = parseInt(info, 10)
  543. }
  544. if (data.indexOf('Number of math inlines') > -1) {
  545. results.mathInline = parseInt(info, 10)
  546. }
  547. if (data.indexOf('Number of math displayed') > -1) {
  548. results.mathDisplay = parseInt(info, 10)
  549. }
  550. if (data === '(errors') {
  551. // errors reported as (errors:123)
  552. results.errors = parseInt(info, 10)
  553. }
  554. if (line.indexOf('!!! ') > -1) {
  555. // errors logged as !!! message !!!
  556. results.messages += line + '\n'
  557. }
  558. }
  559. return results
  560. }
  561. module.exports = {
  562. doCompileWithLock: callbackify(doCompileWithLock),
  563. stopCompile: callbackify(stopCompile),
  564. clearProject: callbackify(clearProject),
  565. clearExpiredProjects: callbackify(clearExpiredProjects),
  566. syncFromCode: callbackify(syncFromCode),
  567. syncFromPdf: callbackify(syncFromPdf),
  568. wordcount: callbackify(wordcount),
  569. promises: {
  570. doCompileWithLock,
  571. stopCompile,
  572. clearProject,
  573. clearExpiredProjects,
  574. syncFromCode,
  575. syncFromPdf,
  576. wordcount,
  577. },
  578. }