CompileManager.js 17 KB

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