OutputCacheManager.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. /*
  2. * decaffeinate suggestions:
  3. * DS101: Remove unnecessary use of Array.from
  4. * DS102: Remove unnecessary code created because of implicit returns
  5. * DS103: Rewrite code to no longer use __guard__
  6. * DS104: Avoid inline assignments
  7. * DS204: Change includes calls to have a more natural evaluation order
  8. * DS207: Consider shorter variations of null checks
  9. * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
  10. */
  11. let OutputCacheManager;
  12. const async = require("async");
  13. const fs = require("fs");
  14. const fse = require("fs-extra");
  15. const Path = require("path");
  16. const logger = require("logger-sharelatex");
  17. const _ = require("underscore");
  18. const Settings = require("settings-sharelatex");
  19. const crypto = require("crypto");
  20. const OutputFileOptimiser = require("./OutputFileOptimiser");
  21. module.exports = (OutputCacheManager = {
  22. CACHE_SUBDIR: '.cache/clsi',
  23. ARCHIVE_SUBDIR: '.archive/clsi',
  24. // build id is HEXDATE-HEXRANDOM from Date.now()and RandomBytes
  25. // for backwards compatibility, make the randombytes part optional
  26. BUILD_REGEX: /^[0-9a-f]+(-[0-9a-f]+)?$/,
  27. CACHE_LIMIT: 2, // maximum number of cache directories
  28. CACHE_AGE: 60*60*1000, // up to one hour old
  29. path(buildId, file) {
  30. // used by static server, given build id return '.cache/clsi/buildId'
  31. if (buildId.match(OutputCacheManager.BUILD_REGEX)) {
  32. return Path.join(OutputCacheManager.CACHE_SUBDIR, buildId, file);
  33. } else {
  34. // for invalid build id, return top level
  35. return file;
  36. }
  37. },
  38. generateBuildId(callback) {
  39. // generate a secure build id from Date.now() and 8 random bytes in hex
  40. if (callback == null) { callback = function(error, buildId) {}; }
  41. return crypto.randomBytes(8, function(err, buf) {
  42. if (err != null) { return callback(err); }
  43. const random = buf.toString('hex');
  44. const date = Date.now().toString(16);
  45. return callback(err, `${date}-${random}`);
  46. });
  47. },
  48. saveOutputFiles(outputFiles, compileDir, callback) {
  49. if (callback == null) { callback = function(error) {}; }
  50. return OutputCacheManager.generateBuildId(function(err, buildId) {
  51. if (err != null) { return callback(err); }
  52. return OutputCacheManager.saveOutputFilesInBuildDir(outputFiles, compileDir, buildId, callback);
  53. });
  54. },
  55. saveOutputFilesInBuildDir(outputFiles, compileDir, buildId, callback) {
  56. // make a compileDir/CACHE_SUBDIR/build_id directory and
  57. // copy all the output files into it
  58. if (callback == null) { callback = function(error) {}; }
  59. const cacheRoot = Path.join(compileDir, OutputCacheManager.CACHE_SUBDIR);
  60. // Put the files into a new cache subdirectory
  61. const cacheDir = Path.join(compileDir, OutputCacheManager.CACHE_SUBDIR, buildId);
  62. // Is it a per-user compile? check if compile directory is PROJECTID-USERID
  63. const perUser = Path.basename(compileDir).match(/^[0-9a-f]{24}-[0-9a-f]{24}$/);
  64. // Archive logs in background
  65. if ((Settings.clsi != null ? Settings.clsi.archive_logs : undefined) || (Settings.clsi != null ? Settings.clsi.strace : undefined)) {
  66. OutputCacheManager.archiveLogs(outputFiles, compileDir, buildId, function(err) {
  67. if (err != null) {
  68. return logger.warn({err}, "erroring archiving log files");
  69. }
  70. });
  71. }
  72. // make the new cache directory
  73. return fse.ensureDir(cacheDir, function(err) {
  74. if (err != null) {
  75. logger.error({err, directory: cacheDir}, "error creating cache directory");
  76. return callback(err, outputFiles);
  77. } else {
  78. // copy all the output files into the new cache directory
  79. const results = [];
  80. return async.mapSeries(outputFiles, function(file, cb) {
  81. // don't send dot files as output, express doesn't serve them
  82. if (OutputCacheManager._fileIsHidden(file.path)) {
  83. logger.debug({compileDir, path: file.path}, "ignoring dotfile in output");
  84. return cb();
  85. }
  86. // copy other files into cache directory if valid
  87. const newFile = _.clone(file);
  88. const [src, dst] = Array.from([Path.join(compileDir, file.path), Path.join(cacheDir, file.path)]);
  89. return OutputCacheManager._checkFileIsSafe(src, function(err, isSafe) {
  90. if (err != null) { return cb(err); }
  91. if (!isSafe) {
  92. return cb();
  93. }
  94. return OutputCacheManager._checkIfShouldCopy(src, function(err, shouldCopy) {
  95. if (err != null) { return cb(err); }
  96. if (!shouldCopy) {
  97. return cb();
  98. }
  99. return OutputCacheManager._copyFile(src, dst, function(err) {
  100. if (err != null) { return cb(err); }
  101. newFile.build = buildId; // attach a build id if we cached the file
  102. results.push(newFile);
  103. return cb();
  104. });
  105. });
  106. });
  107. }
  108. , function(err) {
  109. if (err != null) {
  110. // pass back the original files if we encountered *any* error
  111. callback(err, outputFiles);
  112. // clean up the directory we just created
  113. return fse.remove(cacheDir, function(err) {
  114. if (err != null) {
  115. return logger.error({err, dir: cacheDir}, "error removing cache dir after failure");
  116. }
  117. });
  118. } else {
  119. // pass back the list of new files in the cache
  120. callback(err, results);
  121. // let file expiry run in the background, expire all previous files if per-user
  122. return OutputCacheManager.expireOutputFiles(cacheRoot, {keep: buildId, limit: perUser ? 1 : null});
  123. }
  124. });
  125. }
  126. });
  127. },
  128. archiveLogs(outputFiles, compileDir, buildId, callback) {
  129. if (callback == null) { callback = function(error) {}; }
  130. const archiveDir = Path.join(compileDir, OutputCacheManager.ARCHIVE_SUBDIR, buildId);
  131. logger.log({dir: archiveDir}, "archiving log files for project");
  132. return fse.ensureDir(archiveDir, function(err) {
  133. if (err != null) { return callback(err); }
  134. return async.mapSeries(outputFiles, function(file, cb) {
  135. const [src, dst] = Array.from([Path.join(compileDir, file.path), Path.join(archiveDir, file.path)]);
  136. return OutputCacheManager._checkFileIsSafe(src, function(err, isSafe) {
  137. if (err != null) { return cb(err); }
  138. if (!isSafe) { return cb(); }
  139. return OutputCacheManager._checkIfShouldArchive(src, function(err, shouldArchive) {
  140. if (err != null) { return cb(err); }
  141. if (!shouldArchive) { return cb(); }
  142. return OutputCacheManager._copyFile(src, dst, cb);
  143. });
  144. });
  145. }
  146. , callback);
  147. });
  148. },
  149. expireOutputFiles(cacheRoot, options, callback) {
  150. // look in compileDir for build dirs and delete if > N or age of mod time > T
  151. if (callback == null) { callback = function(error) {}; }
  152. return fs.readdir(cacheRoot, function(err, results) {
  153. if (err != null) {
  154. if (err.code === 'ENOENT') { return callback(null); } // cache directory is empty
  155. logger.error({err, project_id: cacheRoot}, "error clearing cache");
  156. return callback(err);
  157. }
  158. const dirs = results.sort().reverse();
  159. const currentTime = Date.now();
  160. const isExpired = function(dir, index) {
  161. if ((options != null ? options.keep : undefined) === dir) { return false; }
  162. // remove any directories over the requested (non-null) limit
  163. if (((options != null ? options.limit : undefined) != null) && (index > options.limit)) { return true; }
  164. // remove any directories over the hard limit
  165. if (index > OutputCacheManager.CACHE_LIMIT) { return true; }
  166. // we can get the build time from the first part of the directory name DDDD-RRRR
  167. // DDDD is date and RRRR is random bytes
  168. const dirTime = parseInt(__guard__(dir.split('-'), x => x[0]), 16);
  169. const age = currentTime - dirTime;
  170. return age > OutputCacheManager.CACHE_AGE;
  171. };
  172. const toRemove = _.filter(dirs, isExpired);
  173. const removeDir = (dir, cb) =>
  174. fse.remove(Path.join(cacheRoot, dir), function(err, result) {
  175. logger.log({cache: cacheRoot, dir}, "removed expired cache dir");
  176. if (err != null) {
  177. logger.error({err, dir}, "cache remove error");
  178. }
  179. return cb(err, result);
  180. })
  181. ;
  182. return async.eachSeries(toRemove, (dir, cb) => removeDir(dir, cb)
  183. , callback);
  184. });
  185. },
  186. _fileIsHidden(path) {
  187. return ((path != null ? path.match(/^\.|\/\./) : undefined) != null);
  188. },
  189. _checkFileIsSafe(src, callback) {
  190. // check if we have a valid file to copy into the cache
  191. if (callback == null) { callback = function(error, isSafe) {}; }
  192. return fs.stat(src, function(err, stats) {
  193. if ((err != null ? err.code : undefined) === 'ENOENT') {
  194. logger.warn({err, file: src}, "file has disappeared before copying to build cache");
  195. return callback(err, false);
  196. } else if (err != null) {
  197. // some other problem reading the file
  198. logger.error({err, file: src}, "stat error for file in cache");
  199. return callback(err, false);
  200. } else if (!stats.isFile()) {
  201. // other filetype - reject it
  202. logger.warn({src, stat: stats}, "nonfile output - refusing to copy to cache");
  203. return callback(null, false);
  204. } else {
  205. // it's a plain file, ok to copy
  206. return callback(null, true);
  207. }
  208. });
  209. },
  210. _copyFile(src, dst, callback) {
  211. // copy output file into the cache
  212. return fse.copy(src, dst, function(err) {
  213. if ((err != null ? err.code : undefined) === 'ENOENT') {
  214. logger.warn({err, file: src}, "file has disappeared when copying to build cache");
  215. return callback(err, false);
  216. } else if (err != null) {
  217. logger.error({err, src, dst}, "copy error for file in cache");
  218. return callback(err);
  219. } else {
  220. if ((Settings.clsi != null ? Settings.clsi.optimiseInDocker : undefined)) {
  221. // don't run any optimisations on the pdf when they are done
  222. // in the docker container
  223. return callback();
  224. } else {
  225. // call the optimiser for the file too
  226. return OutputFileOptimiser.optimiseFile(src, dst, callback);
  227. }
  228. }
  229. });
  230. },
  231. _checkIfShouldCopy(src, callback) {
  232. if (callback == null) { callback = function(err, shouldCopy) {}; }
  233. return callback(null, !Path.basename(src).match(/^strace/));
  234. },
  235. _checkIfShouldArchive(src, callback) {
  236. let needle;
  237. if (callback == null) { callback = function(err, shouldCopy) {}; }
  238. if (Path.basename(src).match(/^strace/)) {
  239. return callback(null, true);
  240. }
  241. if ((Settings.clsi != null ? Settings.clsi.archive_logs : undefined) && (needle = Path.basename(src), ["output.log", "output.blg"].includes(needle))) {
  242. return callback(null, true);
  243. }
  244. return callback(null, false);
  245. }
  246. });
  247. function __guard__(value, transform) {
  248. return (typeof value !== 'undefined' && value !== null) ? transform(value) : undefined;
  249. }