2021-03-31 00:09:32 +00:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
module Database
|
|
|
|
class BatchedBackgroundMigrationWorker
|
|
|
|
include ApplicationWorker
|
2021-04-30 18:10:09 +00:00
|
|
|
|
2021-07-21 12:09:35 +00:00
|
|
|
data_consistency :always
|
|
|
|
|
2021-03-31 00:09:32 +00:00
|
|
|
include CronjobQueue # rubocop:disable Scalability/CronWorkerContext
|
|
|
|
|
|
|
|
feature_category :database
|
|
|
|
idempotent!
|
|
|
|
|
2021-04-05 21:09:19 +00:00
|
|
|
LEASE_TIMEOUT_MULTIPLIER = 3
|
|
|
|
MINIMUM_LEASE_TIMEOUT = 10.minutes.freeze
|
2021-04-07 09:09:06 +00:00
|
|
|
INTERVAL_VARIANCE = 5.seconds.freeze
|
2021-04-05 21:09:19 +00:00
|
|
|
|
2021-03-31 00:09:32 +00:00
|
|
|
def perform
|
2021-05-18 00:10:37 +00:00
|
|
|
return unless Feature.enabled?(:execute_batched_migrations_on_schedule, type: :ops, default_enabled: :yaml) && active_migration
|
2021-03-31 00:09:32 +00:00
|
|
|
|
|
|
|
with_exclusive_lease(active_migration.interval) do
|
|
|
|
# Now that we have the exclusive lease, reload migration in case another process has changed it.
|
|
|
|
# This is a temporary solution until we have better concurrency handling around job execution
|
|
|
|
#
|
|
|
|
# We also have to disable this cop, because ApplicationRecord aliases reset to reload, but our database
|
|
|
|
# models don't inherit from ApplicationRecord
|
|
|
|
active_migration.reload # rubocop:disable Cop/ActiveRecordAssociationReload
|
|
|
|
|
2021-04-07 09:09:06 +00:00
|
|
|
run_active_migration if active_migration.active? && active_migration.interval_elapsed?(variance: INTERVAL_VARIANCE)
|
2021-03-31 00:09:32 +00:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def active_migration
|
|
|
|
@active_migration ||= Gitlab::Database::BackgroundMigration::BatchedMigration.active_migration
|
|
|
|
end
|
|
|
|
|
|
|
|
def run_active_migration
|
|
|
|
Gitlab::Database::BackgroundMigration::BatchedMigrationRunner.new.run_migration_job(active_migration)
|
|
|
|
end
|
|
|
|
|
2021-04-05 21:09:19 +00:00
|
|
|
def with_exclusive_lease(interval)
|
2021-04-23 21:09:46 +00:00
|
|
|
timeout = [interval * LEASE_TIMEOUT_MULTIPLIER, MINIMUM_LEASE_TIMEOUT].max
|
2021-04-05 21:09:19 +00:00
|
|
|
lease = Gitlab::ExclusiveLease.new(lease_key, timeout: timeout)
|
2021-03-31 00:09:32 +00:00
|
|
|
|
|
|
|
yield if lease.try_obtain
|
|
|
|
ensure
|
|
|
|
lease&.cancel
|
|
|
|
end
|
|
|
|
|
|
|
|
def lease_key
|
|
|
|
self.class.name.demodulize.underscore
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|