CompileManager.js 17 KB

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