CompileManager.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  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 } = 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. // Clear project if this compile was abruptly terminated
  201. if (error.terminated || error.timedout) {
  202. await clearProjectWithListing(
  203. request.project_id,
  204. request.user_id,
  205. allEntries
  206. )
  207. }
  208. throw error
  209. }
  210. // compile completed normally
  211. Metrics.inc('compiles-succeeded', 1, request.metricsOpts)
  212. for (const metricKey in stats) {
  213. const metricValue = stats[metricKey]
  214. Metrics.count(metricKey, metricValue, 1, request.metricsOpts)
  215. }
  216. for (const metricKey in timings) {
  217. const metricValue = timings[metricKey]
  218. Metrics.timing(metricKey, metricValue, 1, request.metricsOpts)
  219. }
  220. const loadavg = typeof os.loadavg === 'function' ? os.loadavg() : undefined
  221. if (loadavg != null) {
  222. Metrics.gauge('load-avg', loadavg[0])
  223. }
  224. const ts = compileTimer.done()
  225. logger.debug(
  226. {
  227. projectId: request.project_id,
  228. userId: request.user_id,
  229. timeTaken: ts,
  230. stats,
  231. timings,
  232. loadavg,
  233. },
  234. 'done compile'
  235. )
  236. if (stats['latex-runs'] > 0) {
  237. Metrics.histogram(
  238. 'avg-compile-per-pass-v2',
  239. ts / stats['latex-runs'],
  240. COMPILE_TIME_BUCKETS,
  241. request.metricsOpts
  242. )
  243. Metrics.timing(
  244. 'avg-compile-per-pass-v2',
  245. ts / stats['latex-runs'],
  246. 1,
  247. request.metricsOpts
  248. )
  249. }
  250. if (stats['latex-runs'] > 0 && timings['cpu-time'] > 0) {
  251. Metrics.timing(
  252. 'run-compile-cpu-time-per-pass',
  253. timings['cpu-time'] / stats['latex-runs'],
  254. 1,
  255. request.metricsOpts
  256. )
  257. }
  258. // Emit compile time.
  259. timings.compile = ts
  260. const { outputFiles } = await _saveOutputFiles({
  261. request,
  262. compileDir,
  263. resourceList,
  264. stats,
  265. timings,
  266. })
  267. // Emit e2e compile time.
  268. timings.compileE2E = timerE2E.done()
  269. Metrics.timing('compile-e2e-v2', timings.compileE2E, 1, request.metricsOpts)
  270. if (stats['pdf-size']) {
  271. emitPdfStats(stats, timings, request)
  272. }
  273. return { outputFiles, stats, timings }
  274. }
  275. async function _saveOutputFiles({
  276. request,
  277. compileDir,
  278. resourceList,
  279. stats,
  280. timings,
  281. }) {
  282. const timer = new Metrics.Timer(
  283. 'process-output-files',
  284. 1,
  285. request.metricsOpts
  286. )
  287. const outputDir = getOutputDir(request.project_id, request.user_id)
  288. let { outputFiles, allEntries } =
  289. await OutputFileFinder.promises.findOutputFiles(resourceList, compileDir)
  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, allEntries }
  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. await fsPromises.rm(compileDir, { force: true, recursive: true })
  311. }
  312. async function clearProjectWithListing(projectId, userId, allEntries) {
  313. const compileDir = getCompileDir(projectId, userId)
  314. const exists = await _checkDirectory(compileDir)
  315. if (!exists) {
  316. // skip removal if no directory present
  317. return
  318. }
  319. for (const pathInProject of allEntries) {
  320. const path = Path.join(compileDir, pathInProject)
  321. if (path.endsWith('/')) {
  322. await fsPromises.rmdir(path)
  323. } else {
  324. await fsPromises.unlink(path)
  325. }
  326. }
  327. await fsPromises.rmdir(compileDir)
  328. }
  329. async function _findAllDirs() {
  330. const root = Settings.path.compilesDir
  331. const files = await fsPromises.readdir(root)
  332. const allDirs = files.map(file => Path.join(root, file))
  333. return allDirs
  334. }
  335. async function clearExpiredProjects(maxCacheAgeMs) {
  336. const now = Date.now()
  337. const dirs = await _findAllDirs()
  338. for (const dir of dirs) {
  339. let stats
  340. try {
  341. stats = await fsPromises.stat(dir)
  342. } catch (err) {
  343. // ignore errors checking directory
  344. continue
  345. }
  346. const age = now - stats.mtime
  347. const hasExpired = age > maxCacheAgeMs
  348. if (hasExpired) {
  349. await fsPromises.rm(dir, { force: true, recursive: true })
  350. }
  351. }
  352. }
  353. async function _checkDirectory(compileDir) {
  354. let stats
  355. try {
  356. stats = await fsPromises.lstat(compileDir)
  357. } catch (err) {
  358. if (err.code === 'ENOENT') {
  359. // directory does not exist
  360. return false
  361. }
  362. OError.tag(err, 'error on stat of project directory for removal', {
  363. dir: compileDir,
  364. })
  365. throw err
  366. }
  367. if (!stats.isDirectory()) {
  368. throw new OError('project directory is not directory', {
  369. dir: compileDir,
  370. stats,
  371. })
  372. }
  373. return true
  374. }
  375. async function syncFromCode(
  376. projectId,
  377. userId,
  378. filename,
  379. line,
  380. column,
  381. imageName
  382. ) {
  383. // If LaTeX was run in a virtual environment, the file path that synctex expects
  384. // might not match the file path on the host. The .synctex.gz file however, will be accessed
  385. // wherever it is on the host.
  386. const compileName = getCompileName(projectId, userId)
  387. const baseDir = Settings.path.synctexBaseDir(compileName)
  388. const inputFilePath = Path.join(baseDir, filename)
  389. const outputFilePath = Path.join(baseDir, 'output.pdf')
  390. const command = [
  391. 'synctex',
  392. 'view',
  393. '-i',
  394. `${line}:${column}:${inputFilePath}`,
  395. '-o',
  396. outputFilePath,
  397. ]
  398. const stdout = await _runSynctex(projectId, userId, command, imageName)
  399. logger.debug(
  400. { projectId, userId, filename, line, column, command, stdout },
  401. 'synctex code output'
  402. )
  403. return SynctexOutputParser.parseViewOutput(stdout)
  404. }
  405. async function syncFromPdf(projectId, userId, page, h, v, imageName) {
  406. const compileName = getCompileName(projectId, userId)
  407. const baseDir = Settings.path.synctexBaseDir(compileName)
  408. const outputFilePath = `${baseDir}/output.pdf`
  409. const command = [
  410. 'synctex',
  411. 'edit',
  412. '-o',
  413. `${page}:${h}:${v}:${outputFilePath}`,
  414. ]
  415. const stdout = await _runSynctex(projectId, userId, command, imageName)
  416. logger.debug({ projectId, userId, page, h, v, stdout }, 'synctex pdf output')
  417. return SynctexOutputParser.parseEditOutput(stdout, baseDir)
  418. }
  419. async function _checkFileExists(dir, filename) {
  420. try {
  421. await fsPromises.stat(dir)
  422. } catch (error) {
  423. if (error.code === 'ENOENT') {
  424. throw new Errors.NotFoundError('no output directory')
  425. }
  426. throw error
  427. }
  428. const file = Path.join(dir, filename)
  429. let stats
  430. try {
  431. stats = await fsPromises.stat(file)
  432. } catch (error) {
  433. if (error.code === 'ENOENT') {
  434. throw new Errors.NotFoundError('no output file')
  435. }
  436. }
  437. if (!stats.isFile()) {
  438. throw new Error('not a file')
  439. }
  440. }
  441. async function _runSynctex(projectId, userId, command, imageName) {
  442. const directory = getCompileDir(projectId, userId)
  443. const timeout = 60 * 1000 // increased to allow for large projects
  444. const compileName = getCompileName(projectId, userId)
  445. const compileGroup = 'synctex'
  446. const defaultImageName =
  447. Settings.clsi && Settings.clsi.docker && Settings.clsi.docker.image
  448. await _checkFileExists(directory, 'output.synctex.gz')
  449. try {
  450. const output = await CommandRunner.promises.run(
  451. compileName,
  452. command,
  453. directory,
  454. imageName || defaultImageName,
  455. timeout,
  456. {},
  457. compileGroup
  458. )
  459. return output.stdout
  460. } catch (error) {
  461. throw OError.tag(error, 'error running synctex', {
  462. command,
  463. projectId,
  464. userId,
  465. })
  466. }
  467. }
  468. async function wordcount(projectId, userId, filename, image) {
  469. logger.debug({ projectId, userId, filename, image }, 'running wordcount')
  470. const filePath = `$COMPILE_DIR/${filename}`
  471. const command = ['texcount', '-nocol', '-inc', filePath]
  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 fsPromises.mkdir(compileDir, { recursive: true })
  478. } catch (err) {
  479. throw OError.tag(err, 'error ensuring dir for wordcount', {
  480. projectId,
  481. userId,
  482. filename,
  483. })
  484. }
  485. try {
  486. const { stdout } = await CommandRunner.promises.run(
  487. compileName,
  488. command,
  489. compileDir,
  490. image,
  491. timeout,
  492. {},
  493. compileGroup
  494. )
  495. const results = _parseWordcountFromOutput(stdout)
  496. logger.debug(
  497. { projectId, userId, wordcount: results },
  498. 'word count results'
  499. )
  500. return results
  501. } catch (err) {
  502. throw OError.tag(err, 'error reading word count output', {
  503. command,
  504. compileDir,
  505. projectId,
  506. userId,
  507. })
  508. }
  509. }
  510. function _parseWordcountFromOutput(output) {
  511. const results = {
  512. encode: '',
  513. textWords: 0,
  514. headWords: 0,
  515. outside: 0,
  516. headers: 0,
  517. elements: 0,
  518. mathInline: 0,
  519. mathDisplay: 0,
  520. errors: 0,
  521. messages: '',
  522. }
  523. for (const line of output.split('\n')) {
  524. const [data, info] = line.split(':')
  525. if (data.indexOf('Encoding') > -1) {
  526. results.encode = info.trim()
  527. }
  528. if (data.indexOf('in text') > -1) {
  529. results.textWords = parseInt(info, 10)
  530. }
  531. if (data.indexOf('in head') > -1) {
  532. results.headWords = parseInt(info, 10)
  533. }
  534. if (data.indexOf('outside') > -1) {
  535. results.outside = parseInt(info, 10)
  536. }
  537. if (data.indexOf('of head') > -1) {
  538. results.headers = parseInt(info, 10)
  539. }
  540. if (data.indexOf('Number of floats/tables/figures') > -1) {
  541. results.elements = parseInt(info, 10)
  542. }
  543. if (data.indexOf('Number of math inlines') > -1) {
  544. results.mathInline = parseInt(info, 10)
  545. }
  546. if (data.indexOf('Number of math displayed') > -1) {
  547. results.mathDisplay = parseInt(info, 10)
  548. }
  549. if (data === '(errors') {
  550. // errors reported as (errors:123)
  551. results.errors = parseInt(info, 10)
  552. }
  553. if (line.indexOf('!!! ') > -1) {
  554. // errors logged as !!! message !!!
  555. results.messages += line + '\n'
  556. }
  557. }
  558. return results
  559. }
  560. module.exports = {
  561. doCompileWithLock: callbackify(doCompileWithLock),
  562. stopCompile: callbackify(stopCompile),
  563. clearProject: callbackify(clearProject),
  564. clearExpiredProjects: callbackify(clearExpiredProjects),
  565. syncFromCode: callbackify(syncFromCode),
  566. syncFromPdf: callbackify(syncFromPdf),
  567. wordcount: callbackify(wordcount),
  568. promises: {
  569. doCompileWithLock,
  570. stopCompile,
  571. clearProject,
  572. clearExpiredProjects,
  573. syncFromCode,
  574. syncFromPdf,
  575. wordcount,
  576. },
  577. }