LockManager.coffee 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. metrics = require('./Metrics')
  2. Settings = require('settings-sharelatex')
  3. redis = require("redis-sharelatex")
  4. rclient = redis.createClient(Settings.redis.lock)
  5. keys = Settings.redis.lock.key_schema
  6. logger = require "logger-sharelatex"
  7. os = require "os"
  8. crypto = require "crypto"
  9. Profiler = require "./Profiler"
  10. HOST = os.hostname()
  11. PID = process.pid
  12. RND = crypto.randomBytes(4).toString('hex')
  13. COUNT = 0
  14. MAX_REDIS_REQUEST_LENGTH = 5000 # 5 seconds
  15. module.exports = LockManager =
  16. LOCK_TEST_INTERVAL: 50 # 50ms between each test of the lock
  17. MAX_TEST_INTERVAL: 1000 # back off to 1s between each test of the lock
  18. MAX_LOCK_WAIT_TIME: 10000 # 10s maximum time to spend trying to get the lock
  19. LOCK_TTL: 30 # seconds. Time until lock auto expires in redis.
  20. # Use a signed lock value as described in
  21. # http://redis.io/topics/distlock#correct-implementation-with-a-single-instance
  22. # to prevent accidental unlocking by multiple processes
  23. randomLock : () ->
  24. time = Date.now()
  25. return "locked:host=#{HOST}:pid=#{PID}:random=#{RND}:time=#{time}:count=#{COUNT++}"
  26. unlockScript: 'if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("del", KEYS[1]) else return 0 end';
  27. tryLock : (doc_id, callback = (err, isFree)->)->
  28. lockValue = LockManager.randomLock()
  29. key = keys.blockingKey(doc_id:doc_id)
  30. profile = new Profiler("tryLock", {doc_id, key, lockValue})
  31. rclient.set key, lockValue, "EX", @LOCK_TTL, "NX", (err, gotLock)->
  32. return callback(err) if err?
  33. if gotLock == "OK"
  34. metrics.inc "doc-not-blocking"
  35. timeTaken = profile.log("got lock").end()
  36. if timeTaken > MAX_REDIS_REQUEST_LENGTH
  37. # took too long, so try to free the lock
  38. LockManager.releaseLock doc_id, lockValue, (err, result) ->
  39. return callback(err) if err? # error freeing lock
  40. callback null, false # tell caller they didn't get the lock
  41. else
  42. callback null, true, lockValue
  43. else
  44. metrics.inc "doc-blocking"
  45. profile.log("doc is locked").end()
  46. callback null, false
  47. getLock: (doc_id, callback = (error, lockValue) ->) ->
  48. startTime = Date.now()
  49. testInterval = LockManager.LOCK_TEST_INTERVAL
  50. profile = new Profiler("getLock", {doc_id})
  51. do attempt = () ->
  52. if Date.now() - startTime > LockManager.MAX_LOCK_WAIT_TIME
  53. e = new Error("Timeout")
  54. e.doc_id = doc_id
  55. profile.log("timeout").end()
  56. return callback(e)
  57. LockManager.tryLock doc_id, (error, gotLock, lockValue) ->
  58. return callback(error) if error?
  59. profile.log("tryLock")
  60. if gotLock
  61. profile.end()
  62. callback(null, lockValue)
  63. else
  64. setTimeout attempt, testInterval
  65. # back off when the lock is taken to avoid overloading
  66. testInterval = Math.min(testInterval * 2, LockManager.MAX_TEST_INTERVAL)
  67. checkLock: (doc_id, callback = (err, isFree)->)->
  68. key = keys.blockingKey(doc_id:doc_id)
  69. rclient.exists key, (err, exists) ->
  70. return callback(err) if err?
  71. exists = parseInt exists
  72. if exists == 1
  73. metrics.inc "doc-blocking"
  74. callback null, false
  75. else
  76. metrics.inc "doc-not-blocking"
  77. callback null, true
  78. releaseLock: (doc_id, lockValue, callback)->
  79. key = keys.blockingKey(doc_id:doc_id)
  80. profile = new Profiler("releaseLock", {doc_id, key, lockValue})
  81. rclient.eval LockManager.unlockScript, 1, key, lockValue, (err, result) ->
  82. if err?
  83. return callback(err)
  84. else if result? and result isnt 1 # successful unlock should release exactly one key
  85. profile.log("unlockScript:expired-lock").end()
  86. logger.error {doc_id:doc_id, key:key, lockValue:lockValue, redis_err:err, redis_result:result}, "unlocking error"
  87. metrics.inc "unlock-error"
  88. return callback(new Error("tried to release timed out lock"))
  89. else
  90. profile.log("unlockScript:ok").end()
  91. callback(null,result)