CompileManager.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709
  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. if (Settings.texliveOpenoutAny && Settings.texliveOpenoutAny !== '') {
  140. // override default texlive openout_any environment variable
  141. env.openout_any = Settings.texliveOpenoutAny
  142. }
  143. // only run chktex on LaTeX files (not knitr .Rtex files or any others)
  144. const isLaTeXFile =
  145. request.rootResourcePath != null
  146. ? request.rootResourcePath.match(/\.tex$/i)
  147. : undefined
  148. if (request.check != null && isLaTeXFile) {
  149. env.CHKTEX_OPTIONS = '-nall -e9 -e10 -w15 -w16'
  150. env.CHKTEX_ULIMIT_OPTIONS = '-t 5 -v 64000'
  151. if (request.check === 'error') {
  152. env.CHKTEX_EXIT_ON_ERROR = 1
  153. }
  154. if (request.check === 'validate') {
  155. env.CHKTEX_VALIDATE = 1
  156. }
  157. }
  158. // apply a series of file modifications/creations for draft mode and tikz
  159. return async.series(
  160. [injectDraftModeIfRequired, createTikzFileIfRequired],
  161. function(error) {
  162. if (error != null) {
  163. return callback(error)
  164. }
  165. timer = new Metrics.Timer('run-compile')
  166. // find the image tag to log it as a metric, e.g. 2015.1 (convert . to - for graphite)
  167. let tag =
  168. __guard__(
  169. __guard__(
  170. request.imageName != null
  171. ? request.imageName.match(/:(.*)/)
  172. : undefined,
  173. x1 => x1[1]
  174. ),
  175. x => x.replace(/\./g, '-')
  176. ) || 'default'
  177. if (!request.project_id.match(/^[0-9a-f]{24}$/)) {
  178. tag = 'other'
  179. } // exclude smoke test
  180. Metrics.inc('compiles')
  181. Metrics.inc(`compiles-with-image.${tag}`)
  182. const compileName = getCompileName(
  183. request.project_id,
  184. request.user_id
  185. )
  186. return LatexRunner.runLatex(
  187. compileName,
  188. {
  189. directory: compileDir,
  190. mainFile: request.rootResourcePath,
  191. compiler: request.compiler,
  192. timeout: request.timeout,
  193. image: request.imageName,
  194. flags: request.flags,
  195. environment: env
  196. },
  197. function(error, output, stats, timings) {
  198. // request was for validation only
  199. let metric_key, metric_value
  200. if (request.check === 'validate') {
  201. const result = (error != null
  202. ? error.code
  203. : undefined)
  204. ? 'fail'
  205. : 'pass'
  206. error = new Error('validation')
  207. error.validate = result
  208. }
  209. // request was for compile, and failed on validation
  210. if (
  211. request.check === 'error' &&
  212. (error != null ? error.message : undefined) === 'exited'
  213. ) {
  214. error = new Error('compilation')
  215. error.validate = 'fail'
  216. }
  217. // compile was killed by user, was a validation, or a compile which failed validation
  218. if (
  219. (error != null ? error.terminated : undefined) ||
  220. (error != null ? error.validate : undefined) ||
  221. (error != null ? error.timedout : undefined)
  222. ) {
  223. OutputFileFinder.findOutputFiles(
  224. resourceList,
  225. compileDir,
  226. function(err, outputFiles) {
  227. if (err != null) {
  228. return callback(err)
  229. }
  230. error.outputFiles = outputFiles // return output files so user can check logs
  231. return callback(error)
  232. }
  233. )
  234. return
  235. }
  236. // compile completed normally
  237. if (error != null) {
  238. return callback(error)
  239. }
  240. Metrics.inc('compiles-succeeded')
  241. const object = stats || {}
  242. for (metric_key in object) {
  243. metric_value = object[metric_key]
  244. Metrics.count(metric_key, metric_value)
  245. }
  246. const object1 = timings || {}
  247. for (metric_key in object1) {
  248. metric_value = object1[metric_key]
  249. Metrics.timing(metric_key, metric_value)
  250. }
  251. const loadavg =
  252. typeof os.loadavg === 'function' ? os.loadavg() : undefined
  253. if (loadavg != null) {
  254. Metrics.gauge('load-avg', loadavg[0])
  255. }
  256. const ts = timer.done()
  257. logger.log(
  258. {
  259. project_id: request.project_id,
  260. user_id: request.user_id,
  261. time_taken: ts,
  262. stats,
  263. timings,
  264. loadavg
  265. },
  266. 'done compile'
  267. )
  268. if ((stats != null ? stats['latex-runs'] : undefined) > 0) {
  269. Metrics.timing('run-compile-per-pass', ts / stats['latex-runs'])
  270. }
  271. if (
  272. (stats != null ? stats['latex-runs'] : undefined) > 0 &&
  273. (timings != null ? timings['cpu-time'] : undefined) > 0
  274. ) {
  275. Metrics.timing(
  276. 'run-compile-cpu-time-per-pass',
  277. timings['cpu-time'] / stats['latex-runs']
  278. )
  279. }
  280. return OutputFileFinder.findOutputFiles(
  281. resourceList,
  282. compileDir,
  283. function(error, outputFiles) {
  284. if (error != null) {
  285. return callback(error)
  286. }
  287. return OutputCacheManager.saveOutputFiles(
  288. outputFiles,
  289. compileDir,
  290. (error, newOutputFiles) => callback(null, newOutputFiles)
  291. )
  292. }
  293. )
  294. }
  295. )
  296. }
  297. )
  298. })
  299. },
  300. stopCompile(project_id, user_id, callback) {
  301. if (callback == null) {
  302. callback = function(error) {}
  303. }
  304. const compileName = getCompileName(project_id, user_id)
  305. return LatexRunner.killLatex(compileName, callback)
  306. },
  307. clearProject(project_id, user_id, _callback) {
  308. if (_callback == null) {
  309. _callback = function(error) {}
  310. }
  311. const callback = function(error) {
  312. _callback(error)
  313. return (_callback = function() {})
  314. }
  315. const compileDir = getCompileDir(project_id, user_id)
  316. return CompileManager._checkDirectory(compileDir, function(err, exists) {
  317. if (err != null) {
  318. return callback(err)
  319. }
  320. if (!exists) {
  321. return callback()
  322. } // skip removal if no directory present
  323. const proc = child_process.spawn('rm', ['-r', compileDir])
  324. proc.on('error', callback)
  325. let stderr = ''
  326. proc.stderr.setEncoding('utf8').on('data', chunk => (stderr += chunk))
  327. return proc.on('close', function(code) {
  328. if (code === 0) {
  329. return callback(null)
  330. } else {
  331. return callback(new Error(`rm -r ${compileDir} failed: ${stderr}`))
  332. }
  333. })
  334. })
  335. },
  336. _findAllDirs(callback) {
  337. if (callback == null) {
  338. callback = function(error, allDirs) {}
  339. }
  340. const root = Settings.path.compilesDir
  341. return fs.readdir(root, function(err, files) {
  342. if (err != null) {
  343. return callback(err)
  344. }
  345. const allDirs = Array.from(files).map(file => Path.join(root, file))
  346. return callback(null, allDirs)
  347. })
  348. },
  349. clearExpiredProjects(max_cache_age_ms, callback) {
  350. if (callback == null) {
  351. callback = function(error) {}
  352. }
  353. const now = Date.now()
  354. // action for each directory
  355. const expireIfNeeded = (checkDir, cb) =>
  356. fs.stat(checkDir, function(err, stats) {
  357. if (err != null) {
  358. return cb()
  359. } // ignore errors checking directory
  360. const age = now - stats.mtime
  361. const hasExpired = age > max_cache_age_ms
  362. if (hasExpired) {
  363. return fse.remove(checkDir, cb)
  364. } else {
  365. return cb()
  366. }
  367. })
  368. // iterate over all project directories
  369. return CompileManager._findAllDirs(function(error, allDirs) {
  370. if (error != null) {
  371. return callback()
  372. }
  373. return async.eachSeries(allDirs, expireIfNeeded, callback)
  374. })
  375. },
  376. _checkDirectory(compileDir, callback) {
  377. if (callback == null) {
  378. callback = function(error, exists) {}
  379. }
  380. return fs.lstat(compileDir, function(err, stats) {
  381. if ((err != null ? err.code : undefined) === 'ENOENT') {
  382. return callback(null, false) // directory does not exist
  383. } else if (err != null) {
  384. logger.err(
  385. { dir: compileDir, err },
  386. 'error on stat of project directory for removal'
  387. )
  388. return callback(err)
  389. } else if (!(stats != null ? stats.isDirectory() : undefined)) {
  390. logger.err(
  391. { dir: compileDir, stats },
  392. 'bad project directory for removal'
  393. )
  394. return callback(new Error('project directory is not directory'))
  395. } else {
  396. return callback(null, true)
  397. }
  398. })
  399. }, // directory exists
  400. syncFromCode(project_id, user_id, file_name, line, column, callback) {
  401. // If LaTeX was run in a virtual environment, the file path that synctex expects
  402. // might not match the file path on the host. The .synctex.gz file however, will be accessed
  403. // wherever it is on the host.
  404. if (callback == null) {
  405. callback = function(error, pdfPositions) {}
  406. }
  407. const compileName = getCompileName(project_id, user_id)
  408. const base_dir = Settings.path.synctexBaseDir(compileName)
  409. const file_path = base_dir + '/' + file_name
  410. const compileDir = getCompileDir(project_id, user_id)
  411. const synctex_path = `${base_dir}/output.pdf`
  412. const command = ['code', synctex_path, file_path, line, column]
  413. return fse.ensureDir(compileDir, function(error) {
  414. if (error != null) {
  415. logger.err(
  416. { error, project_id, user_id, file_name },
  417. 'error ensuring dir for sync from code'
  418. )
  419. return callback(error)
  420. }
  421. return CompileManager._runSynctex(project_id, user_id, command, function(
  422. error,
  423. stdout
  424. ) {
  425. if (error != null) {
  426. return callback(error)
  427. }
  428. logger.log(
  429. { project_id, user_id, file_name, line, column, command, stdout },
  430. 'synctex code output'
  431. )
  432. return callback(
  433. null,
  434. CompileManager._parseSynctexFromCodeOutput(stdout)
  435. )
  436. })
  437. })
  438. },
  439. syncFromPdf(project_id, user_id, page, h, v, callback) {
  440. if (callback == null) {
  441. callback = function(error, filePositions) {}
  442. }
  443. const compileName = getCompileName(project_id, user_id)
  444. const compileDir = getCompileDir(project_id, user_id)
  445. const base_dir = Settings.path.synctexBaseDir(compileName)
  446. const synctex_path = `${base_dir}/output.pdf`
  447. const command = ['pdf', synctex_path, page, h, v]
  448. return fse.ensureDir(compileDir, function(error) {
  449. if (error != null) {
  450. logger.err(
  451. { error, project_id, user_id, file_name },
  452. 'error ensuring dir for sync to code'
  453. )
  454. return callback(error)
  455. }
  456. return CompileManager._runSynctex(project_id, user_id, command, function(
  457. error,
  458. stdout
  459. ) {
  460. if (error != null) {
  461. return callback(error)
  462. }
  463. logger.log(
  464. { project_id, user_id, page, h, v, stdout },
  465. 'synctex pdf output'
  466. )
  467. return callback(
  468. null,
  469. CompileManager._parseSynctexFromPdfOutput(stdout, base_dir)
  470. )
  471. })
  472. })
  473. },
  474. _checkFileExists(path, callback) {
  475. if (callback == null) {
  476. callback = function(error) {}
  477. }
  478. const synctexDir = Path.dirname(path)
  479. const synctexFile = Path.join(synctexDir, 'output.synctex.gz')
  480. return fs.stat(synctexDir, function(error, stats) {
  481. if ((error != null ? error.code : undefined) === 'ENOENT') {
  482. return callback(
  483. new Errors.NotFoundError('called synctex with no output directory')
  484. )
  485. }
  486. if (error != null) {
  487. return callback(error)
  488. }
  489. return fs.stat(synctexFile, function(error, stats) {
  490. if ((error != null ? error.code : undefined) === 'ENOENT') {
  491. return callback(
  492. new Errors.NotFoundError('called synctex with no output file')
  493. )
  494. }
  495. if (error != null) {
  496. return callback(error)
  497. }
  498. if (!(stats != null ? stats.isFile() : undefined)) {
  499. return callback(new Error('not a file'))
  500. }
  501. return callback()
  502. })
  503. })
  504. },
  505. _runSynctex(project_id, user_id, command, callback) {
  506. if (callback == null) {
  507. callback = function(error, stdout) {}
  508. }
  509. const seconds = 1000
  510. command.unshift('/opt/synctex')
  511. const directory = getCompileDir(project_id, user_id)
  512. const timeout = 60 * 1000 // increased to allow for large projects
  513. const compileName = getCompileName(project_id, user_id)
  514. return CommandRunner.run(
  515. compileName,
  516. command,
  517. directory,
  518. Settings.clsi != null ? Settings.clsi.docker.image : undefined,
  519. timeout,
  520. {},
  521. function(error, output) {
  522. if (error != null) {
  523. logger.err(
  524. { err: error, command, project_id, user_id },
  525. 'error running synctex'
  526. )
  527. return callback(error)
  528. }
  529. return callback(null, output.stdout)
  530. }
  531. )
  532. },
  533. _parseSynctexFromCodeOutput(output) {
  534. const results = []
  535. for (const line of Array.from(output.split('\n'))) {
  536. const [node, page, h, v, width, height] = Array.from(line.split('\t'))
  537. if (node === 'NODE') {
  538. results.push({
  539. page: parseInt(page, 10),
  540. h: parseFloat(h),
  541. v: parseFloat(v),
  542. height: parseFloat(height),
  543. width: parseFloat(width)
  544. })
  545. }
  546. }
  547. return results
  548. },
  549. _parseSynctexFromPdfOutput(output, base_dir) {
  550. const results = []
  551. for (let line of Array.from(output.split('\n'))) {
  552. let column, file_path, node
  553. ;[node, file_path, line, column] = Array.from(line.split('\t'))
  554. if (node === 'NODE') {
  555. const file = file_path.slice(base_dir.length + 1)
  556. results.push({
  557. file,
  558. line: parseInt(line, 10),
  559. column: parseInt(column, 10)
  560. })
  561. }
  562. }
  563. return results
  564. },
  565. wordcount(project_id, user_id, file_name, image, callback) {
  566. if (callback == null) {
  567. callback = function(error, pdfPositions) {}
  568. }
  569. logger.log({ project_id, user_id, file_name, image }, 'running wordcount')
  570. const file_path = `$COMPILE_DIR/${file_name}`
  571. const command = [
  572. 'texcount',
  573. '-nocol',
  574. '-inc',
  575. file_path,
  576. `-out=${file_path}.wc`
  577. ]
  578. const compileDir = getCompileDir(project_id, user_id)
  579. const timeout = 60 * 1000
  580. const compileName = getCompileName(project_id, user_id)
  581. return fse.ensureDir(compileDir, function(error) {
  582. if (error != null) {
  583. logger.err(
  584. { error, project_id, user_id, file_name },
  585. 'error ensuring dir for sync from code'
  586. )
  587. return callback(error)
  588. }
  589. return CommandRunner.run(
  590. compileName,
  591. command,
  592. compileDir,
  593. image,
  594. timeout,
  595. {},
  596. function(error) {
  597. if (error != null) {
  598. return callback(error)
  599. }
  600. return fs.readFile(
  601. compileDir + '/' + file_name + '.wc',
  602. 'utf-8',
  603. function(err, stdout) {
  604. if (err != null) {
  605. // call it node_err so sentry doesn't use random path error as unique id so it can't be ignored
  606. logger.err(
  607. { node_err: err, command, compileDir, project_id, user_id },
  608. 'error reading word count output'
  609. )
  610. return callback(err)
  611. }
  612. const results = CompileManager._parseWordcountFromOutput(stdout)
  613. logger.log(
  614. { project_id, user_id, wordcount: results },
  615. 'word count results'
  616. )
  617. return callback(null, results)
  618. }
  619. )
  620. }
  621. )
  622. })
  623. },
  624. _parseWordcountFromOutput(output) {
  625. const results = {
  626. encode: '',
  627. textWords: 0,
  628. headWords: 0,
  629. outside: 0,
  630. headers: 0,
  631. elements: 0,
  632. mathInline: 0,
  633. mathDisplay: 0,
  634. errors: 0,
  635. messages: ''
  636. }
  637. for (const line of Array.from(output.split('\n'))) {
  638. const [data, info] = Array.from(line.split(':'))
  639. if (data.indexOf('Encoding') > -1) {
  640. results.encode = info.trim()
  641. }
  642. if (data.indexOf('in text') > -1) {
  643. results.textWords = parseInt(info, 10)
  644. }
  645. if (data.indexOf('in head') > -1) {
  646. results.headWords = parseInt(info, 10)
  647. }
  648. if (data.indexOf('outside') > -1) {
  649. results.outside = parseInt(info, 10)
  650. }
  651. if (data.indexOf('of head') > -1) {
  652. results.headers = parseInt(info, 10)
  653. }
  654. if (data.indexOf('Number of floats/tables/figures') > -1) {
  655. results.elements = parseInt(info, 10)
  656. }
  657. if (data.indexOf('Number of math inlines') > -1) {
  658. results.mathInline = parseInt(info, 10)
  659. }
  660. if (data.indexOf('Number of math displayed') > -1) {
  661. results.mathDisplay = parseInt(info, 10)
  662. }
  663. if (data === '(errors') {
  664. // errors reported as (errors:123)
  665. results.errors = parseInt(info, 10)
  666. }
  667. if (line.indexOf('!!! ') > -1) {
  668. // errors logged as !!! message !!!
  669. results.messages += line + '\n'
  670. }
  671. }
  672. return results
  673. }
  674. }
  675. function __guard__(value, transform) {
  676. return typeof value !== 'undefined' && value !== null
  677. ? transform(value)
  678. : undefined
  679. }