OutputCacheManager.coffee 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. async = require "async"
  2. fs = require "fs"
  3. fse = require "fs-extra"
  4. Path = require "path"
  5. logger = require "logger-sharelatex"
  6. _ = require "underscore"
  7. Settings = require "settings-sharelatex"
  8. crypto = require "crypto"
  9. OutputFileOptimiser = require "./OutputFileOptimiser"
  10. module.exports = OutputCacheManager =
  11. CACHE_SUBDIR: '.cache/clsi'
  12. ARCHIVE_SUBDIR: '.archive/clsi'
  13. # build id is HEXDATE-HEXRANDOM from Date.now()and RandomBytes
  14. # for backwards compatibility, make the randombytes part optional
  15. BUILD_REGEX: /^[0-9a-f]+(-[0-9a-f]+)?$/
  16. CACHE_LIMIT: 2 # maximum number of cache directories
  17. CACHE_AGE: 60*60*1000 # up to one hour old
  18. path: (buildId, file) ->
  19. # used by static server, given build id return '.cache/clsi/buildId'
  20. if buildId.match OutputCacheManager.BUILD_REGEX
  21. return Path.join(OutputCacheManager.CACHE_SUBDIR, buildId, file)
  22. else
  23. # for invalid build id, return top level
  24. return file
  25. generateBuildId: (callback = (error, buildId) ->) ->
  26. # generate a secure build id from Date.now() and 8 random bytes in hex
  27. crypto.randomBytes 8, (err, buf) ->
  28. return callback(err) if err?
  29. random = buf.toString('hex')
  30. date = Date.now().toString(16)
  31. callback err, "#{date}-#{random}"
  32. saveOutputFiles: (outputFiles, compileDir, callback = (error) ->) ->
  33. OutputCacheManager.generateBuildId (err, buildId) ->
  34. return callback(err) if err?
  35. OutputCacheManager.saveOutputFilesInBuildDir outputFiles, compileDir, buildId, callback
  36. saveOutputFilesInBuildDir: (outputFiles, compileDir, buildId, callback = (error) ->) ->
  37. # make a compileDir/CACHE_SUBDIR/build_id directory and
  38. # copy all the output files into it
  39. cacheRoot = Path.join(compileDir, OutputCacheManager.CACHE_SUBDIR)
  40. # Put the files into a new cache subdirectory
  41. cacheDir = Path.join(compileDir, OutputCacheManager.CACHE_SUBDIR, buildId)
  42. # Is it a per-user compile? check if compile directory is PROJECTID-USERID
  43. perUser = Path.basename(compileDir).match(/^[0-9a-f]{24}-[0-9a-f]{24}$/)
  44. # Archive logs in background
  45. if Settings.clsi?.archive_logs or Settings.clsi?.strace
  46. OutputCacheManager.archiveLogs outputFiles, compileDir, buildId, (err) ->
  47. if err?
  48. logger.warn err:err, "erroring archiving log files"
  49. # make the new cache directory
  50. fse.ensureDir cacheDir, (err) ->
  51. if err?
  52. logger.error err: err, directory: cacheDir, "error creating cache directory"
  53. callback(err, outputFiles)
  54. else
  55. # copy all the output files into the new cache directory
  56. results = []
  57. async.mapSeries outputFiles, (file, cb) ->
  58. newFile = _.clone(file)
  59. [src, dst] = [Path.join(compileDir, file.path), Path.join(cacheDir, file.path)]
  60. OutputCacheManager._checkFileIsSafe src, (err, isSafe) ->
  61. return cb(err) if err?
  62. if !isSafe
  63. return cb()
  64. OutputCacheManager._checkIfShouldCopy src, (err, shouldCopy) ->
  65. return cb(err) if err?
  66. if !shouldCopy
  67. return cb()
  68. OutputCacheManager._copyFile src, dst, (err) ->
  69. return cb(err) if err?
  70. newFile.build = buildId # attach a build id if we cached the file
  71. results.push newFile
  72. cb()
  73. , (err) ->
  74. if err?
  75. # pass back the original files if we encountered *any* error
  76. callback(err, outputFiles)
  77. # clean up the directory we just created
  78. fse.remove cacheDir, (err) ->
  79. if err?
  80. logger.error err: err, dir: dir, "error removing cache dir after failure"
  81. else
  82. # pass back the list of new files in the cache
  83. callback(err, results)
  84. # let file expiry run in the background, expire all previous files if per-user
  85. OutputCacheManager.expireOutputFiles cacheRoot, {keep: buildId, limit: if perUser then 1 else null}
  86. archiveLogs: (outputFiles, compileDir, buildId, callback = (error) ->) ->
  87. archiveDir = Path.join(compileDir, OutputCacheManager.ARCHIVE_SUBDIR, buildId)
  88. logger.log {dir: archiveDir}, "archiving log files for project"
  89. fse.ensureDir archiveDir, (err) ->
  90. return callback(err) if err?
  91. async.mapSeries outputFiles, (file, cb) ->
  92. [src, dst] = [Path.join(compileDir, file.path), Path.join(archiveDir, file.path)]
  93. OutputCacheManager._checkFileIsSafe src, (err, isSafe) ->
  94. return cb(err) if err?
  95. return cb() if !isSafe
  96. OutputCacheManager._checkIfShouldArchive src, (err, shouldArchive) ->
  97. return cb(err) if err?
  98. return cb() if !shouldArchive
  99. OutputCacheManager._copyFile src, dst, cb
  100. , callback
  101. expireOutputFiles: (cacheRoot, options, callback = (error) ->) ->
  102. # look in compileDir for build dirs and delete if > N or age of mod time > T
  103. fs.readdir cacheRoot, (err, results) ->
  104. if err?
  105. return callback(null) if err.code == 'ENOENT' # cache directory is empty
  106. logger.error err: err, project_id: cacheRoot, "error clearing cache"
  107. return callback(err)
  108. dirs = results.sort().reverse()
  109. currentTime = Date.now()
  110. isExpired = (dir, index) ->
  111. return false if options?.keep == dir
  112. # remove any directories over the requested (non-null) limit
  113. return true if options?.limit? and index > options.limit
  114. # remove any directories over the hard limit
  115. return true if index > OutputCacheManager.CACHE_LIMIT
  116. # we can get the build time from the first part of the directory name DDDD-RRRR
  117. # DDDD is date and RRRR is random bytes
  118. dirTime = parseInt(dir.split('-')?[0], 16)
  119. age = currentTime - dirTime
  120. return age > OutputCacheManager.CACHE_AGE
  121. toRemove = _.filter(dirs, isExpired)
  122. removeDir = (dir, cb) ->
  123. fse.remove Path.join(cacheRoot, dir), (err, result) ->
  124. logger.log cache: cacheRoot, dir: dir, "removed expired cache dir"
  125. if err?
  126. logger.error err: err, dir: dir, "cache remove error"
  127. cb(err, result)
  128. async.eachSeries toRemove, (dir, cb) ->
  129. removeDir dir, cb
  130. , callback
  131. _checkFileIsSafe: (src, callback = (error, isSafe) ->) ->
  132. # check if we have a valid file to copy into the cache
  133. fs.stat src, (err, stats) ->
  134. if err?.code is 'ENOENT'
  135. logger.warn err: err, file: src, "file has disappeared before copying to build cache"
  136. callback(err, false)
  137. else if err?
  138. # some other problem reading the file
  139. logger.error err: err, file: src, "stat error for file in cache"
  140. callback(err, false)
  141. else if not stats.isFile()
  142. # other filetype - reject it
  143. logger.warn src: src, stat: stats, "nonfile output - refusing to copy to cache"
  144. callback(null, false)
  145. else
  146. # it's a plain file, ok to copy
  147. callback(null, true)
  148. _copyFile: (src, dst, callback) ->
  149. # copy output file into the cache
  150. fse.copy src, dst, (err) ->
  151. if err?.code is 'ENOENT'
  152. logger.warn err: err, file: src, "file has disappeared when copying to build cache"
  153. callback(err, false)
  154. else if err?
  155. logger.error err: err, src: src, dst: dst, "copy error for file in cache"
  156. callback(err)
  157. else
  158. # call the optimiser for the file too
  159. OutputFileOptimiser.optimiseFile src, dst, callback
  160. _checkIfShouldCopy: (src, callback = (err, shouldCopy) ->) ->
  161. return callback(null, !Path.basename(src).match(/^strace/))
  162. _checkIfShouldArchive: (src, callback = (err, shouldCopy) ->) ->
  163. if Path.basename(src).match(/^strace/)
  164. return callback(null, true)
  165. if Settings.clsi?.archive_logs and Path.basename(src) in ["output.log", "output.blg"]
  166. return callback(null, true)
  167. return callback(null, false)