2018-07-16 12:31:01 -04:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2018-05-03 10:19:21 -04:00
|
|
|
#
|
|
|
|
# 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-01-10 09:22:58 -05:00
|
|
|
# for the exclusive lease.
|
|
|
|
#
|
|
|
|
# Optionally override `#lease_key` to set the
|
2018-05-03 10:19:21 -04:00
|
|
|
# lease key, it defaults to the class name with underscores.
|
|
|
|
#
|
2019-01-10 09:22:58 -05:00
|
|
|
# Optionally override `#lease_release?` to prevent the job to
|
|
|
|
# be re-executed more often than LEASE_TIMEOUT.
|
|
|
|
#
|
2018-05-03 10:19:21 -04:00
|
|
|
module ExclusiveLeaseGuard
|
|
|
|
extend ActiveSupport::Concern
|
|
|
|
|
|
|
|
def try_obtain_lease
|
|
|
|
lease = exclusive_lease.try_obtain
|
|
|
|
|
|
|
|
unless lease
|
2020-06-29 11:08:56 -04:00
|
|
|
log_error("Cannot obtain an exclusive lease for #{self.class.name}. There must be another instance already in execution.")
|
2018-05-03 10:19:21 -04:00
|
|
|
return
|
|
|
|
end
|
|
|
|
|
|
|
|
begin
|
|
|
|
yield lease
|
|
|
|
ensure
|
2019-01-10 09:22:58 -05:00
|
|
|
release_lease(lease) if lease_release?
|
2018-05-03 10:19:21 -04:00
|
|
|
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-02-06 07:41:17 -05:00
|
|
|
"#{self.class.name} does not implement #{__method__}"
|
2018-05-03 10:19:21 -04:00
|
|
|
end
|
|
|
|
|
2019-01-10 09:22:58 -05:00
|
|
|
def lease_release?
|
|
|
|
true
|
|
|
|
end
|
|
|
|
|
2018-05-03 10:19:21 -04:00
|
|
|
def release_lease(uuid)
|
|
|
|
Gitlab::ExclusiveLease.cancel(lease_key, uuid)
|
|
|
|
end
|
|
|
|
|
|
|
|
def renew_lease!
|
|
|
|
exclusive_lease.renew
|
|
|
|
end
|
|
|
|
|
|
|
|
def log_error(message, extra_args = {})
|
2020-05-21 17:08:31 -04:00
|
|
|
Gitlab::AppLogger.error(message)
|
2018-05-03 10:19:21 -04:00
|
|
|
end
|
|
|
|
end
|