CompileManager.js 22 KB

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