OutputCacheManager.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  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 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(
  96. outputFiles,
  97. compileDir,
  98. buildId,
  99. function (err) {
  100. if (err != null) {
  101. return logger.warn({ err }, 'erroring archiving log files')
  102. }
  103. }
  104. )
  105. }
  106. // make the new cache directory
  107. return fse.ensureDir(cacheDir, function (err) {
  108. if (err != null) {
  109. logger.error(
  110. { err, directory: cacheDir },
  111. 'error creating cache directory'
  112. )
  113. return callback(err, outputFiles)
  114. } else {
  115. // copy all the output files into the new cache directory
  116. const results = []
  117. return async.mapSeries(
  118. outputFiles,
  119. function (file, cb) {
  120. // don't send dot files as output, express doesn't serve them
  121. if (OutputCacheManager._fileIsHidden(file.path)) {
  122. logger.debug(
  123. { compileDir, path: file.path },
  124. 'ignoring dotfile in output'
  125. )
  126. return cb()
  127. }
  128. // copy other files into cache directory if valid
  129. const newFile = _.clone(file)
  130. const [src, dst] = Array.from([
  131. Path.join(compileDir, file.path),
  132. Path.join(cacheDir, file.path)
  133. ])
  134. return OutputCacheManager._checkFileIsSafe(src, function (
  135. err,
  136. isSafe
  137. ) {
  138. if (err != null) {
  139. return cb(err)
  140. }
  141. if (!isSafe) {
  142. return cb()
  143. }
  144. return OutputCacheManager._checkIfShouldCopy(src, function (
  145. err,
  146. shouldCopy
  147. ) {
  148. if (err != null) {
  149. return cb(err)
  150. }
  151. if (!shouldCopy) {
  152. return cb()
  153. }
  154. return OutputCacheManager._copyFile(src, dst, function (err) {
  155. if (err != null) {
  156. return cb(err)
  157. }
  158. newFile.build = buildId // attach a build id if we cached the file
  159. results.push(newFile)
  160. return cb()
  161. })
  162. })
  163. })
  164. },
  165. function (err) {
  166. if (err != null) {
  167. // pass back the original files if we encountered *any* error
  168. callback(err, outputFiles)
  169. // clean up the directory we just created
  170. return fse.remove(cacheDir, function (err) {
  171. if (err != null) {
  172. return logger.error(
  173. { err, dir: cacheDir },
  174. 'error removing cache dir after failure'
  175. )
  176. }
  177. })
  178. } else {
  179. // pass back the list of new files in the cache
  180. callback(err, results)
  181. // let file expiry run in the background, expire all previous files if per-user
  182. return OutputCacheManager.expireOutputFiles(cacheRoot, {
  183. keep: buildId,
  184. limit: perUser ? 1 : null
  185. })
  186. }
  187. }
  188. )
  189. }
  190. })
  191. },
  192. archiveLogs(outputFiles, compileDir, buildId, callback) {
  193. if (callback == null) {
  194. callback = function (error) {}
  195. }
  196. const archiveDir = Path.join(
  197. compileDir,
  198. OutputCacheManager.ARCHIVE_SUBDIR,
  199. buildId
  200. )
  201. logger.log({ dir: archiveDir }, 'archiving log files for project')
  202. return fse.ensureDir(archiveDir, function (err) {
  203. if (err != null) {
  204. return callback(err)
  205. }
  206. return async.mapSeries(
  207. outputFiles,
  208. function (file, cb) {
  209. const [src, dst] = Array.from([
  210. Path.join(compileDir, file.path),
  211. Path.join(archiveDir, file.path)
  212. ])
  213. return OutputCacheManager._checkFileIsSafe(src, function (
  214. err,
  215. isSafe
  216. ) {
  217. if (err != null) {
  218. return cb(err)
  219. }
  220. if (!isSafe) {
  221. return cb()
  222. }
  223. return OutputCacheManager._checkIfShouldArchive(src, function (
  224. err,
  225. shouldArchive
  226. ) {
  227. if (err != null) {
  228. return cb(err)
  229. }
  230. if (!shouldArchive) {
  231. return cb()
  232. }
  233. return OutputCacheManager._copyFile(src, dst, cb)
  234. })
  235. })
  236. },
  237. callback
  238. )
  239. })
  240. },
  241. expireOutputFiles(cacheRoot, options, callback) {
  242. // look in compileDir for build dirs and delete if > N or age of mod time > T
  243. if (callback == null) {
  244. callback = function (error) {}
  245. }
  246. return fs.readdir(cacheRoot, function (err, results) {
  247. if (err != null) {
  248. if (err.code === 'ENOENT') {
  249. return callback(null)
  250. } // cache directory is empty
  251. logger.error({ err, project_id: cacheRoot }, 'error clearing cache')
  252. return callback(err)
  253. }
  254. const dirs = results.sort().reverse()
  255. const currentTime = Date.now()
  256. const isExpired = function (dir, index) {
  257. if ((options != null ? options.keep : undefined) === dir) {
  258. return false
  259. }
  260. // remove any directories over the requested (non-null) limit
  261. if (
  262. (options != null ? options.limit : undefined) != null &&
  263. index > options.limit
  264. ) {
  265. return true
  266. }
  267. // remove any directories over the hard limit
  268. if (index > OutputCacheManager.CACHE_LIMIT) {
  269. return true
  270. }
  271. // we can get the build time from the first part of the directory name DDDD-RRRR
  272. // DDDD is date and RRRR is random bytes
  273. const dirTime = parseInt(
  274. __guard__(dir.split('-'), (x) => x[0]),
  275. 16
  276. )
  277. const age = currentTime - dirTime
  278. return age > OutputCacheManager.CACHE_AGE
  279. }
  280. const toRemove = _.filter(dirs, isExpired)
  281. const removeDir = (dir, cb) =>
  282. fse.remove(Path.join(cacheRoot, dir), function (err, result) {
  283. logger.log({ cache: cacheRoot, dir }, 'removed expired cache dir')
  284. if (err != null) {
  285. logger.error({ err, dir }, 'cache remove error')
  286. }
  287. return cb(err, result)
  288. })
  289. return async.eachSeries(
  290. toRemove,
  291. (dir, cb) => removeDir(dir, cb),
  292. callback
  293. )
  294. })
  295. },
  296. _fileIsHidden(path) {
  297. return (path != null ? path.match(/^\.|\/\./) : undefined) != null
  298. },
  299. _checkFileIsSafe(src, callback) {
  300. // check if we have a valid file to copy into the cache
  301. if (callback == null) {
  302. callback = function (error, isSafe) {}
  303. }
  304. return fs.stat(src, function (err, stats) {
  305. if ((err != null ? err.code : undefined) === 'ENOENT') {
  306. logger.warn(
  307. { err, file: src },
  308. 'file has disappeared before copying to build cache'
  309. )
  310. return callback(err, false)
  311. } else if (err != null) {
  312. // some other problem reading the file
  313. logger.error({ err, file: src }, 'stat error for file in cache')
  314. return callback(err, false)
  315. } else if (!stats.isFile()) {
  316. // other filetype - reject it
  317. logger.warn(
  318. { src, stat: stats },
  319. 'nonfile output - refusing to copy to cache'
  320. )
  321. return callback(null, false)
  322. } else {
  323. // it's a plain file, ok to copy
  324. return callback(null, true)
  325. }
  326. })
  327. },
  328. _copyFile(src, dst, callback) {
  329. // copy output file into the cache
  330. return fse.copy(src, dst, function (err) {
  331. if ((err != null ? err.code : undefined) === 'ENOENT') {
  332. logger.warn(
  333. { err, file: src },
  334. 'file has disappeared when copying to build cache'
  335. )
  336. return callback(err, false)
  337. } else if (err != null) {
  338. logger.error({ err, src, dst }, 'copy error for file in cache')
  339. return callback(err)
  340. } else {
  341. if (
  342. Settings.clsi != null ? Settings.clsi.optimiseInDocker : undefined
  343. ) {
  344. // don't run any optimisations on the pdf when they are done
  345. // in the docker container
  346. return callback()
  347. } else {
  348. // call the optimiser for the file too
  349. return OutputFileOptimiser.optimiseFile(src, dst, callback)
  350. }
  351. }
  352. })
  353. },
  354. _checkIfShouldCopy(src, callback) {
  355. if (callback == null) {
  356. callback = function (err, shouldCopy) {}
  357. }
  358. return callback(null, !Path.basename(src).match(/^strace/))
  359. },
  360. _checkIfShouldArchive(src, callback) {
  361. let needle
  362. if (callback == null) {
  363. callback = function (err, shouldCopy) {}
  364. }
  365. if (Path.basename(src).match(/^strace/)) {
  366. return callback(null, true)
  367. }
  368. if (
  369. (Settings.clsi != null ? Settings.clsi.archive_logs : undefined) &&
  370. ((needle = Path.basename(src)),
  371. ['output.log', 'output.blg'].includes(needle))
  372. ) {
  373. return callback(null, true)
  374. }
  375. return callback(null, false)
  376. }
  377. }
  378. function __guard__(value, transform) {
  379. return typeof value !== 'undefined' && value !== null
  380. ? transform(value)
  381. : undefined
  382. }