CompileManager.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652
  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. const outputDir = getOutputDir(projectId, userId)
  311. _checkDirectory(compileDir, (err, exists) => {
  312. if (err) {
  313. return callback(err)
  314. }
  315. if (!exists) {
  316. return callback()
  317. } // skip removal if no directory present
  318. const proc = childProcess.spawn('rm', [
  319. '-r',
  320. '-f',
  321. '--',
  322. compileDir,
  323. outputDir,
  324. ])
  325. proc.on('error', callback)
  326. let stderr = ''
  327. proc.stderr.setEncoding('utf8').on('data', chunk => (stderr += chunk))
  328. proc.on('close', code => {
  329. if (code === 0) {
  330. callback(null)
  331. } else {
  332. callback(
  333. new Error(`rm -r ${compileDir} ${outputDir} failed: ${stderr}`)
  334. )
  335. }
  336. })
  337. })
  338. }
  339. function _findAllDirs(callback) {
  340. const root = Settings.path.compilesDir
  341. fs.readdir(root, (err, files) => {
  342. if (err) {
  343. return callback(err)
  344. }
  345. const allDirs = files.map(file => Path.join(root, file))
  346. callback(null, allDirs)
  347. })
  348. }
  349. function clearExpiredProjects(maxCacheAgeMs, callback) {
  350. const now = Date.now()
  351. // action for each directory
  352. const expireIfNeeded = (checkDir, cb) =>
  353. fs.stat(checkDir, (err, stats) => {
  354. if (err) {
  355. return cb()
  356. } // ignore errors checking directory
  357. const age = now - stats.mtime
  358. const hasExpired = age > maxCacheAgeMs
  359. if (hasExpired) {
  360. fse.remove(checkDir, cb)
  361. } else {
  362. cb()
  363. }
  364. })
  365. // iterate over all project directories
  366. _findAllDirs((error, allDirs) => {
  367. if (error) {
  368. return callback()
  369. }
  370. async.eachSeries(allDirs, expireIfNeeded, callback)
  371. })
  372. }
  373. function _checkDirectory(compileDir, callback) {
  374. fs.lstat(compileDir, (err, stats) => {
  375. if (err && err.code === 'ENOENT') {
  376. callback(null, false) // directory does not exist
  377. } else if (err) {
  378. logger.err(
  379. { dir: compileDir, err },
  380. 'error on stat of project directory for removal'
  381. )
  382. callback(err)
  383. } else if (!stats.isDirectory()) {
  384. logger.err(
  385. { dir: compileDir, stats },
  386. 'bad project directory for removal'
  387. )
  388. callback(new Error('project directory is not directory'))
  389. } else {
  390. // directory exists
  391. callback(null, true)
  392. }
  393. })
  394. }
  395. function syncFromCode(
  396. projectId,
  397. userId,
  398. filename,
  399. line,
  400. column,
  401. imageName,
  402. callback
  403. ) {
  404. // If LaTeX was run in a virtual environment, the file path that synctex expects
  405. // might not match the file path on the host. The .synctex.gz file however, will be accessed
  406. // wherever it is on the host.
  407. const compileName = getCompileName(projectId, userId)
  408. const baseDir = Settings.path.synctexBaseDir(compileName)
  409. const inputFilePath = Path.join(baseDir, filename)
  410. const outputFilePath = Path.join(baseDir, 'output.pdf')
  411. const command = [
  412. 'synctex',
  413. 'view',
  414. '-i',
  415. `${line}:${column}:${inputFilePath}`,
  416. '-o',
  417. outputFilePath,
  418. ]
  419. _runSynctex(projectId, userId, command, imageName, (error, stdout) => {
  420. if (error) {
  421. return callback(error)
  422. }
  423. logger.debug(
  424. { projectId, userId, filename, line, column, command, stdout },
  425. 'synctex code output'
  426. )
  427. callback(null, SynctexOutputParser.parseViewOutput(stdout))
  428. })
  429. }
  430. function syncFromPdf(projectId, userId, page, h, v, imageName, callback) {
  431. const compileName = getCompileName(projectId, userId)
  432. const baseDir = Settings.path.synctexBaseDir(compileName)
  433. const outputFilePath = `${baseDir}/output.pdf`
  434. const command = [
  435. 'synctex',
  436. 'edit',
  437. '-o',
  438. `${page}:${h}:${v}:${outputFilePath}`,
  439. ]
  440. _runSynctex(projectId, userId, command, imageName, (error, stdout) => {
  441. if (error != null) {
  442. return callback(error)
  443. }
  444. logger.log({ projectId, userId, page, h, v, stdout }, 'synctex pdf output')
  445. callback(null, SynctexOutputParser.parseEditOutput(stdout, baseDir))
  446. })
  447. }
  448. function _checkFileExists(dir, filename, callback) {
  449. const file = Path.join(dir, filename)
  450. fs.stat(dir, (error, stats) => {
  451. if (error && error.code === 'ENOENT') {
  452. return callback(new Errors.NotFoundError('no output directory'))
  453. }
  454. if (error) {
  455. return callback(error)
  456. }
  457. fs.stat(file, (error, stats) => {
  458. if (error && error.code === 'ENOENT') {
  459. return callback(new Errors.NotFoundError('no output file'))
  460. }
  461. if (error) {
  462. return callback(error)
  463. }
  464. if (!stats.isFile()) {
  465. return callback(new Error('not a file'))
  466. }
  467. callback()
  468. })
  469. })
  470. }
  471. function _runSynctex(projectId, userId, command, imageName, callback) {
  472. const directory = getCompileDir(projectId, userId)
  473. const timeout = 60 * 1000 // increased to allow for large projects
  474. const compileName = getCompileName(projectId, userId)
  475. const compileGroup = 'synctex'
  476. const defaultImageName =
  477. Settings.clsi && Settings.clsi.docker && Settings.clsi.docker.image
  478. _checkFileExists(directory, 'output.synctex.gz', error => {
  479. if (error) {
  480. return callback(error)
  481. }
  482. CommandRunner.run(
  483. compileName,
  484. command,
  485. directory,
  486. imageName || defaultImageName,
  487. timeout,
  488. {},
  489. compileGroup,
  490. (error, output) => {
  491. if (error) {
  492. logger.err(
  493. { err: error, command, projectId, userId },
  494. 'error running synctex'
  495. )
  496. return callback(error)
  497. }
  498. callback(null, output.stdout)
  499. }
  500. )
  501. })
  502. }
  503. function wordcount(projectId, userId, filename, image, callback) {
  504. logger.log({ projectId, userId, filename, image }, 'running wordcount')
  505. const filePath = `$COMPILE_DIR/${filename}`
  506. const command = [
  507. 'texcount',
  508. '-nocol',
  509. '-inc',
  510. filePath,
  511. `-out=${filePath}.wc`,
  512. ]
  513. const compileDir = getCompileDir(projectId, userId)
  514. const timeout = 60 * 1000
  515. const compileName = getCompileName(projectId, userId)
  516. const compileGroup = 'wordcount'
  517. fse.ensureDir(compileDir, error => {
  518. if (error) {
  519. logger.err(
  520. { error, projectId, userId, filename },
  521. 'error ensuring dir for sync from code'
  522. )
  523. return callback(error)
  524. }
  525. CommandRunner.run(
  526. compileName,
  527. command,
  528. compileDir,
  529. image,
  530. timeout,
  531. {},
  532. compileGroup,
  533. error => {
  534. if (error) {
  535. return callback(error)
  536. }
  537. fs.readFile(
  538. compileDir + '/' + filename + '.wc',
  539. 'utf-8',
  540. (err, stdout) => {
  541. if (err) {
  542. // call it node_err so sentry doesn't use random path error as unique id so it can't be ignored
  543. logger.err(
  544. { node_err: err, command, compileDir, projectId, userId },
  545. 'error reading word count output'
  546. )
  547. return callback(err)
  548. }
  549. const results = _parseWordcountFromOutput(stdout)
  550. logger.log(
  551. { projectId, userId, wordcount: results },
  552. 'word count results'
  553. )
  554. callback(null, results)
  555. }
  556. )
  557. }
  558. )
  559. })
  560. }
  561. function _parseWordcountFromOutput(output) {
  562. const results = {
  563. encode: '',
  564. textWords: 0,
  565. headWords: 0,
  566. outside: 0,
  567. headers: 0,
  568. elements: 0,
  569. mathInline: 0,
  570. mathDisplay: 0,
  571. errors: 0,
  572. messages: '',
  573. }
  574. for (const line of output.split('\n')) {
  575. const [data, info] = line.split(':')
  576. if (data.indexOf('Encoding') > -1) {
  577. results.encode = info.trim()
  578. }
  579. if (data.indexOf('in text') > -1) {
  580. results.textWords = parseInt(info, 10)
  581. }
  582. if (data.indexOf('in head') > -1) {
  583. results.headWords = parseInt(info, 10)
  584. }
  585. if (data.indexOf('outside') > -1) {
  586. results.outside = parseInt(info, 10)
  587. }
  588. if (data.indexOf('of head') > -1) {
  589. results.headers = parseInt(info, 10)
  590. }
  591. if (data.indexOf('Number of floats/tables/figures') > -1) {
  592. results.elements = parseInt(info, 10)
  593. }
  594. if (data.indexOf('Number of math inlines') > -1) {
  595. results.mathInline = parseInt(info, 10)
  596. }
  597. if (data.indexOf('Number of math displayed') > -1) {
  598. results.mathDisplay = parseInt(info, 10)
  599. }
  600. if (data === '(errors') {
  601. // errors reported as (errors:123)
  602. results.errors = parseInt(info, 10)
  603. }
  604. if (line.indexOf('!!! ') > -1) {
  605. // errors logged as !!! message !!!
  606. results.messages += line + '\n'
  607. }
  608. }
  609. return results
  610. }
  611. module.exports = {
  612. doCompileWithLock,
  613. stopCompile,
  614. clearProject,
  615. clearExpiredProjects,
  616. syncFromCode,
  617. syncFromPdf,
  618. wordcount,
  619. }