LockManager.coffee 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. metrics = require('./Metrics')
  2. Settings = require('settings-sharelatex')
  3. rclient = require("./RedisBackend").createClient()
  4. keys = require('./RedisKeyBuilder')
  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_LOCK_WAIT_TIME: 10000 # 10s maximum time to spend trying to get the lock
  15. LOCK_TTL: 30 # seconds. Time until lock auto expires in redis.
  16. # Use a signed lock value as described in
  17. # http://redis.io/topics/distlock#correct-implementation-with-a-single-instance
  18. # to prevent accidental unlocking by multiple processes
  19. randomLock : () ->
  20. time = Date.now()
  21. return "locked:host=#{HOST}:pid=#{PID}:random=#{RND}:time=#{time}:count=#{COUNT++}"
  22. unlockScript: 'if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("del", KEYS[1]) else return 0 end';
  23. tryLock : (doc_id, callback = (err, isFree)->)->
  24. lockValue = LockManager.randomLock()
  25. key = keys.blockingKey(doc_id:doc_id)
  26. rclient.set key, lockValue, "EX", @LOCK_TTL, "NX", (err, gotLock)->
  27. return callback(err) if err?
  28. if gotLock == "OK"
  29. metrics.inc "doc-not-blocking"
  30. callback err, true, lockValue
  31. else
  32. metrics.inc "doc-blocking"
  33. logger.log {doc_id}, "doc is locked"
  34. callback err, false
  35. getLock: (doc_id, callback = (error) ->) ->
  36. startTime = Date.now()
  37. do attempt = () ->
  38. if Date.now() - startTime > LockManager.MAX_LOCK_WAIT_TIME
  39. e = new Error("Timeout")
  40. e.doc_id = doc_id
  41. return callback(e)
  42. LockManager.tryLock doc_id, (error, gotLock, lockValue) ->
  43. return callback(error) if error?
  44. if gotLock
  45. callback(null, lockValue)
  46. else
  47. setTimeout attempt, LockManager.LOCK_TEST_INTERVAL
  48. checkLock: (doc_id, callback = (err, isFree)->)->
  49. key = keys.blockingKey(doc_id:doc_id)
  50. rclient.exists key, (err, exists) ->
  51. return callback(err) if err?
  52. exists = parseInt exists
  53. if exists == 1
  54. metrics.inc "doc-blocking"
  55. callback err, false
  56. else
  57. metrics.inc "doc-not-blocking"
  58. callback err, true
  59. releaseLock: (doc_id, lockValue, callback)->
  60. key = keys.blockingKey(doc_id:doc_id)
  61. rclient.eval LockManager.unlockScript, 1, key, lockValue, callback