OutputCacheManager.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  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 timer = new Metrics.Timer('compute-pdf-ranges')
  265. ContentCacheManager.update(contentDir, outputFilePath, function (
  266. err,
  267. result
  268. ) {
  269. if (err) return callback(err, outputFiles)
  270. const [contentRanges, newContentRanges, reclaimedSpace] = result
  271. if (Settings.enablePdfCachingDark) {
  272. // In dark mode we are doing the computation only and do not emit
  273. // any ranges to the frontend.
  274. } else {
  275. outputFile.contentId = Path.basename(contentDir)
  276. outputFile.ranges = contentRanges
  277. }
  278. timings['compute-pdf-caching'] = timer.done()
  279. stats['pdf-caching-n-ranges'] = contentRanges.length
  280. stats['pdf-caching-total-ranges-size'] = contentRanges.reduce(
  281. (sum, next) => sum + (next.end - next.start),
  282. 0
  283. )
  284. stats['pdf-caching-n-new-ranges'] = newContentRanges.length
  285. stats['pdf-caching-new-ranges-size'] = newContentRanges.reduce(
  286. (sum, next) => sum + (next.end - next.start),
  287. 0
  288. )
  289. stats['pdf-caching-reclaimed-space'] = reclaimedSpace
  290. callback(null, outputFiles)
  291. })
  292. } else {
  293. callback(null, outputFiles)
  294. }
  295. })
  296. },
  297. ensureContentDir(contentRoot, callback) {
  298. fse.ensureDir(contentRoot, function (err) {
  299. if (err != null) {
  300. return callback(err)
  301. }
  302. fs.readdir(contentRoot, function (err, results) {
  303. const dirs = results.sort()
  304. const contentId = dirs.find((dir) =>
  305. OutputCacheManager.BUILD_REGEX.test(dir)
  306. )
  307. if (contentId) {
  308. callback(null, Path.join(contentRoot, contentId))
  309. } else {
  310. // make a content directory
  311. OutputCacheManager.generateBuildId(function (err, contentId) {
  312. if (err) {
  313. return callback(err)
  314. }
  315. const contentDir = Path.join(contentRoot, contentId)
  316. fse.ensureDir(contentDir, function (err) {
  317. if (err) {
  318. return callback(err)
  319. }
  320. return callback(null, contentDir)
  321. })
  322. })
  323. }
  324. })
  325. })
  326. },
  327. archiveLogs(outputFiles, compileDir, outputDir, buildId, callback) {
  328. if (callback == null) {
  329. callback = function (error) {}
  330. }
  331. const archiveDir = Path.join(
  332. outputDir,
  333. OutputCacheManager.ARCHIVE_SUBDIR,
  334. buildId
  335. )
  336. logger.log({ dir: archiveDir }, 'archiving log files for project')
  337. return fse.ensureDir(archiveDir, function (err) {
  338. if (err != null) {
  339. return callback(err)
  340. }
  341. return async.mapSeries(
  342. outputFiles,
  343. function (file, cb) {
  344. const [src, dst] = Array.from([
  345. Path.join(compileDir, file.path),
  346. Path.join(archiveDir, file.path)
  347. ])
  348. return OutputCacheManager._checkFileIsSafe(src, function (
  349. err,
  350. isSafe
  351. ) {
  352. if (err != null) {
  353. return cb(err)
  354. }
  355. if (!isSafe) {
  356. return cb()
  357. }
  358. return OutputCacheManager._checkIfShouldArchive(src, function (
  359. err,
  360. shouldArchive
  361. ) {
  362. if (err != null) {
  363. return cb(err)
  364. }
  365. if (!shouldArchive) {
  366. return cb()
  367. }
  368. return OutputCacheManager._copyFile(src, dst, cb)
  369. })
  370. })
  371. },
  372. callback
  373. )
  374. })
  375. },
  376. expireOutputFiles(cacheRoot, options, callback) {
  377. // look in compileDir for build dirs and delete if > N or age of mod time > T
  378. if (callback == null) {
  379. callback = function (error) {}
  380. }
  381. return fs.readdir(cacheRoot, function (err, results) {
  382. if (err != null) {
  383. if (err.code === 'ENOENT') {
  384. return callback(null)
  385. } // cache directory is empty
  386. logger.error({ err, project_id: cacheRoot }, 'error clearing cache')
  387. return callback(err)
  388. }
  389. const dirs = results.sort().reverse()
  390. const currentTime = Date.now()
  391. const isExpired = function (dir, index) {
  392. if ((options != null ? options.keep : undefined) === dir) {
  393. return false
  394. }
  395. // remove any directories over the requested (non-null) limit
  396. if (
  397. (options != null ? options.limit : undefined) != null &&
  398. index > options.limit
  399. ) {
  400. return true
  401. }
  402. // remove any directories over the hard limit
  403. if (index > OutputCacheManager.CACHE_LIMIT) {
  404. return true
  405. }
  406. // we can get the build time from the first part of the directory name DDDD-RRRR
  407. // DDDD is date and RRRR is random bytes
  408. const dirTime = parseInt(
  409. __guard__(dir.split('-'), (x) => x[0]),
  410. 16
  411. )
  412. const age = currentTime - dirTime
  413. return age > OutputCacheManager.CACHE_AGE
  414. }
  415. const toRemove = _.filter(dirs, isExpired)
  416. const removeDir = (dir, cb) =>
  417. fse.remove(Path.join(cacheRoot, dir), function (err, result) {
  418. logger.log({ cache: cacheRoot, dir }, 'removed expired cache dir')
  419. if (err != null) {
  420. logger.error({ err, dir }, 'cache remove error')
  421. }
  422. return cb(err, result)
  423. })
  424. return async.eachSeries(
  425. toRemove,
  426. (dir, cb) => removeDir(dir, cb),
  427. callback
  428. )
  429. })
  430. },
  431. _fileIsHidden(path) {
  432. return (path != null ? path.match(/^\.|\/\./) : undefined) != null
  433. },
  434. _checkFileIsSafe(src, callback) {
  435. // check if we have a valid file to copy into the cache
  436. if (callback == null) {
  437. callback = function (error, isSafe) {}
  438. }
  439. return fs.stat(src, function (err, stats) {
  440. if ((err != null ? err.code : undefined) === 'ENOENT') {
  441. logger.warn(
  442. { err, file: src },
  443. 'file has disappeared before copying to build cache'
  444. )
  445. return callback(err, false)
  446. } else if (err != null) {
  447. // some other problem reading the file
  448. logger.error({ err, file: src }, 'stat error for file in cache')
  449. return callback(err, false)
  450. } else if (!stats.isFile()) {
  451. // other filetype - reject it
  452. logger.warn(
  453. { src, stat: stats },
  454. 'nonfile output - refusing to copy to cache'
  455. )
  456. return callback(null, false)
  457. } else {
  458. // it's a plain file, ok to copy
  459. return callback(null, true)
  460. }
  461. })
  462. },
  463. _copyFile(src, dst, callback) {
  464. // copy output file into the cache
  465. return fse.copy(src, dst, function (err) {
  466. if ((err != null ? err.code : undefined) === 'ENOENT') {
  467. logger.warn(
  468. { err, file: src },
  469. 'file has disappeared when copying to build cache'
  470. )
  471. return callback(err, false)
  472. } else if (err != null) {
  473. logger.error({ err, src, dst }, 'copy error for file in cache')
  474. return callback(err)
  475. } else {
  476. if (
  477. Settings.clsi != null ? Settings.clsi.optimiseInDocker : undefined
  478. ) {
  479. // don't run any optimisations on the pdf when they are done
  480. // in the docker container
  481. return callback()
  482. } else {
  483. // call the optimiser for the file too
  484. return OutputFileOptimiser.optimiseFile(src, dst, callback)
  485. }
  486. }
  487. })
  488. },
  489. _checkIfShouldCopy(src, callback) {
  490. if (callback == null) {
  491. callback = function (err, shouldCopy) {}
  492. }
  493. return callback(null, !Path.basename(src).match(/^strace/))
  494. },
  495. _checkIfShouldArchive(src, callback) {
  496. let needle
  497. if (callback == null) {
  498. callback = function (err, shouldCopy) {}
  499. }
  500. if (Path.basename(src).match(/^strace/)) {
  501. return callback(null, true)
  502. }
  503. if (
  504. (Settings.clsi != null ? Settings.clsi.archive_logs : undefined) &&
  505. ((needle = Path.basename(src)),
  506. ['output.log', 'output.blg'].includes(needle))
  507. ) {
  508. return callback(null, true)
  509. }
  510. return callback(null, false)
  511. }
  512. }
  513. function __guard__(value, transform) {
  514. return typeof value !== 'undefined' && value !== null
  515. ? transform(value)
  516. : undefined
  517. }