OutputCacheManager.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  1. /* eslint-disable
  2. handle-callback-err,
  3. */
  4. // TODO: This file was created by bulk-decaffeinate.
  5. // Fix any style issues and re-enable lint.
  6. /*
  7. * decaffeinate suggestions:
  8. * DS101: Remove unnecessary use of Array.from
  9. * DS102: Remove unnecessary code created because of implicit returns
  10. * DS103: Rewrite code to no longer use __guard__
  11. * DS104: Avoid inline assignments
  12. * DS204: Change includes calls to have a more natural evaluation order
  13. * DS207: Consider shorter variations of null checks
  14. * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
  15. */
  16. let OutputCacheManager
  17. const async = require('async')
  18. const fs = require('fs')
  19. const fse = require('fs-extra')
  20. const Path = require('path')
  21. const logger = require('logger-sharelatex')
  22. const _ = require('lodash')
  23. const Settings = require('settings-sharelatex')
  24. const crypto = require('crypto')
  25. const Metrics = require('./Metrics')
  26. const OutputFileOptimiser = require('./OutputFileOptimiser')
  27. const ContentCacheManager = require('./ContentCacheManager')
  28. module.exports = OutputCacheManager = {
  29. CONTENT_SUBDIR: 'content',
  30. CACHE_SUBDIR: 'generated-files',
  31. ARCHIVE_SUBDIR: 'archived-logs',
  32. // build id is HEXDATE-HEXRANDOM from Date.now()and RandomBytes
  33. // for backwards compatibility, make the randombytes part optional
  34. BUILD_REGEX: /^[0-9a-f]+(-[0-9a-f]+)?$/,
  35. CONTENT_REGEX: /^[0-9a-f]+(-[0-9a-f]+)?$/,
  36. CACHE_LIMIT: 2, // maximum number of cache directories
  37. CACHE_AGE: 60 * 60 * 1000, // up to one hour old
  38. path(buildId, file) {
  39. // used by static server, given build id return '.cache/clsi/buildId'
  40. if (buildId.match(OutputCacheManager.BUILD_REGEX)) {
  41. return Path.join(OutputCacheManager.CACHE_SUBDIR, buildId, file)
  42. } else {
  43. // for invalid build id, return top level
  44. return file
  45. }
  46. },
  47. generateBuildId(callback) {
  48. // generate a secure build id from Date.now() and 8 random bytes in hex
  49. if (callback == null) {
  50. callback = function (error, buildId) {}
  51. }
  52. return crypto.randomBytes(8, function (err, buf) {
  53. if (err != null) {
  54. return callback(err)
  55. }
  56. const random = buf.toString('hex')
  57. const date = Date.now().toString(16)
  58. return callback(err, `${date}-${random}`)
  59. })
  60. },
  61. saveOutputFiles(
  62. { request, stats, timings },
  63. outputFiles,
  64. compileDir,
  65. outputDir,
  66. callback
  67. ) {
  68. if (callback == null) {
  69. callback = function (error) {}
  70. }
  71. return OutputCacheManager.generateBuildId(function (err, buildId) {
  72. if (err != null) {
  73. return callback(err)
  74. }
  75. return OutputCacheManager.saveOutputFilesInBuildDir(
  76. outputFiles,
  77. compileDir,
  78. outputDir,
  79. buildId,
  80. function (err, result) {
  81. if (err != null) {
  82. return callback(err)
  83. }
  84. OutputCacheManager.collectOutputPdfSize(
  85. result,
  86. outputDir,
  87. stats,
  88. (err, result) => {
  89. if (err) return callback(err, result)
  90. if (!Settings.enablePdfCaching || !request.enablePdfCaching) {
  91. return callback(null, result)
  92. }
  93. OutputCacheManager.saveStreamsInContentDir(
  94. { stats, timings },
  95. result,
  96. compileDir,
  97. outputDir,
  98. callback
  99. )
  100. }
  101. )
  102. }
  103. )
  104. })
  105. },
  106. saveOutputFilesInBuildDir(
  107. outputFiles,
  108. compileDir,
  109. outputDir,
  110. buildId,
  111. callback
  112. ) {
  113. // make a compileDir/CACHE_SUBDIR/build_id directory and
  114. // copy all the output files into it
  115. if (callback == null) {
  116. callback = function (error) {}
  117. }
  118. const cacheRoot = Path.join(outputDir, OutputCacheManager.CACHE_SUBDIR)
  119. // Put the files into a new cache subdirectory
  120. const cacheDir = Path.join(
  121. outputDir,
  122. OutputCacheManager.CACHE_SUBDIR,
  123. buildId
  124. )
  125. // Is it a per-user compile? check if compile directory is PROJECTID-USERID
  126. const perUser = Path.basename(compileDir).match(
  127. /^[0-9a-f]{24}-[0-9a-f]{24}$/
  128. )
  129. // Archive logs in background
  130. if (
  131. (Settings.clsi != null ? Settings.clsi.archive_logs : undefined) ||
  132. (Settings.clsi != null ? Settings.clsi.strace : undefined)
  133. ) {
  134. OutputCacheManager.archiveLogs(
  135. outputFiles,
  136. compileDir,
  137. outputDir,
  138. buildId,
  139. function (err) {
  140. if (err != null) {
  141. return logger.warn({ err }, 'erroring archiving log files')
  142. }
  143. }
  144. )
  145. }
  146. // make the new cache directory
  147. return fse.ensureDir(cacheDir, function (err) {
  148. if (err != null) {
  149. logger.error(
  150. { err, directory: cacheDir },
  151. 'error creating cache directory'
  152. )
  153. return callback(err, outputFiles)
  154. } else {
  155. // copy all the output files into the new cache directory
  156. const results = []
  157. return async.mapSeries(
  158. outputFiles,
  159. function (file, cb) {
  160. // don't send dot files as output, express doesn't serve them
  161. if (OutputCacheManager._fileIsHidden(file.path)) {
  162. logger.debug(
  163. { compileDir, path: file.path },
  164. 'ignoring dotfile in output'
  165. )
  166. return cb()
  167. }
  168. // copy other files into cache directory if valid
  169. const newFile = _.clone(file)
  170. const [src, dst] = Array.from([
  171. Path.join(compileDir, file.path),
  172. Path.join(cacheDir, file.path)
  173. ])
  174. return OutputCacheManager._checkFileIsSafe(src, function (
  175. err,
  176. isSafe
  177. ) {
  178. if (err != null) {
  179. return cb(err)
  180. }
  181. if (!isSafe) {
  182. return cb()
  183. }
  184. return OutputCacheManager._checkIfShouldCopy(src, function (
  185. err,
  186. shouldCopy
  187. ) {
  188. if (err != null) {
  189. return cb(err)
  190. }
  191. if (!shouldCopy) {
  192. return cb()
  193. }
  194. return OutputCacheManager._copyFile(src, dst, function (err) {
  195. if (err != null) {
  196. return cb(err)
  197. }
  198. newFile.build = buildId // attach a build id if we cached the file
  199. results.push(newFile)
  200. return cb()
  201. })
  202. })
  203. })
  204. },
  205. function (err) {
  206. if (err != null) {
  207. // pass back the original files if we encountered *any* error
  208. callback(err, outputFiles)
  209. // clean up the directory we just created
  210. return fse.remove(cacheDir, function (err) {
  211. if (err != null) {
  212. return logger.error(
  213. { err, dir: cacheDir },
  214. 'error removing cache dir after failure'
  215. )
  216. }
  217. })
  218. } else {
  219. // pass back the list of new files in the cache
  220. callback(err, results)
  221. // let file expiry run in the background, expire all previous files if per-user
  222. return OutputCacheManager.expireOutputFiles(cacheRoot, {
  223. keep: buildId,
  224. limit: perUser ? 1 : null
  225. })
  226. }
  227. }
  228. )
  229. }
  230. })
  231. },
  232. collectOutputPdfSize(outputFiles, outputDir, stats, callback) {
  233. const outputFile = outputFiles.find((x) => x.path === 'output.pdf')
  234. if (!outputFile) return callback(null, outputFiles)
  235. const outputFilePath = Path.join(
  236. outputDir,
  237. OutputCacheManager.path(outputFile.build, outputFile.path)
  238. )
  239. fs.stat(outputFilePath, (err, stat) => {
  240. if (err) return callback(err, outputFiles)
  241. outputFile.size = stat.size
  242. stats['pdf-size'] = outputFile.size
  243. callback(null, outputFiles)
  244. })
  245. },
  246. saveStreamsInContentDir(
  247. { stats, timings },
  248. outputFiles,
  249. compileDir,
  250. outputDir,
  251. callback
  252. ) {
  253. const cacheRoot = Path.join(outputDir, OutputCacheManager.CONTENT_SUBDIR)
  254. // check if content dir exists
  255. OutputCacheManager.ensureContentDir(cacheRoot, function (err, contentDir) {
  256. if (err) return callback(err, outputFiles)
  257. const outputFile = outputFiles.find((x) => x.path === 'output.pdf')
  258. if (outputFile) {
  259. // possibly we should copy the file from the build dir here
  260. const outputFilePath = Path.join(
  261. outputDir,
  262. OutputCacheManager.path(outputFile.build, outputFile.path)
  263. )
  264. const pdfSize = outputFile.size
  265. const timer = new Metrics.Timer('compute-pdf-ranges')
  266. ContentCacheManager.update(
  267. contentDir,
  268. outputFilePath,
  269. pdfSize,
  270. function (err, result) {
  271. if (err) return callback(err, outputFiles)
  272. const [contentRanges, newContentRanges, reclaimedSpace] = result
  273. if (Settings.enablePdfCachingDark) {
  274. // In dark mode we are doing the computation only and do not emit
  275. // any ranges to the frontend.
  276. } else {
  277. outputFile.contentId = Path.basename(contentDir)
  278. outputFile.ranges = contentRanges
  279. }
  280. timings['compute-pdf-caching'] = timer.done()
  281. stats['pdf-caching-n-ranges'] = contentRanges.length
  282. stats['pdf-caching-total-ranges-size'] = contentRanges.reduce(
  283. (sum, next) => sum + (next.end - next.start),
  284. 0
  285. )
  286. stats['pdf-caching-n-new-ranges'] = newContentRanges.length
  287. stats['pdf-caching-new-ranges-size'] = newContentRanges.reduce(
  288. (sum, next) => sum + (next.end - next.start),
  289. 0
  290. )
  291. stats['pdf-caching-reclaimed-space'] = reclaimedSpace
  292. callback(null, outputFiles)
  293. }
  294. )
  295. } else {
  296. callback(null, outputFiles)
  297. }
  298. })
  299. },
  300. ensureContentDir(contentRoot, callback) {
  301. fse.ensureDir(contentRoot, function (err) {
  302. if (err != null) {
  303. return callback(err)
  304. }
  305. fs.readdir(contentRoot, function (err, results) {
  306. const dirs = results.sort()
  307. const contentId = dirs.find((dir) =>
  308. OutputCacheManager.BUILD_REGEX.test(dir)
  309. )
  310. if (contentId) {
  311. callback(null, Path.join(contentRoot, contentId))
  312. } else {
  313. // make a content directory
  314. OutputCacheManager.generateBuildId(function (err, contentId) {
  315. if (err) {
  316. return callback(err)
  317. }
  318. const contentDir = Path.join(contentRoot, contentId)
  319. fse.ensureDir(contentDir, function (err) {
  320. if (err) {
  321. return callback(err)
  322. }
  323. return callback(null, contentDir)
  324. })
  325. })
  326. }
  327. })
  328. })
  329. },
  330. archiveLogs(outputFiles, compileDir, outputDir, buildId, callback) {
  331. if (callback == null) {
  332. callback = function (error) {}
  333. }
  334. const archiveDir = Path.join(
  335. outputDir,
  336. OutputCacheManager.ARCHIVE_SUBDIR,
  337. buildId
  338. )
  339. logger.log({ dir: archiveDir }, 'archiving log files for project')
  340. return fse.ensureDir(archiveDir, function (err) {
  341. if (err != null) {
  342. return callback(err)
  343. }
  344. return async.mapSeries(
  345. outputFiles,
  346. function (file, cb) {
  347. const [src, dst] = Array.from([
  348. Path.join(compileDir, file.path),
  349. Path.join(archiveDir, file.path)
  350. ])
  351. return OutputCacheManager._checkFileIsSafe(src, function (
  352. err,
  353. isSafe
  354. ) {
  355. if (err != null) {
  356. return cb(err)
  357. }
  358. if (!isSafe) {
  359. return cb()
  360. }
  361. return OutputCacheManager._checkIfShouldArchive(src, function (
  362. err,
  363. shouldArchive
  364. ) {
  365. if (err != null) {
  366. return cb(err)
  367. }
  368. if (!shouldArchive) {
  369. return cb()
  370. }
  371. return OutputCacheManager._copyFile(src, dst, cb)
  372. })
  373. })
  374. },
  375. callback
  376. )
  377. })
  378. },
  379. expireOutputFiles(cacheRoot, options, callback) {
  380. // look in compileDir for build dirs and delete if > N or age of mod time > T
  381. if (callback == null) {
  382. callback = function (error) {}
  383. }
  384. return fs.readdir(cacheRoot, function (err, results) {
  385. if (err != null) {
  386. if (err.code === 'ENOENT') {
  387. return callback(null)
  388. } // cache directory is empty
  389. logger.error({ err, project_id: cacheRoot }, 'error clearing cache')
  390. return callback(err)
  391. }
  392. const dirs = results.sort().reverse()
  393. const currentTime = Date.now()
  394. const isExpired = function (dir, index) {
  395. if ((options != null ? options.keep : undefined) === dir) {
  396. return false
  397. }
  398. // remove any directories over the requested (non-null) limit
  399. if (
  400. (options != null ? options.limit : undefined) != null &&
  401. index > options.limit
  402. ) {
  403. return true
  404. }
  405. // remove any directories over the hard limit
  406. if (index > OutputCacheManager.CACHE_LIMIT) {
  407. return true
  408. }
  409. // we can get the build time from the first part of the directory name DDDD-RRRR
  410. // DDDD is date and RRRR is random bytes
  411. const dirTime = parseInt(
  412. __guard__(dir.split('-'), (x) => x[0]),
  413. 16
  414. )
  415. const age = currentTime - dirTime
  416. return age > OutputCacheManager.CACHE_AGE
  417. }
  418. const toRemove = _.filter(dirs, isExpired)
  419. const removeDir = (dir, cb) =>
  420. fse.remove(Path.join(cacheRoot, dir), function (err, result) {
  421. logger.log({ cache: cacheRoot, dir }, 'removed expired cache dir')
  422. if (err != null) {
  423. logger.error({ err, dir }, 'cache remove error')
  424. }
  425. return cb(err, result)
  426. })
  427. return async.eachSeries(
  428. toRemove,
  429. (dir, cb) => removeDir(dir, cb),
  430. callback
  431. )
  432. })
  433. },
  434. _fileIsHidden(path) {
  435. return (path != null ? path.match(/^\.|\/\./) : undefined) != null
  436. },
  437. _checkFileIsSafe(src, callback) {
  438. // check if we have a valid file to copy into the cache
  439. if (callback == null) {
  440. callback = function (error, isSafe) {}
  441. }
  442. return fs.stat(src, function (err, stats) {
  443. if ((err != null ? err.code : undefined) === 'ENOENT') {
  444. logger.warn(
  445. { err, file: src },
  446. 'file has disappeared before copying to build cache'
  447. )
  448. return callback(err, false)
  449. } else if (err != null) {
  450. // some other problem reading the file
  451. logger.error({ err, file: src }, 'stat error for file in cache')
  452. return callback(err, false)
  453. } else if (!stats.isFile()) {
  454. // other filetype - reject it
  455. logger.warn(
  456. { src, stat: stats },
  457. 'nonfile output - refusing to copy to cache'
  458. )
  459. return callback(null, false)
  460. } else {
  461. // it's a plain file, ok to copy
  462. return callback(null, true)
  463. }
  464. })
  465. },
  466. _copyFile(src, dst, callback) {
  467. // copy output file into the cache
  468. return fse.copy(src, dst, function (err) {
  469. if ((err != null ? err.code : undefined) === 'ENOENT') {
  470. logger.warn(
  471. { err, file: src },
  472. 'file has disappeared when copying to build cache'
  473. )
  474. return callback(err, false)
  475. } else if (err != null) {
  476. logger.error({ err, src, dst }, 'copy error for file in cache')
  477. return callback(err)
  478. } else {
  479. if (
  480. Settings.clsi != null ? Settings.clsi.optimiseInDocker : undefined
  481. ) {
  482. // don't run any optimisations on the pdf when they are done
  483. // in the docker container
  484. return callback()
  485. } else {
  486. // call the optimiser for the file too
  487. return OutputFileOptimiser.optimiseFile(src, dst, callback)
  488. }
  489. }
  490. })
  491. },
  492. _checkIfShouldCopy(src, callback) {
  493. if (callback == null) {
  494. callback = function (err, shouldCopy) {}
  495. }
  496. return callback(null, !Path.basename(src).match(/^strace/))
  497. },
  498. _checkIfShouldArchive(src, callback) {
  499. let needle
  500. if (callback == null) {
  501. callback = function (err, shouldCopy) {}
  502. }
  503. if (Path.basename(src).match(/^strace/)) {
  504. return callback(null, true)
  505. }
  506. if (
  507. (Settings.clsi != null ? Settings.clsi.archive_logs : undefined) &&
  508. ((needle = Path.basename(src)),
  509. ['output.log', 'output.blg'].includes(needle))
  510. ) {
  511. return callback(null, true)
  512. }
  513. return callback(null, false)
  514. }
  515. }
  516. function __guard__(value, transform) {
  517. return typeof value !== 'undefined' && value !== null
  518. ? transform(value)
  519. : undefined
  520. }