LockManager.js 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  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. * DS102: Remove unnecessary code created because of implicit returns
  9. * DS207: Consider shorter variations of null checks
  10. * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
  11. */
  12. let LockManager;
  13. const Settings = require("settings-sharelatex");
  14. const redis = require("redis-sharelatex");
  15. const rclient = redis.createClient(Settings.redis.lock);
  16. const os = require("os");
  17. const crypto = require("crypto");
  18. const logger = require("logger-sharelatex");
  19. const HOST = os.hostname();
  20. const PID = process.pid;
  21. const RND = crypto.randomBytes(4).toString('hex');
  22. let COUNT = 0;
  23. module.exports = (LockManager = {
  24. LOCK_TEST_INTERVAL: 50, // 50ms between each test of the lock
  25. MAX_LOCK_WAIT_TIME: 10000, // 10s maximum time to spend trying to get the lock
  26. LOCK_TTL: 300, // seconds (allow 5 minutes for any operation to complete)
  27. // Use a signed lock value as described in
  28. // http://redis.io/topics/distlock#correct-implementation-with-a-single-instance
  29. // to prevent accidental unlocking by multiple processes
  30. randomLock() {
  31. const time = Date.now();
  32. return `locked:host=${HOST}:pid=${PID}:random=${RND}:time=${time}:count=${COUNT++}`;
  33. },
  34. unlockScript: 'if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("del", KEYS[1]) else return 0 end',
  35. tryLock(key, callback) {
  36. if (callback == null) { callback = function(err, gotLock) {}; }
  37. const lockValue = LockManager.randomLock();
  38. return rclient.set(key, lockValue, "EX", this.LOCK_TTL, "NX", function(err, gotLock){
  39. if (err != null) { return callback(err); }
  40. if (gotLock === "OK") {
  41. return callback(err, true, lockValue);
  42. } else {
  43. return callback(err, false);
  44. }
  45. });
  46. },
  47. getLock(key, callback) {
  48. let attempt;
  49. if (callback == null) { callback = function(error) {}; }
  50. const startTime = Date.now();
  51. return (attempt = function() {
  52. if ((Date.now() - startTime) > LockManager.MAX_LOCK_WAIT_TIME) {
  53. const e = new Error("Timeout");
  54. e.key = key;
  55. return callback(e);
  56. }
  57. return LockManager.tryLock(key, function(error, gotLock, lockValue) {
  58. if (error != null) { return callback(error); }
  59. if (gotLock) {
  60. return callback(null, lockValue);
  61. } else {
  62. return setTimeout(attempt, LockManager.LOCK_TEST_INTERVAL);
  63. }
  64. });
  65. })();
  66. },
  67. checkLock(key, callback) {
  68. if (callback == null) { callback = function(err, isFree) {}; }
  69. return rclient.exists(key, function(err, exists) {
  70. if (err != null) { return callback(err); }
  71. exists = parseInt(exists);
  72. if (exists === 1) {
  73. return callback(err, false);
  74. } else {
  75. return callback(err, true);
  76. }
  77. });
  78. },
  79. releaseLock(key, lockValue, callback) {
  80. return rclient.eval(LockManager.unlockScript, 1, key, lockValue, function(err, result) {
  81. if (err != null) {
  82. return callback(err);
  83. }
  84. if ((result != null) && (result !== 1)) { // successful unlock should release exactly one key
  85. logger.error({key, lockValue, redis_err:err, redis_result:result}, "unlocking error");
  86. return callback(new Error("tried to release timed out lock"));
  87. }
  88. return callback(err,result);
  89. });
  90. },
  91. runWithLock(key, runner, callback) {
  92. if (callback == null) { callback = function(error) {}; }
  93. return LockManager.getLock(key, function(error, lockValue) {
  94. if (error != null) { return callback(error); }
  95. return runner(error1 =>
  96. LockManager.releaseLock(key, lockValue, function(error2) {
  97. error = error1 || error2;
  98. if (error != null) { return callback(error); }
  99. return callback();
  100. })
  101. );
  102. });
  103. },
  104. healthCheck(callback) {
  105. const action = releaseLock => releaseLock();
  106. return LockManager.runWithLock(`HistoryLock:HealthCheck:host=${HOST}:pid=${PID}:random=${RND}`, action, callback);
  107. },
  108. close(callback) {
  109. rclient.quit();
  110. return rclient.once('end', callback);
  111. }
  112. });