CompileManager.js 19 KB

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