CompileManager.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685
  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. stopOnFirstError: request.stopOnFirstError,
  192. },
  193. (error, output, stats, timings) => {
  194. // request was for validation only
  195. if (request.check === 'validate') {
  196. const result = error && error.code ? 'fail' : 'pass'
  197. error = new Error('validation')
  198. error.validate = result
  199. }
  200. // request was for compile, and failed on validation
  201. if (
  202. request.check === 'error' &&
  203. error &&
  204. error.message === 'exited'
  205. ) {
  206. error = new Error('compilation')
  207. error.validate = 'fail'
  208. }
  209. // record timeout errors as a separate counter, success is recorded later
  210. if (error && error.timedout) {
  211. Metrics.inc('compiles-timeout', 1, request.metricsOpts)
  212. }
  213. // compile was killed by user, was a validation, or a compile which failed validation
  214. if (
  215. error &&
  216. (error.terminated || error.validate || error.timedout)
  217. ) {
  218. return OutputFileFinder.findOutputFiles(
  219. resourceList,
  220. compileDir,
  221. (err, outputFiles) => {
  222. if (err) {
  223. return callback(err)
  224. }
  225. error.outputFiles = outputFiles // return output files so user can check logs
  226. callback(error)
  227. }
  228. )
  229. }
  230. // compile completed normally
  231. if (error) {
  232. return callback(error)
  233. }
  234. Metrics.inc('compiles-succeeded', 1, request.metricsOpts)
  235. stats = stats || {}
  236. for (const metricKey in stats) {
  237. const metricValue = stats[metricKey]
  238. Metrics.count(metricKey, metricValue, 1, request.metricsOpts)
  239. }
  240. timings = timings || {}
  241. for (const metricKey in timings) {
  242. const metricValue = timings[metricKey]
  243. Metrics.timing(metricKey, metricValue, 1, request.metricsOpts)
  244. }
  245. const loadavg =
  246. typeof os.loadavg === 'function' ? os.loadavg() : undefined
  247. if (loadavg != null) {
  248. Metrics.gauge('load-avg', loadavg[0])
  249. }
  250. const ts = timer.done()
  251. logger.debug(
  252. {
  253. projectId: request.project_id,
  254. userId: request.user_id,
  255. time_taken: ts,
  256. stats,
  257. timings,
  258. loadavg,
  259. },
  260. 'done compile'
  261. )
  262. if (stats['latex-runs'] > 0) {
  263. Metrics.histogram(
  264. 'avg-compile-per-pass-v2',
  265. ts / stats['latex-runs'],
  266. COMPILE_TIME_BUCKETS,
  267. request.metricsOpts
  268. )
  269. Metrics.timing(
  270. 'avg-compile-per-pass-v2',
  271. ts / stats['latex-runs'],
  272. 1,
  273. request.metricsOpts
  274. )
  275. }
  276. if (stats['latex-runs'] > 0 && timings['cpu-time'] > 0) {
  277. Metrics.timing(
  278. 'run-compile-cpu-time-per-pass',
  279. timings['cpu-time'] / stats['latex-runs'],
  280. 1,
  281. request.metricsOpts
  282. )
  283. }
  284. // Emit compile time.
  285. timings.compile = ts
  286. const outputStageTimer = new Metrics.Timer(
  287. 'process-output-files',
  288. 1,
  289. request.metricsOpts
  290. )
  291. OutputFileFinder.findOutputFiles(
  292. resourceList,
  293. compileDir,
  294. (error, outputFiles) => {
  295. if (error) {
  296. return callback(error)
  297. }
  298. OutputCacheManager.saveOutputFiles(
  299. { request, stats, timings },
  300. outputFiles,
  301. compileDir,
  302. outputDir,
  303. (err, newOutputFiles) => {
  304. if (err) {
  305. const { project_id: projectId, user_id: userId } =
  306. request
  307. logger.err(
  308. { projectId, userId, err },
  309. 'failed to save output files'
  310. )
  311. }
  312. const outputStage = outputStageTimer.done()
  313. timings.sync = syncStage
  314. timings.output = outputStage
  315. // Emit e2e compile time.
  316. timings.compileE2E = timerE2E.done()
  317. Metrics.timing(
  318. 'compile-e2e-v2',
  319. timings.compileE2E,
  320. 1,
  321. request.metricsOpts
  322. )
  323. if (stats['pdf-size']) {
  324. emitPdfStats(stats, timings, request)
  325. }
  326. callback(null, newOutputFiles, stats, timings)
  327. }
  328. )
  329. }
  330. )
  331. }
  332. )
  333. }
  334. )
  335. }
  336. )
  337. }
  338. function stopCompile(projectId, userId, callback) {
  339. const compileName = getCompileName(projectId, userId)
  340. LatexRunner.killLatex(compileName, callback)
  341. }
  342. function clearProject(projectId, userId, _callback) {
  343. function callback(error) {
  344. _callback(error)
  345. _callback = function () {}
  346. }
  347. const compileDir = getCompileDir(projectId, userId)
  348. _checkDirectory(compileDir, (err, exists) => {
  349. if (err) {
  350. return callback(err)
  351. }
  352. if (!exists) {
  353. return callback()
  354. } // skip removal if no directory present
  355. const proc = childProcess.spawn('rm', ['-r', '-f', '--', compileDir])
  356. proc.on('error', callback)
  357. let stderr = ''
  358. proc.stderr.setEncoding('utf8').on('data', chunk => (stderr += chunk))
  359. proc.on('close', code => {
  360. if (code === 0) {
  361. callback(null)
  362. } else {
  363. callback(new Error(`rm -r ${compileDir} failed: ${stderr}`))
  364. }
  365. })
  366. })
  367. }
  368. function _findAllDirs(callback) {
  369. const root = Settings.path.compilesDir
  370. fs.readdir(root, (err, files) => {
  371. if (err) {
  372. return callback(err)
  373. }
  374. const allDirs = files.map(file => Path.join(root, file))
  375. callback(null, allDirs)
  376. })
  377. }
  378. function clearExpiredProjects(maxCacheAgeMs, callback) {
  379. const now = Date.now()
  380. // action for each directory
  381. const expireIfNeeded = (checkDir, cb) =>
  382. fs.stat(checkDir, (err, stats) => {
  383. if (err) {
  384. return cb()
  385. } // ignore errors checking directory
  386. const age = now - stats.mtime
  387. const hasExpired = age > maxCacheAgeMs
  388. if (hasExpired) {
  389. fse.remove(checkDir, cb)
  390. } else {
  391. cb()
  392. }
  393. })
  394. // iterate over all project directories
  395. _findAllDirs((error, allDirs) => {
  396. if (error) {
  397. return callback()
  398. }
  399. async.eachSeries(allDirs, expireIfNeeded, callback)
  400. })
  401. }
  402. function _checkDirectory(compileDir, callback) {
  403. fs.lstat(compileDir, (err, stats) => {
  404. if (err && err.code === 'ENOENT') {
  405. callback(null, false) // directory does not exist
  406. } else if (err) {
  407. logger.err(
  408. { dir: compileDir, err },
  409. 'error on stat of project directory for removal'
  410. )
  411. callback(err)
  412. } else if (!stats.isDirectory()) {
  413. logger.err(
  414. { dir: compileDir, stats },
  415. 'bad project directory for removal'
  416. )
  417. callback(new Error('project directory is not directory'))
  418. } else {
  419. // directory exists
  420. callback(null, true)
  421. }
  422. })
  423. }
  424. function syncFromCode(
  425. projectId,
  426. userId,
  427. filename,
  428. line,
  429. column,
  430. imageName,
  431. callback
  432. ) {
  433. // If LaTeX was run in a virtual environment, the file path that synctex expects
  434. // might not match the file path on the host. The .synctex.gz file however, will be accessed
  435. // wherever it is on the host.
  436. const compileName = getCompileName(projectId, userId)
  437. const baseDir = Settings.path.synctexBaseDir(compileName)
  438. const inputFilePath = Path.join(baseDir, filename)
  439. const outputFilePath = Path.join(baseDir, 'output.pdf')
  440. const command = [
  441. 'synctex',
  442. 'view',
  443. '-i',
  444. `${line}:${column}:${inputFilePath}`,
  445. '-o',
  446. outputFilePath,
  447. ]
  448. _runSynctex(projectId, userId, command, imageName, (error, stdout) => {
  449. if (error) {
  450. return callback(error)
  451. }
  452. logger.debug(
  453. { projectId, userId, filename, line, column, command, stdout },
  454. 'synctex code output'
  455. )
  456. callback(null, SynctexOutputParser.parseViewOutput(stdout))
  457. })
  458. }
  459. function syncFromPdf(projectId, userId, page, h, v, imageName, callback) {
  460. const compileName = getCompileName(projectId, userId)
  461. const baseDir = Settings.path.synctexBaseDir(compileName)
  462. const outputFilePath = `${baseDir}/output.pdf`
  463. const command = [
  464. 'synctex',
  465. 'edit',
  466. '-o',
  467. `${page}:${h}:${v}:${outputFilePath}`,
  468. ]
  469. _runSynctex(projectId, userId, command, imageName, (error, stdout) => {
  470. if (error != null) {
  471. return callback(error)
  472. }
  473. logger.debug(
  474. { projectId, userId, page, h, v, stdout },
  475. 'synctex pdf output'
  476. )
  477. callback(null, SynctexOutputParser.parseEditOutput(stdout, baseDir))
  478. })
  479. }
  480. function _checkFileExists(dir, filename, callback) {
  481. const file = Path.join(dir, filename)
  482. fs.stat(dir, (error, stats) => {
  483. if (error && error.code === 'ENOENT') {
  484. return callback(new Errors.NotFoundError('no output directory'))
  485. }
  486. if (error) {
  487. return callback(error)
  488. }
  489. fs.stat(file, (error, stats) => {
  490. if (error && error.code === 'ENOENT') {
  491. return callback(new Errors.NotFoundError('no output file'))
  492. }
  493. if (error) {
  494. return callback(error)
  495. }
  496. if (!stats.isFile()) {
  497. return callback(new Error('not a file'))
  498. }
  499. callback()
  500. })
  501. })
  502. }
  503. function _runSynctex(projectId, userId, command, imageName, callback) {
  504. const directory = getCompileDir(projectId, userId)
  505. const timeout = 60 * 1000 // increased to allow for large projects
  506. const compileName = getCompileName(projectId, userId)
  507. const compileGroup = 'synctex'
  508. const defaultImageName =
  509. Settings.clsi && Settings.clsi.docker && Settings.clsi.docker.image
  510. _checkFileExists(directory, 'output.synctex.gz', error => {
  511. if (error) {
  512. return callback(error)
  513. }
  514. CommandRunner.run(
  515. compileName,
  516. command,
  517. directory,
  518. imageName || defaultImageName,
  519. timeout,
  520. {},
  521. compileGroup,
  522. (error, output) => {
  523. if (error) {
  524. logger.err(
  525. { err: error, command, projectId, userId },
  526. 'error running synctex'
  527. )
  528. return callback(error)
  529. }
  530. callback(null, output.stdout)
  531. }
  532. )
  533. })
  534. }
  535. function wordcount(projectId, userId, filename, image, callback) {
  536. logger.debug({ projectId, userId, filename, image }, 'running wordcount')
  537. const filePath = `$COMPILE_DIR/${filename}`
  538. const command = [
  539. 'texcount',
  540. '-nocol',
  541. '-inc',
  542. filePath,
  543. `-out=${filePath}.wc`,
  544. ]
  545. const compileDir = getCompileDir(projectId, userId)
  546. const timeout = 60 * 1000
  547. const compileName = getCompileName(projectId, userId)
  548. const compileGroup = 'wordcount'
  549. fse.ensureDir(compileDir, error => {
  550. if (error) {
  551. logger.err(
  552. { error, projectId, userId, filename },
  553. 'error ensuring dir for sync from code'
  554. )
  555. return callback(error)
  556. }
  557. CommandRunner.run(
  558. compileName,
  559. command,
  560. compileDir,
  561. image,
  562. timeout,
  563. {},
  564. compileGroup,
  565. error => {
  566. if (error) {
  567. return callback(error)
  568. }
  569. fs.readFile(
  570. compileDir + '/' + filename + '.wc',
  571. 'utf-8',
  572. (err, stdout) => {
  573. if (err) {
  574. // call it node_err so sentry doesn't use random path error as unique id so it can't be ignored
  575. logger.err(
  576. { node_err: err, command, compileDir, projectId, userId },
  577. 'error reading word count output'
  578. )
  579. return callback(err)
  580. }
  581. const results = _parseWordcountFromOutput(stdout)
  582. logger.debug(
  583. { projectId, userId, wordcount: results },
  584. 'word count results'
  585. )
  586. callback(null, results)
  587. }
  588. )
  589. }
  590. )
  591. })
  592. }
  593. function _parseWordcountFromOutput(output) {
  594. const results = {
  595. encode: '',
  596. textWords: 0,
  597. headWords: 0,
  598. outside: 0,
  599. headers: 0,
  600. elements: 0,
  601. mathInline: 0,
  602. mathDisplay: 0,
  603. errors: 0,
  604. messages: '',
  605. }
  606. for (const line of output.split('\n')) {
  607. const [data, info] = line.split(':')
  608. if (data.indexOf('Encoding') > -1) {
  609. results.encode = info.trim()
  610. }
  611. if (data.indexOf('in text') > -1) {
  612. results.textWords = parseInt(info, 10)
  613. }
  614. if (data.indexOf('in head') > -1) {
  615. results.headWords = parseInt(info, 10)
  616. }
  617. if (data.indexOf('outside') > -1) {
  618. results.outside = parseInt(info, 10)
  619. }
  620. if (data.indexOf('of head') > -1) {
  621. results.headers = parseInt(info, 10)
  622. }
  623. if (data.indexOf('Number of floats/tables/figures') > -1) {
  624. results.elements = parseInt(info, 10)
  625. }
  626. if (data.indexOf('Number of math inlines') > -1) {
  627. results.mathInline = parseInt(info, 10)
  628. }
  629. if (data.indexOf('Number of math displayed') > -1) {
  630. results.mathDisplay = parseInt(info, 10)
  631. }
  632. if (data === '(errors') {
  633. // errors reported as (errors:123)
  634. results.errors = parseInt(info, 10)
  635. }
  636. if (line.indexOf('!!! ') > -1) {
  637. // errors logged as !!! message !!!
  638. results.messages += line + '\n'
  639. }
  640. }
  641. return results
  642. }
  643. module.exports = {
  644. doCompileWithLock,
  645. stopCompile,
  646. clearProject,
  647. clearExpiredProjects,
  648. syncFromCode,
  649. syncFromPdf,
  650. wordcount,
  651. }