2014-04-11 13:43:33 +08:00
|
|
|
# Cross-process locking using Redis.
|
|
|
|
class DistributedMutex
|
2019-02-20 09:23:42 +08:00
|
|
|
DEFAULT_VALIDITY = 60
|
2014-04-11 13:43:33 +08:00
|
|
|
|
2019-02-20 09:23:42 +08:00
|
|
|
def self.synchronize(key, redis: nil, validity: DEFAULT_VALIDITY, &blk)
|
2019-02-20 09:28:10 +08:00
|
|
|
self.new(
|
|
|
|
key,
|
|
|
|
redis: redis,
|
|
|
|
validity: validity
|
|
|
|
).synchronize(&blk)
|
2014-07-30 12:04:27 +08:00
|
|
|
end
|
|
|
|
|
2019-02-20 09:28:10 +08:00
|
|
|
def initialize(key, redis: nil, validity: DEFAULT_VALIDITY)
|
2014-04-11 13:43:33 +08:00
|
|
|
@key = key
|
2018-09-19 13:49:18 +08:00
|
|
|
@using_global_redis = true if !redis
|
2014-04-11 13:43:33 +08:00
|
|
|
@redis = redis || $redis
|
2014-04-14 08:51:46 +08:00
|
|
|
@mutex = Mutex.new
|
2019-02-20 09:28:10 +08:00
|
|
|
@validity = validity
|
2014-04-11 13:43:33 +08:00
|
|
|
end
|
|
|
|
|
2018-09-19 13:49:18 +08:00
|
|
|
CHECK_READONLY_ATTEMPT ||= 10
|
|
|
|
|
2014-04-14 08:51:46 +08:00
|
|
|
# NOTE wrapped in mutex to maintain its semantics
|
2019-02-20 09:28:10 +08:00
|
|
|
def synchronize
|
2014-04-14 08:51:46 +08:00
|
|
|
@mutex.lock
|
2018-09-19 13:49:18 +08:00
|
|
|
attempts = 0
|
|
|
|
|
2019-02-20 09:28:10 +08:00
|
|
|
while !try_to_get_lock
|
2014-04-14 08:51:46 +08:00
|
|
|
sleep 0.001
|
2018-09-19 13:49:18 +08:00
|
|
|
# in readonly we will never be able to get a lock
|
2018-09-20 13:15:29 +08:00
|
|
|
if @using_global_redis && Discourse.recently_readonly?
|
2018-09-19 14:07:29 +08:00
|
|
|
attempts += 1
|
2019-02-20 09:23:42 +08:00
|
|
|
|
2018-09-19 14:07:29 +08:00
|
|
|
if attempts > CHECK_READONLY_ATTEMPT
|
|
|
|
raise Discourse::ReadOnly
|
|
|
|
end
|
2018-09-19 13:49:18 +08:00
|
|
|
end
|
2014-04-14 08:51:46 +08:00
|
|
|
end
|
|
|
|
|
|
|
|
yield
|
|
|
|
|
|
|
|
ensure
|
|
|
|
@redis.del @key
|
|
|
|
@mutex.unlock
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
2019-02-20 09:28:10 +08:00
|
|
|
def try_to_get_lock
|
2014-04-14 08:51:46 +08:00
|
|
|
got_lock = false
|
2019-02-20 09:23:42 +08:00
|
|
|
|
2019-02-20 09:28:10 +08:00
|
|
|
if @redis.setnx @key, Time.now.to_i + @validity
|
|
|
|
@redis.expire @key, @validity
|
2014-04-14 08:51:46 +08:00
|
|
|
got_lock = true
|
2014-04-11 13:43:33 +08:00
|
|
|
else
|
|
|
|
begin
|
2014-04-14 08:51:46 +08:00
|
|
|
@redis.watch @key
|
|
|
|
time = @redis.get @key
|
2019-02-20 09:23:42 +08:00
|
|
|
|
2014-04-11 13:43:33 +08:00
|
|
|
if time && time.to_i < Time.now.to_i
|
2014-04-14 08:51:46 +08:00
|
|
|
got_lock = @redis.multi do
|
2019-02-20 09:28:10 +08:00
|
|
|
@redis.set @key, Time.now.to_i + @validity
|
2014-04-11 13:43:33 +08:00
|
|
|
end
|
|
|
|
end
|
|
|
|
ensure
|
2014-04-14 08:51:46 +08:00
|
|
|
@redis.unwatch
|
2014-04-11 13:43:33 +08:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2014-04-14 08:51:46 +08:00
|
|
|
got_lock
|
2014-04-11 13:43:33 +08:00
|
|
|
end
|
|
|
|
|
|
|
|
end
|