OutputCacheManager.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690
  1. let OutputCacheManager
  2. const { callbackify, promisify } = require('util')
  3. const async = require('async')
  4. const fs = require('fs')
  5. const fse = require('fs-extra')
  6. const Path = require('path')
  7. const logger = require('@overleaf/logger')
  8. const _ = require('lodash')
  9. const Settings = require('@overleaf/settings')
  10. const crypto = require('crypto')
  11. const Metrics = require('./Metrics')
  12. const OutputFileOptimiser = require('./OutputFileOptimiser')
  13. const ContentCacheManager = require('./ContentCacheManager')
  14. const {
  15. QueueLimitReachedError,
  16. TimedOutError,
  17. NoXrefTableError,
  18. } = require('./Errors')
  19. const OLDEST_BUILD_DIR = new Map()
  20. const PENDING_PROJECT_ACTIONS = new Map()
  21. function init() {
  22. doInit().catch(err => {
  23. logger.fatal({ err }, 'low level error setting up cleanup of output dir')
  24. // consider shutting down?
  25. })
  26. }
  27. async function doInit() {
  28. await fillCache()
  29. const oldestTimestamp = await runBulkCleanup()
  30. scheduleBulkCleanup(oldestTimestamp)
  31. }
  32. function scheduleBulkCleanup(oldestTimestamp) {
  33. const delay =
  34. Math.max(OutputCacheManager.CACHE_AGE + oldestTimestamp - Date.now(), 0) +
  35. 60 * 1000
  36. setTimeout(async function () {
  37. const oldestTimestamp = await runBulkCleanup()
  38. scheduleBulkCleanup(oldestTimestamp)
  39. }, delay)
  40. }
  41. async function fillCache() {
  42. const handle = await fs.promises.opendir(Settings.path.outputDir)
  43. try {
  44. for await (const { name: projectIdAndUserId } of handle) {
  45. OLDEST_BUILD_DIR.set(
  46. Path.join(Settings.path.outputDir, projectIdAndUserId),
  47. // Queue them for cleanup in the next hour.
  48. Date.now() - Math.random() * OutputCacheManager.CACHE_AGE
  49. )
  50. }
  51. } finally {
  52. try {
  53. await handle.close()
  54. } catch (e) {}
  55. }
  56. }
  57. async function runBulkCleanup() {
  58. const cleanupThreshold = Date.now() - OutputCacheManager.CACHE_AGE
  59. let oldestTimestamp = Date.now()
  60. for (const [dir, timeStamp] of OLDEST_BUILD_DIR.entries()) {
  61. if (timeStamp < cleanupThreshold) {
  62. await cleanupDirectory(dir, { limit: OutputCacheManager.CACHE_LIMIT })
  63. } else if (timeStamp < oldestTimestamp) {
  64. oldestTimestamp = timeStamp
  65. }
  66. }
  67. return oldestTimestamp
  68. }
  69. async function cleanupDirectory(dir, options) {
  70. return queueDirOperation(dir, async () => {
  71. try {
  72. await OutputCacheManager.promises.expireOutputFiles(dir, options)
  73. } catch (err) {
  74. logger.err({ dir, err }, 'cleanup of output directory failed')
  75. }
  76. })
  77. }
  78. async function queueDirOperation(dir, fn) {
  79. const pending = PENDING_PROJECT_ACTIONS.get(dir) || Promise.resolve()
  80. const p = pending.then(fn, fn).finally(() => {
  81. if (PENDING_PROJECT_ACTIONS.get(dir) === p) {
  82. PENDING_PROJECT_ACTIONS.delete(dir)
  83. }
  84. })
  85. PENDING_PROJECT_ACTIONS.set(dir, p)
  86. return p
  87. }
  88. module.exports = OutputCacheManager = {
  89. CONTENT_SUBDIR: 'content',
  90. CACHE_SUBDIR: 'generated-files',
  91. ARCHIVE_SUBDIR: 'archived-logs',
  92. // build id is HEXDATE-HEXRANDOM from Date.now()and RandomBytes
  93. // for backwards compatibility, make the randombytes part optional
  94. BUILD_REGEX: /^[0-9a-f]+(-[0-9a-f]+)?$/,
  95. CONTENT_REGEX: /^[0-9a-f]+(-[0-9a-f]+)?$/,
  96. CACHE_LIMIT: 2, // maximum number of cache directories
  97. CACHE_AGE: 60 * 60 * 1000, // up to one hour old
  98. init,
  99. queueDirOperation: callbackify(queueDirOperation),
  100. path(buildId, file) {
  101. // used by static server, given build id return '.cache/clsi/buildId'
  102. if (buildId.match(OutputCacheManager.BUILD_REGEX)) {
  103. return Path.join(OutputCacheManager.CACHE_SUBDIR, buildId, file)
  104. } else {
  105. // for invalid build id, return top level
  106. return file
  107. }
  108. },
  109. generateBuildId(callback) {
  110. // generate a secure build id from Date.now() and 8 random bytes in hex
  111. crypto.randomBytes(8, function (err, buf) {
  112. if (err) {
  113. return callback(err)
  114. }
  115. const random = buf.toString('hex')
  116. const date = Date.now().toString(16)
  117. callback(err, `${date}-${random}`)
  118. })
  119. },
  120. saveOutputFiles(
  121. { request, stats, timings },
  122. outputFiles,
  123. compileDir,
  124. outputDir,
  125. callback
  126. ) {
  127. OutputCacheManager.generateBuildId(function (err, buildId) {
  128. if (err) {
  129. return callback(err)
  130. }
  131. if (!OLDEST_BUILD_DIR.has(outputDir)) {
  132. // Register for cleanup
  133. OLDEST_BUILD_DIR.set(outputDir, Date.now())
  134. }
  135. OutputCacheManager.queueDirOperation(
  136. outputDir,
  137. () =>
  138. OutputCacheManager.promises.saveOutputFilesInBuildDir(
  139. outputFiles,
  140. compileDir,
  141. outputDir,
  142. buildId
  143. ),
  144. function (err, result) {
  145. if (err) {
  146. return callback(err)
  147. }
  148. OutputCacheManager.collectOutputPdfSize(
  149. result,
  150. outputDir,
  151. stats,
  152. (err, outputFiles) => {
  153. if (err) return callback(err, outputFiles)
  154. const enablePdfCaching = request.enablePdfCaching
  155. const enablePdfCachingDark =
  156. Settings.enablePdfCachingDark && !request.enablePdfCaching
  157. if (
  158. !Settings.enablePdfCaching ||
  159. (!enablePdfCaching && !enablePdfCachingDark)
  160. ) {
  161. return callback(null, outputFiles)
  162. }
  163. OutputCacheManager.saveStreamsInContentDir(
  164. { request, stats, timings, enablePdfCachingDark },
  165. outputFiles,
  166. compileDir,
  167. outputDir,
  168. (err, status) => {
  169. Metrics.inc('pdf-caching-status', 1, {
  170. status,
  171. ...request.metricsOpts,
  172. })
  173. if (err) {
  174. logger.warn(
  175. { err, outputDir, stats, timings },
  176. 'pdf caching failed'
  177. )
  178. return callback(null, outputFiles)
  179. }
  180. callback(err, outputFiles)
  181. }
  182. )
  183. }
  184. )
  185. }
  186. )
  187. })
  188. },
  189. saveOutputFilesInBuildDir(
  190. outputFiles,
  191. compileDir,
  192. outputDir,
  193. buildId,
  194. callback
  195. ) {
  196. // make a compileDir/CACHE_SUBDIR/build_id directory and
  197. // copy all the output files into it
  198. // Put the files into a new cache subdirectory
  199. const cacheDir = Path.join(
  200. outputDir,
  201. OutputCacheManager.CACHE_SUBDIR,
  202. buildId
  203. )
  204. // Is it a per-user compile? check if compile directory is PROJECTID-USERID
  205. const perUser = Path.basename(compileDir).match(
  206. /^[0-9a-f]{24}-[0-9a-f]{24}$/
  207. )
  208. // Archive logs in background
  209. if (Settings.clsi?.archive_logs || Settings.clsi?.strace) {
  210. OutputCacheManager.archiveLogs(
  211. outputFiles,
  212. compileDir,
  213. outputDir,
  214. buildId,
  215. function (err) {
  216. if (err) {
  217. return logger.warn({ err }, 'erroring archiving log files')
  218. }
  219. }
  220. )
  221. }
  222. // make the new cache directory
  223. fse.ensureDir(cacheDir, function (err) {
  224. if (err) {
  225. logger.error(
  226. { err, directory: cacheDir },
  227. 'error creating cache directory'
  228. )
  229. callback(err, outputFiles)
  230. } else {
  231. // copy all the output files into the new cache directory
  232. const results = []
  233. async.mapSeries(
  234. outputFiles,
  235. function (file, cb) {
  236. // don't send dot files as output, express doesn't serve them
  237. if (OutputCacheManager._fileIsHidden(file.path)) {
  238. logger.debug(
  239. { compileDir, path: file.path },
  240. 'ignoring dotfile in output'
  241. )
  242. return cb()
  243. }
  244. // copy other files into cache directory if valid
  245. const newFile = _.clone(file)
  246. const src = Path.join(compileDir, file.path)
  247. const dst = Path.join(cacheDir, file.path)
  248. OutputCacheManager._checkFileIsSafe(src, function (err, isSafe) {
  249. if (err) {
  250. return cb(err)
  251. }
  252. if (!isSafe) {
  253. return cb()
  254. }
  255. OutputCacheManager._checkIfShouldCopy(
  256. src,
  257. function (err, shouldCopy) {
  258. if (err) {
  259. return cb(err)
  260. }
  261. if (!shouldCopy) {
  262. return cb()
  263. }
  264. OutputCacheManager._copyFile(src, dst, function (err) {
  265. if (err) {
  266. return cb(err)
  267. }
  268. newFile.build = buildId // attach a build id if we cached the file
  269. results.push(newFile)
  270. cb()
  271. })
  272. }
  273. )
  274. })
  275. },
  276. function (err) {
  277. if (err) {
  278. // pass back the original files if we encountered *any* error
  279. callback(err, outputFiles)
  280. // clean up the directory we just created
  281. fse.remove(cacheDir, function (err) {
  282. if (err) {
  283. return logger.error(
  284. { err, dir: cacheDir },
  285. 'error removing cache dir after failure'
  286. )
  287. }
  288. })
  289. } else {
  290. // pass back the list of new files in the cache
  291. callback(err, results)
  292. // let file expiry run in the background, expire all previous files if per-user
  293. cleanupDirectory(outputDir, {
  294. keep: buildId,
  295. limit: perUser ? 1 : null,
  296. }).catch(() => {})
  297. }
  298. }
  299. )
  300. }
  301. })
  302. },
  303. collectOutputPdfSize(outputFiles, outputDir, stats, callback) {
  304. const outputFile = outputFiles.find(x => x.path === 'output.pdf')
  305. if (!outputFile) return callback(null, outputFiles)
  306. const outputFilePath = Path.join(
  307. outputDir,
  308. OutputCacheManager.path(outputFile.build, outputFile.path)
  309. )
  310. fs.stat(outputFilePath, (err, stat) => {
  311. if (err) return callback(err, outputFiles)
  312. outputFile.size = stat.size
  313. stats['pdf-size'] = outputFile.size
  314. callback(null, outputFiles)
  315. })
  316. },
  317. saveStreamsInContentDir(
  318. { request, stats, timings, enablePdfCachingDark },
  319. outputFiles,
  320. compileDir,
  321. outputDir,
  322. callback
  323. ) {
  324. const cacheRoot = Path.join(outputDir, OutputCacheManager.CONTENT_SUBDIR)
  325. // check if content dir exists
  326. OutputCacheManager.ensureContentDir(cacheRoot, function (err, contentDir) {
  327. if (err) return callback(err, 'content-dir-unavailable')
  328. const outputFile = outputFiles.find(x => x.path === 'output.pdf')
  329. if (outputFile) {
  330. // possibly we should copy the file from the build dir here
  331. const outputFilePath = Path.join(
  332. outputDir,
  333. OutputCacheManager.path(outputFile.build, outputFile.path)
  334. )
  335. const pdfSize = outputFile.size
  336. const timer = new Metrics.Timer(
  337. 'compute-pdf-ranges',
  338. 1,
  339. request.metricsOpts
  340. )
  341. ContentCacheManager.update(
  342. {
  343. contentDir,
  344. filePath: outputFilePath,
  345. pdfSize,
  346. pdfCachingMinChunkSize: request.pdfCachingMinChunkSize,
  347. compileTime: timings.compile,
  348. },
  349. function (err, result) {
  350. if (err && err instanceof NoXrefTableError) {
  351. return callback(null, err.message)
  352. }
  353. if (err && err instanceof QueueLimitReachedError) {
  354. logger.warn({ err, outputDir }, 'pdf caching queue limit reached')
  355. stats['pdf-caching-queue-limit-reached'] = 1
  356. return callback(null, 'queue-limit')
  357. }
  358. if (err && err instanceof TimedOutError) {
  359. logger.warn(
  360. { err, outputDir, stats, timings },
  361. 'pdf caching timed out'
  362. )
  363. stats['pdf-caching-timed-out'] = 1
  364. return callback(null, 'timed-out')
  365. }
  366. if (err) return callback(err, 'failed')
  367. const {
  368. contentRanges,
  369. newContentRanges,
  370. reclaimedSpace,
  371. overheadDeleteStaleHashes,
  372. timedOutErr,
  373. startXRefTable,
  374. } = result
  375. let status = 'success'
  376. if (timedOutErr) {
  377. // Soft failure: let the frontend use partial set of ranges.
  378. logger.warn(
  379. {
  380. err: timedOutErr,
  381. overheadDeleteStaleHashes,
  382. outputDir,
  383. stats,
  384. timings,
  385. },
  386. 'pdf caching timed out - soft failure'
  387. )
  388. stats['pdf-caching-timed-out'] = 1
  389. status = 'timed-out-soft-failure'
  390. }
  391. if (enablePdfCachingDark) {
  392. // In dark mode we are doing the computation only and do not emit
  393. // any ranges to the frontend.
  394. } else {
  395. outputFile.contentId = Path.basename(contentDir)
  396. outputFile.ranges = contentRanges
  397. outputFile.startXRefTable = startXRefTable
  398. }
  399. timings['compute-pdf-caching'] = timer.done()
  400. stats['pdf-caching-n-ranges'] = contentRanges.length
  401. stats['pdf-caching-total-ranges-size'] = contentRanges.reduce(
  402. (sum, next) => sum + (next.end - next.start),
  403. 0
  404. )
  405. stats['pdf-caching-n-new-ranges'] = newContentRanges.length
  406. stats['pdf-caching-new-ranges-size'] = newContentRanges.reduce(
  407. (sum, next) => sum + (next.end - next.start),
  408. 0
  409. )
  410. stats['pdf-caching-reclaimed-space'] = reclaimedSpace
  411. timings['pdf-caching-overhead-delete-stale-hashes'] =
  412. overheadDeleteStaleHashes
  413. callback(null, status)
  414. }
  415. )
  416. } else {
  417. callback(null, 'missing-pdf')
  418. }
  419. })
  420. },
  421. ensureContentDir(contentRoot, callback) {
  422. fse.ensureDir(contentRoot, function (err) {
  423. if (err) {
  424. return callback(err)
  425. }
  426. fs.readdir(contentRoot, function (err, results) {
  427. if (err) return callback(err)
  428. const dirs = results.sort()
  429. const contentId = dirs.find(dir =>
  430. OutputCacheManager.BUILD_REGEX.test(dir)
  431. )
  432. if (contentId) {
  433. callback(null, Path.join(contentRoot, contentId))
  434. } else {
  435. // make a content directory
  436. OutputCacheManager.generateBuildId(function (err, contentId) {
  437. if (err) {
  438. return callback(err)
  439. }
  440. const contentDir = Path.join(contentRoot, contentId)
  441. fse.ensureDir(contentDir, function (err) {
  442. if (err) {
  443. return callback(err)
  444. }
  445. callback(null, contentDir)
  446. })
  447. })
  448. }
  449. })
  450. })
  451. },
  452. archiveLogs(outputFiles, compileDir, outputDir, buildId, callback) {
  453. const archiveDir = Path.join(
  454. outputDir,
  455. OutputCacheManager.ARCHIVE_SUBDIR,
  456. buildId
  457. )
  458. logger.debug({ dir: archiveDir }, 'archiving log files for project')
  459. fse.ensureDir(archiveDir, function (err) {
  460. if (err) {
  461. return callback(err)
  462. }
  463. async.mapSeries(
  464. outputFiles,
  465. function (file, cb) {
  466. const src = Path.join(compileDir, file.path)
  467. const dst = Path.join(archiveDir, file.path)
  468. OutputCacheManager._checkFileIsSafe(src, function (err, isSafe) {
  469. if (err) {
  470. return cb(err)
  471. }
  472. if (!isSafe) {
  473. return cb()
  474. }
  475. OutputCacheManager._checkIfShouldArchive(
  476. src,
  477. function (err, shouldArchive) {
  478. if (err) {
  479. return cb(err)
  480. }
  481. if (!shouldArchive) {
  482. return cb()
  483. }
  484. OutputCacheManager._copyFile(src, dst, cb)
  485. }
  486. )
  487. })
  488. },
  489. callback
  490. )
  491. })
  492. },
  493. expireOutputFiles(outputDir, options, callback) {
  494. // look in compileDir for build dirs and delete if > N or age of mod time > T
  495. const cleanupAll = cb => {
  496. fse.remove(outputDir, err => {
  497. if (err) {
  498. return cb(err)
  499. }
  500. // Drop reference after successful cleanup of the output dir.
  501. OLDEST_BUILD_DIR.delete(outputDir)
  502. cb(null)
  503. })
  504. }
  505. const cacheRoot = Path.join(outputDir, OutputCacheManager.CACHE_SUBDIR)
  506. fs.readdir(cacheRoot, function (err, results) {
  507. if (err) {
  508. if (err.code === 'ENOENT') {
  509. // cache directory is empty
  510. return cleanupAll(callback)
  511. }
  512. logger.error({ err, projectId: cacheRoot }, 'error clearing cache')
  513. return callback(err)
  514. }
  515. const dirs = results.sort().reverse()
  516. const currentTime = Date.now()
  517. let oldestDirTimeToKeep = 0
  518. const isExpired = function (dir, index) {
  519. if (options?.keep === dir) {
  520. // This is the directory we just created for the compile request.
  521. oldestDirTimeToKeep = currentTime
  522. return false
  523. }
  524. // remove any directories over the requested (non-null) limit
  525. if (options?.limit != null && index > options.limit) {
  526. return true
  527. }
  528. // remove any directories over the hard limit
  529. if (index > OutputCacheManager.CACHE_LIMIT) {
  530. return true
  531. }
  532. // we can get the build time from the first part of the directory name DDDD-RRRR
  533. // DDDD is date and RRRR is random bytes
  534. const dirTime = parseInt(dir.split('-')[0], 16)
  535. const age = currentTime - dirTime
  536. const expired = age > OutputCacheManager.CACHE_AGE
  537. if (expired) {
  538. return true
  539. }
  540. oldestDirTimeToKeep = dirTime
  541. return false
  542. }
  543. const toRemove = _.filter(dirs, isExpired)
  544. if (toRemove.length === dirs.length) {
  545. // No builds left after cleanup.
  546. return cleanupAll(callback)
  547. }
  548. const removeDir = (dir, cb) =>
  549. fse.remove(Path.join(cacheRoot, dir), function (err, result) {
  550. logger.debug({ cache: cacheRoot, dir }, 'removed expired cache dir')
  551. if (err) {
  552. logger.error({ err, dir }, 'cache remove error')
  553. }
  554. cb(err, result)
  555. })
  556. async.eachSeries(
  557. toRemove,
  558. (dir, cb) => removeDir(dir, cb),
  559. err => {
  560. if (err) {
  561. // On error: keep the timestamp in the past.
  562. // The next iteration of the cleanup loop will retry the deletion.
  563. return callback(err)
  564. }
  565. // On success: push the timestamp into the future.
  566. OLDEST_BUILD_DIR.set(outputDir, oldestDirTimeToKeep)
  567. callback(null)
  568. }
  569. )
  570. })
  571. },
  572. _fileIsHidden(path) {
  573. return path?.match(/^\.|\/\./) != null
  574. },
  575. _checkFileIsSafe(src, callback) {
  576. // check if we have a valid file to copy into the cache
  577. fs.stat(src, function (err, stats) {
  578. if (err?.code === 'ENOENT') {
  579. logger.warn(
  580. { err, file: src },
  581. 'file has disappeared before copying to build cache'
  582. )
  583. return callback(err, false)
  584. } else if (err) {
  585. // some other problem reading the file
  586. logger.error({ err, file: src }, 'stat error for file in cache')
  587. return callback(err, false)
  588. } else if (!stats.isFile()) {
  589. // other filetype - reject it
  590. logger.warn(
  591. { src, stat: stats },
  592. 'nonfile output - refusing to copy to cache'
  593. )
  594. return callback(null, false)
  595. } else {
  596. // it's a plain file, ok to copy
  597. return callback(null, true)
  598. }
  599. })
  600. },
  601. _copyFile(src, dst, callback) {
  602. // copy output file into the cache
  603. fse.copy(src, dst, function (err) {
  604. if (err?.code === 'ENOENT') {
  605. logger.warn(
  606. { err, file: src },
  607. 'file has disappeared when copying to build cache'
  608. )
  609. callback(err, false)
  610. } else if (err) {
  611. logger.error({ err, src, dst }, 'copy error for file in cache')
  612. callback(err)
  613. } else {
  614. if (Settings.clsi?.optimiseInDocker) {
  615. // don't run any optimisations on the pdf when they are done
  616. // in the docker container
  617. callback()
  618. } else {
  619. // call the optimiser for the file too
  620. OutputFileOptimiser.optimiseFile(src, dst, callback)
  621. }
  622. }
  623. })
  624. },
  625. _checkIfShouldCopy(src, callback) {
  626. callback(null, !Path.basename(src).match(/^strace/))
  627. },
  628. _checkIfShouldArchive(src, callback) {
  629. if (Path.basename(src).match(/^strace/)) {
  630. return callback(null, true)
  631. }
  632. const basename = Path.basename(src)
  633. if (
  634. Settings.clsi?.archive_logs &&
  635. ['output.log', 'output.blg'].includes(basename)
  636. ) {
  637. return callback(null, true)
  638. }
  639. callback(null, false)
  640. },
  641. }
  642. OutputCacheManager.promises = {
  643. expireOutputFiles: promisify(OutputCacheManager.expireOutputFiles),
  644. saveOutputFiles: promisify(OutputCacheManager.saveOutputFiles),
  645. saveOutputFilesInBuildDir: promisify(
  646. OutputCacheManager.saveOutputFilesInBuildDir
  647. ),
  648. }