CompileManager.js 20 KB

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