2016-10-27 08:59:52 -04:00
|
|
|
require 'securerandom'
|
|
|
|
|
2016-03-10 04:41:16 -05:00
|
|
|
module Gitlab
|
|
|
|
# This class implements an 'exclusive lease'. We call it a 'lease'
|
|
|
|
# because it has a set expiry time. We call it 'exclusive' because only
|
|
|
|
# one caller may obtain a lease for a given key at a time. The
|
|
|
|
# implementation is intended to work across GitLab processes and across
|
2016-10-27 08:59:52 -04:00
|
|
|
# servers. It is a cheap alternative to using SQL queries and updates:
|
2016-03-10 04:41:16 -05:00
|
|
|
# you do not need to change the SQL schema to start using
|
|
|
|
# ExclusiveLease.
|
2016-03-10 06:37:14 -05:00
|
|
|
#
|
2016-03-10 04:41:16 -05:00
|
|
|
class ExclusiveLease
|
2017-02-21 18:32:18 -05:00
|
|
|
LUA_CANCEL_SCRIPT = <<-EOS.freeze
|
2016-10-27 08:59:52 -04:00
|
|
|
local key, uuid = KEYS[1], ARGV[1]
|
|
|
|
if redis.call("get", key) == uuid then
|
|
|
|
redis.call("del", key)
|
|
|
|
end
|
|
|
|
EOS
|
|
|
|
|
|
|
|
def self.cancel(key, uuid)
|
|
|
|
Gitlab::Redis.with do |redis|
|
|
|
|
redis.eval(LUA_CANCEL_SCRIPT, keys: [redis_key(key)], argv: [uuid])
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def self.redis_key(key)
|
|
|
|
"gitlab:exclusive_lease:#{key}"
|
|
|
|
end
|
|
|
|
|
2016-03-10 06:37:14 -05:00
|
|
|
def initialize(key, timeout:)
|
2016-10-27 08:59:52 -04:00
|
|
|
@redis_key = self.class.redis_key(key)
|
|
|
|
@timeout = timeout
|
|
|
|
@uuid = SecureRandom.uuid
|
2016-03-10 04:41:16 -05:00
|
|
|
end
|
|
|
|
|
2016-10-27 08:59:52 -04:00
|
|
|
# Try to obtain the lease. Return lease UUID on success,
|
2016-03-10 04:41:16 -05:00
|
|
|
# false if the lease is already taken.
|
|
|
|
def try_obtain
|
2016-03-10 12:39:50 -05:00
|
|
|
# Performing a single SET is atomic
|
2016-03-16 13:10:03 -04:00
|
|
|
Gitlab::Redis.with do |redis|
|
2016-10-27 08:59:52 -04:00
|
|
|
redis.set(@redis_key, @uuid, nx: true, ex: @timeout) && @uuid
|
2016-03-16 13:10:03 -04:00
|
|
|
end
|
2016-03-10 04:41:16 -05:00
|
|
|
end
|
|
|
|
|
2016-10-25 10:01:24 -04:00
|
|
|
# Returns true if the key for this lease is set.
|
|
|
|
def exists?
|
|
|
|
Gitlab::Redis.with do |redis|
|
2016-10-27 08:59:52 -04:00
|
|
|
redis.exists(@redis_key)
|
2016-10-25 10:01:24 -04:00
|
|
|
end
|
|
|
|
end
|
2016-03-10 04:41:16 -05:00
|
|
|
end
|
|
|
|
end
|