LockManager.coffee 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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. HOST = os.hostname()
  9. PID = process.pid
  10. RND = crypto.randomBytes(4).toString('hex')
  11. COUNT = 0
  12. module.exports = LockManager =
  13. LOCK_TEST_INTERVAL: 50 # 50ms between each test of the lock
  14. MAX_TEST_INTERVAL: 1000 # back off to 1s between each test of the lock
  15. MAX_LOCK_WAIT_TIME: 10000 # 10s maximum time to spend trying to get the lock
  16. REDIS_LOCK_EXPIRY: 30 # seconds. Time until lock auto expires in redis
  17. SLOW_EXECUTION_THRESHOLD: 5000 # 5s, if execution takes longer than this then log
  18. # Use a signed lock value as described in
  19. # http://redis.io/topics/distlock#correct-implementation-with-a-single-instance
  20. # to prevent accidental unlocking by multiple processes
  21. randomLock : () ->
  22. time = Date.now()
  23. return "locked:host=#{HOST}:pid=#{PID}:random=#{RND}:time=#{time}:count=#{COUNT++}"
  24. unlockScript: 'if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("del", KEYS[1]) else return 0 end'
  25. runWithLock: (namespace, id, runner = ( (releaseLock = (error) ->) -> ), callback = ( (error) -> )) ->
  26. # This error is defined here so we get a useful stacktrace
  27. slowExecutionError = new Error "slow execution during lock"
  28. timer = new metrics.Timer("lock.#{namespace}")
  29. key = "lock:web:#{namespace}:#{id}"
  30. LockManager._getLock key, namespace, (error, lockValue) ->
  31. return callback(error) if error?
  32. # The lock can expire in redis but the process carry on. This setTimout call
  33. # is designed to log if this happens.
  34. countIfExceededLockTimeout = () ->
  35. metrics.inc "lock.#{namespace}.exceeded_lock_timeout"
  36. logger.log "exceeded lock timeout", { namespace, id, slowExecutionError }
  37. exceededLockTimeout = setTimeout countIfExceededLockTimeout, LockManager.REDIS_LOCK_EXPIRY * 1000
  38. runner (error1, values...) ->
  39. LockManager._releaseLock key, lockValue, (error2) ->
  40. clearTimeout exceededLockTimeout
  41. timeTaken = new Date - timer.start
  42. if timeTaken > LockManager.SLOW_EXECUTION_THRESHOLD
  43. logger.log "slow execution during lock", { namespace, id, timeTaken, slowExecutionError }
  44. timer.done()
  45. error = error1 or error2
  46. return callback(error) if error?
  47. callback null, values...
  48. _tryLock : (key, namespace, callback = (err, isFree, lockValue)->)->
  49. lockValue = LockManager.randomLock()
  50. rclient.set key, lockValue, "EX", LockManager.REDIS_LOCK_EXPIRY, "NX", (err, gotLock)->
  51. return callback(err) if err?
  52. if gotLock == "OK"
  53. metrics.inc "lock.#{namespace}.try.success"
  54. callback err, true, lockValue
  55. else
  56. metrics.inc "lock.#{namespace}.try.failed"
  57. logger.log key: key, redis_response: gotLock, "lock is locked"
  58. callback err, false
  59. _getLock: (key, namespace, callback = (error, lockValue) ->) ->
  60. startTime = Date.now()
  61. testInterval = LockManager.LOCK_TEST_INTERVAL
  62. attempts = 0
  63. do attempt = () ->
  64. if Date.now() - startTime > LockManager.MAX_LOCK_WAIT_TIME
  65. metrics.inc "lock.#{namespace}.get.failed"
  66. return callback(new Error("Timeout"))
  67. attempts += 1
  68. LockManager._tryLock key, namespace, (error, gotLock, lockValue) ->
  69. return callback(error) if error?
  70. if gotLock
  71. metrics.gauge "lock.#{namespace}.get.success.tries", attempts
  72. callback(null, lockValue)
  73. else
  74. setTimeout attempt, testInterval
  75. # back off when the lock is taken to avoid overloading
  76. testInterval = Math.min(testInterval * 2, LockManager.MAX_TEST_INTERVAL)
  77. _releaseLock: (key, lockValue, callback)->
  78. rclient.eval LockManager.unlockScript, 1, key, lockValue, (err, result) ->
  79. if err?
  80. return callback(err)
  81. else if result? and result isnt 1 # successful unlock should release exactly one key
  82. logger.error {key:key, lockValue:lockValue, redis_err:err, redis_result:result}, "unlocking error"
  83. metrics.inc "unlock-error"
  84. return callback(new Error("tried to release timed out lock"))
  85. else
  86. callback(null,result)