CompileManager.js 17 KB

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