CompileManager.js 20 KB

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