CompileManager.js 21 KB

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