2018-11-18 11:00:15 +05:30
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2018-10-15 14:42:47 +05:30
|
|
|
#
|
|
|
|
# Concern that helps with getting an exclusive lease for running a block
|
|
|
|
# of code.
|
|
|
|
#
|
|
|
|
# `#try_obtain_lease` takes a block which will be run if it was able to
|
|
|
|
# obtain the lease. Implement `#lease_timeout` to configure the timeout
|
2019-03-02 22:35:43 +05:30
|
|
|
# for the exclusive lease.
|
|
|
|
#
|
|
|
|
# Optionally override `#lease_key` to set the
|
2018-10-15 14:42:47 +05:30
|
|
|
# lease key, it defaults to the class name with underscores.
|
|
|
|
#
|
2019-03-02 22:35:43 +05:30
|
|
|
# Optionally override `#lease_release?` to prevent the job to
|
|
|
|
# be re-executed more often than LEASE_TIMEOUT.
|
|
|
|
#
|
2018-10-15 14:42:47 +05:30
|
|
|
module ExclusiveLeaseGuard
|
|
|
|
extend ActiveSupport::Concern
|
|
|
|
|
|
|
|
def try_obtain_lease
|
|
|
|
lease = exclusive_lease.try_obtain
|
|
|
|
|
|
|
|
unless lease
|
2023-07-09 08:55:56 +05:30
|
|
|
log_lease_taken
|
2018-10-15 14:42:47 +05:30
|
|
|
return
|
|
|
|
end
|
|
|
|
|
|
|
|
begin
|
|
|
|
yield lease
|
|
|
|
ensure
|
2019-03-02 22:35:43 +05:30
|
|
|
release_lease(lease) if lease_release?
|
2018-10-15 14:42:47 +05:30
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def exclusive_lease
|
|
|
|
@lease ||= Gitlab::ExclusiveLease.new(lease_key, timeout: lease_timeout)
|
|
|
|
end
|
|
|
|
|
|
|
|
def lease_key
|
|
|
|
@lease_key ||= self.class.name.underscore
|
|
|
|
end
|
|
|
|
|
|
|
|
def lease_timeout
|
|
|
|
raise NotImplementedError,
|
2019-07-07 11:18:12 +05:30
|
|
|
"#{self.class.name} does not implement #{__method__}"
|
2018-10-15 14:42:47 +05:30
|
|
|
end
|
|
|
|
|
2019-03-02 22:35:43 +05:30
|
|
|
def lease_release?
|
|
|
|
true
|
|
|
|
end
|
|
|
|
|
2018-10-15 14:42:47 +05:30
|
|
|
def release_lease(uuid)
|
|
|
|
Gitlab::ExclusiveLease.cancel(lease_key, uuid)
|
|
|
|
end
|
|
|
|
|
|
|
|
def renew_lease!
|
|
|
|
exclusive_lease.renew
|
|
|
|
end
|
|
|
|
|
2023-07-09 08:55:56 +05:30
|
|
|
def log_lease_taken
|
|
|
|
logger = Gitlab::AppJsonLogger
|
|
|
|
args = { message: lease_taken_message, lease_key: lease_key, class_name: self.class.name, lease_timeout: lease_timeout }
|
|
|
|
|
|
|
|
case lease_taken_log_level
|
|
|
|
when :debug then logger.debug(args)
|
|
|
|
when :info then logger.info(args)
|
|
|
|
when :warn then logger.warn(args)
|
|
|
|
else logger.error(args)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def lease_taken_message
|
|
|
|
"Cannot obtain an exclusive lease. There must be another instance already in execution."
|
|
|
|
end
|
|
|
|
|
|
|
|
def lease_taken_log_level
|
|
|
|
:error
|
2018-10-15 14:42:47 +05:30
|
|
|
end
|
|
|
|
end
|