OutputCacheManager.js 13 KB

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