LockManager.coffee 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. metrics = require('./Metrics')
  2. Settings = require('settings-sharelatex')
  3. redis = require("redis-sharelatex")
  4. rclient = redis.createClient(Settings.redis.web)
  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. keys =
  13. blockingKey: ({doc_id}) -> "Blocking:#{doc_id}"
  14. module.exports = LockManager =
  15. LOCK_TEST_INTERVAL: 50 # 50ms between each test of the lock
  16. MAX_LOCK_WAIT_TIME: 10000 # 10s maximum time to spend trying to get the lock
  17. LOCK_TTL: 30 # seconds. Time until lock auto expires in redis.
  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. tryLock : (doc_id, callback = (err, isFree)->)->
  26. lockValue = LockManager.randomLock()
  27. key = keys.blockingKey(doc_id:doc_id)
  28. rclient.set key, lockValue, "EX", @LOCK_TTL, "NX", (err, gotLock)->
  29. return callback(err) if err?
  30. if gotLock == "OK"
  31. metrics.inc "doc-not-blocking"
  32. callback err, true, lockValue
  33. else
  34. metrics.inc "doc-blocking"
  35. logger.log {doc_id}, "doc is locked"
  36. callback err, false
  37. getLock: (doc_id, callback = (error) ->) ->
  38. startTime = Date.now()
  39. do attempt = () ->
  40. if Date.now() - startTime > LockManager.MAX_LOCK_WAIT_TIME
  41. e = new Error("Timeout")
  42. e.doc_id = doc_id
  43. return callback(e)
  44. LockManager.tryLock doc_id, (error, gotLock, lockValue) ->
  45. return callback(error) if error?
  46. if gotLock
  47. callback(null, lockValue)
  48. else
  49. setTimeout attempt, LockManager.LOCK_TEST_INTERVAL
  50. checkLock: (doc_id, callback = (err, isFree)->)->
  51. key = keys.blockingKey(doc_id:doc_id)
  52. rclient.exists key, (err, exists) ->
  53. return callback(err) if err?
  54. exists = parseInt exists
  55. if exists == 1
  56. metrics.inc "doc-blocking"
  57. callback err, false
  58. else
  59. metrics.inc "doc-not-blocking"
  60. callback err, true
  61. releaseLock: (doc_id, lockValue, callback)->
  62. key = keys.blockingKey(doc_id:doc_id)
  63. rclient.eval LockManager.unlockScript, 1, key, lockValue, callback