LockManager.coffee 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  1. metrics = require('metrics-sharelatex')
  2. Settings = require('settings-sharelatex')
  3. RedisWrapper = require("./RedisWrapper")
  4. rclient = RedisWrapper.client("lock")
  5. logger = require "logger-sharelatex"
  6. os = require "os"
  7. crypto = require "crypto"
  8. async = require "async"
  9. HOST = os.hostname()
  10. PID = process.pid
  11. RND = crypto.randomBytes(4).toString('hex')
  12. COUNT = 0
  13. LOCK_QUEUES = new Map() # queue lock requests for each name/id so they get the lock on a first-come first-served basis
  14. module.exports = LockManager =
  15. LOCK_TEST_INTERVAL: 50 # 50ms between each test of the lock
  16. MAX_TEST_INTERVAL: 1000 # back off to 1s between each test of the lock
  17. MAX_LOCK_WAIT_TIME: 10000 # 10s maximum time to spend trying to get the lock
  18. REDIS_LOCK_EXPIRY: 30 # seconds. Time until lock auto expires in redis
  19. SLOW_EXECUTION_THRESHOLD: 5000 # 5s, if execution takes longer than this then log
  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. runWithLock: (namespace, id, runner = ( (releaseLock = (error) ->) -> ), callback = ( (error) -> )) ->
  28. # This error is defined here so we get a useful stacktrace
  29. slowExecutionError = new Error "slow execution during lock"
  30. timer = new metrics.Timer("lock.#{namespace}")
  31. key = "lock:web:#{namespace}:#{id}"
  32. LockManager._getLock key, namespace, (error, lockValue) ->
  33. return callback(error) if error?
  34. # The lock can expire in redis but the process carry on. This setTimout call
  35. # is designed to log if this happens.
  36. countIfExceededLockTimeout = () ->
  37. metrics.inc "lock.#{namespace}.exceeded_lock_timeout"
  38. logger.log "exceeded lock timeout", { namespace, id, slowExecutionError }
  39. exceededLockTimeout = setTimeout countIfExceededLockTimeout, LockManager.REDIS_LOCK_EXPIRY * 1000
  40. runner (error1, values...) ->
  41. LockManager._releaseLock key, lockValue, (error2) ->
  42. clearTimeout exceededLockTimeout
  43. timeTaken = new Date - timer.start
  44. if timeTaken > LockManager.SLOW_EXECUTION_THRESHOLD
  45. logger.log "slow execution during lock", { namespace, id, timeTaken, slowExecutionError }
  46. timer.done()
  47. error = error1 or error2
  48. return callback(error) if error?
  49. callback null, values...
  50. _tryLock : (key, namespace, callback = (err, isFree, lockValue)->)->
  51. lockValue = LockManager.randomLock()
  52. rclient.set key, lockValue, "EX", LockManager.REDIS_LOCK_EXPIRY, "NX", (err, gotLock)->
  53. return callback(err) if err?
  54. if gotLock == "OK"
  55. metrics.inc "lock.#{namespace}.try.success"
  56. callback err, true, lockValue
  57. else
  58. metrics.inc "lock.#{namespace}.try.failed"
  59. logger.log key: key, redis_response: gotLock, "lock is locked"
  60. callback err, false
  61. # it's sufficient to serialize within a process because that is where the parallel operations occur
  62. _getLock: (key, namespace, callback = (error, lockValue) ->) ->
  63. # this is what we need to do for each lock we want to request
  64. task = (next) ->
  65. LockManager._getLockByPolling key, namespace, (error, lockValue) ->
  66. # tell the queue to start trying to get the next lock (if any)
  67. next()
  68. # we have got a lock result, so we can continue with our own execution
  69. callback(error, lockValue)
  70. # create a queue for this key if needed
  71. queueName = "#{key}:#{namespace}"
  72. queue = LOCK_QUEUES.get queueName
  73. if !queue?
  74. handler = (fn, cb) ->
  75. fn(cb) # execute any function as our task
  76. # set up a new queue for this key
  77. queue = async.queue handler, 1
  78. queue.push task
  79. # remove the queue object when queue is empty
  80. queue.drain = () ->
  81. LOCK_QUEUES.delete queueName
  82. # store the queue in our global map
  83. LOCK_QUEUES.set queueName, queue
  84. else
  85. # queue the request to get the lock
  86. queue.push task
  87. _getLockByPolling: (key, namespace, callback = (error, lockValue) ->) ->
  88. startTime = Date.now()
  89. testInterval = LockManager.LOCK_TEST_INTERVAL
  90. attempts = 0
  91. do attempt = () ->
  92. if Date.now() - startTime > LockManager.MAX_LOCK_WAIT_TIME
  93. metrics.inc "lock.#{namespace}.get.failed"
  94. return callback(new Error("Timeout"))
  95. attempts += 1
  96. LockManager._tryLock key, namespace, (error, gotLock, lockValue) ->
  97. return callback(error) if error?
  98. if gotLock
  99. metrics.gauge "lock.#{namespace}.get.success.tries", attempts
  100. callback(null, lockValue)
  101. else
  102. setTimeout attempt, testInterval
  103. _releaseLock: (key, lockValue, callback)->
  104. rclient.eval LockManager.unlockScript, 1, key, lockValue, (err, result) ->
  105. if err?
  106. return callback(err)
  107. else if result? and result isnt 1 # successful unlock should release exactly one key
  108. logger.error {key:key, lockValue:lockValue, redis_err:err, redis_result:result}, "unlocking error"
  109. metrics.inc "unlock-error"
  110. return callback(new Error("tried to release timed out lock"))
  111. else
  112. callback(null,result)