OutputCacheManager.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  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('underscore')
  23. const Settings = require('settings-sharelatex')
  24. const crypto = require('crypto')
  25. const OutputFileOptimiser = require('./OutputFileOptimiser')
  26. module.exports = OutputCacheManager = {
  27. CACHE_SUBDIR: '.cache/clsi',
  28. ARCHIVE_SUBDIR: '.archive/clsi',
  29. // build id is HEXDATE-HEXRANDOM from Date.now()and RandomBytes
  30. // for backwards compatibility, make the randombytes part optional
  31. BUILD_REGEX: /^[0-9a-f]+(-[0-9a-f]+)?$/,
  32. CACHE_LIMIT: 2, // maximum number of cache directories
  33. CACHE_AGE: 60 * 60 * 1000, // up to one hour old
  34. path(buildId, file) {
  35. // used by static server, given build id return '.cache/clsi/buildId'
  36. if (buildId.match(OutputCacheManager.BUILD_REGEX)) {
  37. return Path.join(OutputCacheManager.CACHE_SUBDIR, buildId, file)
  38. } else {
  39. // for invalid build id, return top level
  40. return file
  41. }
  42. },
  43. generateBuildId(callback) {
  44. // generate a secure build id from Date.now() and 8 random bytes in hex
  45. if (callback == null) {
  46. callback = function(error, buildId) {}
  47. }
  48. return crypto.randomBytes(8, function(err, buf) {
  49. if (err != null) {
  50. return callback(err)
  51. }
  52. const random = buf.toString('hex')
  53. const date = Date.now().toString(16)
  54. return callback(err, `${date}-${random}`)
  55. })
  56. },
  57. saveOutputFiles(outputFiles, compileDir, callback) {
  58. if (callback == null) {
  59. callback = function(error) {}
  60. }
  61. return OutputCacheManager.generateBuildId(function(err, buildId) {
  62. if (err != null) {
  63. return callback(err)
  64. }
  65. return OutputCacheManager.saveOutputFilesInBuildDir(
  66. outputFiles,
  67. compileDir,
  68. buildId,
  69. callback
  70. )
  71. })
  72. },
  73. saveOutputFilesInBuildDir(outputFiles, compileDir, buildId, callback) {
  74. // make a compileDir/CACHE_SUBDIR/build_id directory and
  75. // copy all the output files into it
  76. if (callback == null) {
  77. callback = function(error) {}
  78. }
  79. const cacheRoot = Path.join(compileDir, OutputCacheManager.CACHE_SUBDIR)
  80. // Put the files into a new cache subdirectory
  81. const cacheDir = Path.join(
  82. compileDir,
  83. OutputCacheManager.CACHE_SUBDIR,
  84. buildId
  85. )
  86. // Is it a per-user compile? check if compile directory is PROJECTID-USERID
  87. const perUser = Path.basename(compileDir).match(
  88. /^[0-9a-f]{24}-[0-9a-f]{24}$/
  89. )
  90. // Archive logs in background
  91. if (
  92. (Settings.clsi != null ? Settings.clsi.archive_logs : undefined) ||
  93. (Settings.clsi != null ? Settings.clsi.strace : undefined)
  94. ) {
  95. OutputCacheManager.archiveLogs(outputFiles, compileDir, buildId, function(
  96. err
  97. ) {
  98. if (err != null) {
  99. return logger.warn({ err }, 'erroring archiving log files')
  100. }
  101. })
  102. }
  103. // make the new cache directory
  104. return fse.ensureDir(cacheDir, function(err) {
  105. if (err != null) {
  106. logger.error(
  107. { err, directory: cacheDir },
  108. 'error creating cache directory'
  109. )
  110. return callback(err, outputFiles)
  111. } else {
  112. // copy all the output files into the new cache directory
  113. const results = []
  114. return async.mapSeries(
  115. outputFiles,
  116. function(file, cb) {
  117. // don't send dot files as output, express doesn't serve them
  118. if (OutputCacheManager._fileIsHidden(file.path)) {
  119. logger.debug(
  120. { compileDir, path: file.path },
  121. 'ignoring dotfile in output'
  122. )
  123. return cb()
  124. }
  125. // copy other files into cache directory if valid
  126. const newFile = _.clone(file)
  127. const [src, dst] = Array.from([
  128. Path.join(compileDir, file.path),
  129. Path.join(cacheDir, file.path)
  130. ])
  131. return OutputCacheManager._checkFileIsSafe(src, function(
  132. err,
  133. isSafe
  134. ) {
  135. if (err != null) {
  136. return cb(err)
  137. }
  138. if (!isSafe) {
  139. return cb()
  140. }
  141. return OutputCacheManager._checkIfShouldCopy(src, function(
  142. err,
  143. shouldCopy
  144. ) {
  145. if (err != null) {
  146. return cb(err)
  147. }
  148. if (!shouldCopy) {
  149. return cb()
  150. }
  151. return OutputCacheManager._copyFile(src, dst, function(err) {
  152. if (err != null) {
  153. return cb(err)
  154. }
  155. newFile.build = buildId // attach a build id if we cached the file
  156. results.push(newFile)
  157. return cb()
  158. })
  159. })
  160. })
  161. },
  162. function(err) {
  163. if (err != null) {
  164. // pass back the original files if we encountered *any* error
  165. callback(err, outputFiles)
  166. // clean up the directory we just created
  167. return fse.remove(cacheDir, function(err) {
  168. if (err != null) {
  169. return logger.error(
  170. { err, dir: cacheDir },
  171. 'error removing cache dir after failure'
  172. )
  173. }
  174. })
  175. } else {
  176. // pass back the list of new files in the cache
  177. callback(err, results)
  178. // let file expiry run in the background, expire all previous files if per-user
  179. return OutputCacheManager.expireOutputFiles(cacheRoot, {
  180. keep: buildId,
  181. limit: perUser ? 1 : null
  182. })
  183. }
  184. }
  185. )
  186. }
  187. })
  188. },
  189. archiveLogs(outputFiles, compileDir, buildId, callback) {
  190. if (callback == null) {
  191. callback = function(error) {}
  192. }
  193. const archiveDir = Path.join(
  194. compileDir,
  195. OutputCacheManager.ARCHIVE_SUBDIR,
  196. buildId
  197. )
  198. logger.log({ dir: archiveDir }, 'archiving log files for project')
  199. return fse.ensureDir(archiveDir, function(err) {
  200. if (err != null) {
  201. return callback(err)
  202. }
  203. return async.mapSeries(
  204. outputFiles,
  205. function(file, cb) {
  206. const [src, dst] = Array.from([
  207. Path.join(compileDir, file.path),
  208. Path.join(archiveDir, file.path)
  209. ])
  210. return OutputCacheManager._checkFileIsSafe(src, function(
  211. err,
  212. isSafe
  213. ) {
  214. if (err != null) {
  215. return cb(err)
  216. }
  217. if (!isSafe) {
  218. return cb()
  219. }
  220. return OutputCacheManager._checkIfShouldArchive(src, function(
  221. err,
  222. shouldArchive
  223. ) {
  224. if (err != null) {
  225. return cb(err)
  226. }
  227. if (!shouldArchive) {
  228. return cb()
  229. }
  230. return OutputCacheManager._copyFile(src, dst, cb)
  231. })
  232. })
  233. },
  234. callback
  235. )
  236. })
  237. },
  238. expireOutputFiles(cacheRoot, options, callback) {
  239. // look in compileDir for build dirs and delete if > N or age of mod time > T
  240. if (callback == null) {
  241. callback = function(error) {}
  242. }
  243. return fs.readdir(cacheRoot, function(err, results) {
  244. if (err != null) {
  245. if (err.code === 'ENOENT') {
  246. return callback(null)
  247. } // cache directory is empty
  248. logger.error({ err, project_id: cacheRoot }, 'error clearing cache')
  249. return callback(err)
  250. }
  251. const dirs = results.sort().reverse()
  252. const currentTime = Date.now()
  253. const isExpired = function(dir, index) {
  254. if ((options != null ? options.keep : undefined) === dir) {
  255. return false
  256. }
  257. // remove any directories over the requested (non-null) limit
  258. if (
  259. (options != null ? options.limit : undefined) != null &&
  260. index > options.limit
  261. ) {
  262. return true
  263. }
  264. // remove any directories over the hard limit
  265. if (index > OutputCacheManager.CACHE_LIMIT) {
  266. return true
  267. }
  268. // we can get the build time from the first part of the directory name DDDD-RRRR
  269. // DDDD is date and RRRR is random bytes
  270. const dirTime = parseInt(
  271. __guard__(dir.split('-'), x => x[0]),
  272. 16
  273. )
  274. const age = currentTime - dirTime
  275. return age > OutputCacheManager.CACHE_AGE
  276. }
  277. const toRemove = _.filter(dirs, isExpired)
  278. const removeDir = (dir, cb) =>
  279. fse.remove(Path.join(cacheRoot, dir), function(err, result) {
  280. logger.log({ cache: cacheRoot, dir }, 'removed expired cache dir')
  281. if (err != null) {
  282. logger.error({ err, dir }, 'cache remove error')
  283. }
  284. return cb(err, result)
  285. })
  286. return async.eachSeries(
  287. toRemove,
  288. (dir, cb) => removeDir(dir, cb),
  289. callback
  290. )
  291. })
  292. },
  293. _fileIsHidden(path) {
  294. return (path != null ? path.match(/^\.|\/\./) : undefined) != null
  295. },
  296. _checkFileIsSafe(src, callback) {
  297. // check if we have a valid file to copy into the cache
  298. if (callback == null) {
  299. callback = function(error, isSafe) {}
  300. }
  301. return fs.stat(src, function(err, stats) {
  302. if ((err != null ? err.code : undefined) === 'ENOENT') {
  303. logger.warn(
  304. { err, file: src },
  305. 'file has disappeared before copying to build cache'
  306. )
  307. return callback(err, false)
  308. } else if (err != null) {
  309. // some other problem reading the file
  310. logger.error({ err, file: src }, 'stat error for file in cache')
  311. return callback(err, false)
  312. } else if (!stats.isFile()) {
  313. // other filetype - reject it
  314. logger.warn(
  315. { src, stat: stats },
  316. 'nonfile output - refusing to copy to cache'
  317. )
  318. return callback(null, false)
  319. } else {
  320. // it's a plain file, ok to copy
  321. return callback(null, true)
  322. }
  323. })
  324. },
  325. _copyFile(src, dst, callback) {
  326. // copy output file into the cache
  327. return fse.copy(src, dst, function(err) {
  328. if ((err != null ? err.code : undefined) === 'ENOENT') {
  329. logger.warn(
  330. { err, file: src },
  331. 'file has disappeared when copying to build cache'
  332. )
  333. return callback(err, false)
  334. } else if (err != null) {
  335. logger.error({ err, src, dst }, 'copy error for file in cache')
  336. return callback(err)
  337. } else {
  338. if (
  339. Settings.clsi != null ? Settings.clsi.optimiseInDocker : undefined
  340. ) {
  341. // don't run any optimisations on the pdf when they are done
  342. // in the docker container
  343. return callback()
  344. } else {
  345. // call the optimiser for the file too
  346. return OutputFileOptimiser.optimiseFile(src, dst, callback)
  347. }
  348. }
  349. })
  350. },
  351. _checkIfShouldCopy(src, callback) {
  352. if (callback == null) {
  353. callback = function(err, shouldCopy) {}
  354. }
  355. return callback(null, !Path.basename(src).match(/^strace/))
  356. },
  357. _checkIfShouldArchive(src, callback) {
  358. let needle
  359. if (callback == null) {
  360. callback = function(err, shouldCopy) {}
  361. }
  362. if (Path.basename(src).match(/^strace/)) {
  363. return callback(null, true)
  364. }
  365. if (
  366. (Settings.clsi != null ? Settings.clsi.archive_logs : undefined) &&
  367. ((needle = Path.basename(src)),
  368. ['output.log', 'output.blg'].includes(needle))
  369. ) {
  370. return callback(null, true)
  371. }
  372. return callback(null, false)
  373. }
  374. }
  375. function __guard__(value, transform) {
  376. return typeof value !== 'undefined' && value !== null
  377. ? transform(value)
  378. : undefined
  379. }