Commit 7c5506ec authored by Andreas Brandl's avatar Andreas Brandl

Merge branch 'stomlinson/identify-partitions-to-drop' into 'master'

Partition manager identifies partitions to detach

See merge request gitlab-org/gitlab!65093
parents 74159ded 01210db7
...@@ -10,12 +10,12 @@ module PartitionedTable ...@@ -10,12 +10,12 @@ module PartitionedTable
monthly: Gitlab::Database::Partitioning::MonthlyStrategy monthly: Gitlab::Database::Partitioning::MonthlyStrategy
}.freeze }.freeze
def partitioned_by(partitioning_key, strategy:) def partitioned_by(partitioning_key, strategy:, **kwargs)
strategy_class = PARTITIONING_STRATEGIES[strategy.to_sym] || raise(ArgumentError, "Unknown partitioning strategy: #{strategy}") strategy_class = PARTITIONING_STRATEGIES[strategy.to_sym] || raise(ArgumentError, "Unknown partitioning strategy: #{strategy}")
@partitioning_strategy = strategy_class.new(self, partitioning_key) @partitioning_strategy = strategy_class.new(self, partitioning_key, **kwargs)
Gitlab::Database::Partitioning::PartitionCreator.register(self) Gitlab::Database::Partitioning::PartitionManager.register(self)
end end
end end
end end
...@@ -9,7 +9,7 @@ class WebHookLog < ApplicationRecord ...@@ -9,7 +9,7 @@ class WebHookLog < ApplicationRecord
self.primary_key = :id self.primary_key = :id
partitioned_by :created_at, strategy: :monthly partitioned_by :created_at, strategy: :monthly, retain_for: 3.months
belongs_to :web_hook belongs_to :web_hook
......
...@@ -247,6 +247,15 @@ ...@@ -247,6 +247,15 @@
:idempotent: true :idempotent: true
:tags: :tags:
- :exclude_from_kubernetes - :exclude_from_kubernetes
- :name: cronjob:database_partition_management
:worker_name: Database::PartitionManagementWorker
:feature_category: :database
:has_external_dependencies:
:urgency: :low
:resource_boundary: :unknown
:weight: 1
:idempotent: true
:tags: []
- :name: cronjob:environments_auto_stop_cron - :name: cronjob:environments_auto_stop_cron
:worker_name: Environments::AutoStopCronWorker :worker_name: Environments::AutoStopCronWorker
:feature_category: :continuous_delivery :feature_category: :continuous_delivery
......
# frozen_string_literal: true
module Database
class PartitionManagementWorker
include ApplicationWorker
sidekiq_options retry: 3
include CronjobQueue # rubocop:disable Scalability/CronWorkerContext
feature_category :database
idempotent!
def perform
Gitlab::Database::Partitioning::PartitionManager.new.sync_partitions
ensure
Gitlab::Database::Partitioning::PartitionMonitoring.new.report_metrics
end
end
end
...@@ -10,8 +10,7 @@ class PartitionCreationWorker ...@@ -10,8 +10,7 @@ class PartitionCreationWorker
idempotent! idempotent!
def perform def perform
Gitlab::Database::Partitioning::PartitionCreator.new.create_partitions # This worker has been removed in favor of Database::PartitionManagementWorker
ensure Database::PartitionManagementWorker.new.perform
Gitlab::Database::Partitioning::PartitionMonitoring.new.report_metrics
end end
end end
---
name: partition_pruning_dry_run
introduced_by_url: https://gitlab.com/gitlab-org/gitlab/-/merge_requests/65093
rollout_issue_url:
milestone: '14.1'
type: development
group: group::database
default_enabled: false
...@@ -540,9 +540,9 @@ Settings.cron_jobs['authorized_project_update_periodic_recalculate_worker']['job ...@@ -540,9 +540,9 @@ Settings.cron_jobs['authorized_project_update_periodic_recalculate_worker']['job
Settings.cron_jobs['update_container_registry_info_worker'] ||= Settingslogic.new({}) Settings.cron_jobs['update_container_registry_info_worker'] ||= Settingslogic.new({})
Settings.cron_jobs['update_container_registry_info_worker']['cron'] ||= '0 0 * * *' Settings.cron_jobs['update_container_registry_info_worker']['cron'] ||= '0 0 * * *'
Settings.cron_jobs['update_container_registry_info_worker']['job_class'] = 'UpdateContainerRegistryInfoWorker' Settings.cron_jobs['update_container_registry_info_worker']['job_class'] = 'UpdateContainerRegistryInfoWorker'
Settings.cron_jobs['postgres_dynamic_partitions_creator'] ||= Settingslogic.new({}) Settings.cron_jobs['postgres_dynamic_partitions_manager'] ||= Settingslogic.new({})
Settings.cron_jobs['postgres_dynamic_partitions_creator']['cron'] ||= '21 */6 * * *' Settings.cron_jobs['postgres_dynamic_partitions_manager']['cron'] ||= '21 */6 * * *'
Settings.cron_jobs['postgres_dynamic_partitions_creator']['job_class'] ||= 'PartitionCreationWorker' Settings.cron_jobs['postgres_dynamic_partitions_manager']['job_class'] ||= 'Database::PartitionManagementWorker'
Settings.cron_jobs['ci_platform_metrics_update_cron_worker'] ||= Settingslogic.new({}) Settings.cron_jobs['ci_platform_metrics_update_cron_worker'] ||= Settingslogic.new({})
Settings.cron_jobs['ci_platform_metrics_update_cron_worker']['cron'] ||= '47 9 * * *' Settings.cron_jobs['ci_platform_metrics_update_cron_worker']['cron'] ||= '47 9 * * *'
Settings.cron_jobs['ci_platform_metrics_update_cron_worker']['job_class'] = 'CiPlatformMetricsUpdateCronWorker' Settings.cron_jobs['ci_platform_metrics_update_cron_worker']['job_class'] = 'CiPlatformMetricsUpdateCronWorker'
......
...@@ -3,15 +3,15 @@ ...@@ -3,15 +3,15 @@
# Make sure we have loaded partitioned models here # Make sure we have loaded partitioned models here
# (even with eager loading disabled). # (even with eager loading disabled).
Gitlab::Database::Partitioning::PartitionCreator.register(AuditEvent) Gitlab::Database::Partitioning::PartitionManager.register(AuditEvent)
Gitlab::Database::Partitioning::PartitionCreator.register(WebHookLog) Gitlab::Database::Partitioning::PartitionManager.register(WebHookLog)
if Gitlab.ee? if Gitlab.ee?
Gitlab::Database::Partitioning::PartitionCreator.register(IncidentManagement::PendingEscalations::Alert) Gitlab::Database::Partitioning::PartitionManager.register(IncidentManagement::PendingEscalations::Alert)
end end
begin begin
Gitlab::Database::Partitioning::PartitionCreator.new.create_partitions unless ENV['DISABLE_POSTGRES_PARTITION_CREATION_ON_STARTUP'] Gitlab::Database::Partitioning::PartitionManager.new.sync_partitions unless ENV['DISABLE_POSTGRES_PARTITION_CREATION_ON_STARTUP']
rescue ActiveRecord::ActiveRecordError, PG::Error rescue ActiveRecord::ActiveRecordError, PG::Error
# ignore - happens when Rake tasks yet have to create a database, e.g. for testing # ignore - happens when Rake tasks yet have to create a database, e.g. for testing
end end
...@@ -4,16 +4,17 @@ module Gitlab ...@@ -4,16 +4,17 @@ module Gitlab
module Database module Database
module Partitioning module Partitioning
class MonthlyStrategy class MonthlyStrategy
attr_reader :model, :partitioning_key attr_reader :model, :partitioning_key, :retain_for
# We create this many partitions in the future # We create this many partitions in the future
HEADROOM = 6.months HEADROOM = 6.months
delegate :table_name, to: :model delegate :table_name, to: :model
def initialize(model, partitioning_key) def initialize(model, partitioning_key, retain_for: nil)
@model = model @model = model
@partitioning_key = partitioning_key @partitioning_key = partitioning_key
@retain_for = retain_for
end end
def current_partitions def current_partitions
...@@ -27,13 +28,21 @@ module Gitlab ...@@ -27,13 +28,21 @@ module Gitlab
desired_partitions - current_partitions desired_partitions - current_partitions
end end
def extra_partitions
current_partitions - desired_partitions
end
private private
def desired_partitions def desired_partitions
[].tap do |parts| [].tap do |parts|
min_date, max_date = relevant_range min_date, max_date = relevant_range
parts << partition_for(upper_bound: min_date) if pruning_old_partitions? && min_date <= oldest_active_date
min_date = oldest_active_date.beginning_of_month
else
parts << partition_for(upper_bound: min_date)
end
while min_date < max_date while min_date < max_date
next_date = min_date.next_month next_date = min_date.next_month
...@@ -52,13 +61,17 @@ module Gitlab ...@@ -52,13 +61,17 @@ module Gitlab
# to start from MINVALUE to a specific date `x`. The range returned # to start from MINVALUE to a specific date `x`. The range returned
# does not include the range of the first, half-unbounded partition. # does not include the range of the first, half-unbounded partition.
def relevant_range def relevant_range
if first_partition = current_partitions.min if (first_partition = current_partitions.min)
# Case 1: First partition starts with MINVALUE, i.e. from is nil -> start with first real partition # Case 1: First partition starts with MINVALUE, i.e. from is nil -> start with first real partition
# Case 2: Rather unexpectedly, first partition does not start with MINVALUE, i.e. from is not nil # Case 2: Rather unexpectedly, first partition does not start with MINVALUE, i.e. from is not nil
# In this case, use first partition beginning as a start # In this case, use first partition beginning as a start
min_date = first_partition.from || first_partition.to min_date = first_partition.from || first_partition.to
end end
if pruning_old_partitions?
min_date ||= oldest_active_date
end
# In case we don't have a partition yet # In case we don't have a partition yet
min_date ||= Date.today min_date ||= Date.today
min_date = min_date.beginning_of_month min_date = min_date.beginning_of_month
...@@ -72,6 +85,14 @@ module Gitlab ...@@ -72,6 +85,14 @@ module Gitlab
TimePartition.new(table_name, lower_bound, upper_bound) TimePartition.new(table_name, lower_bound, upper_bound)
end end
def pruning_old_partitions?
Feature.enabled?(:partition_pruning_dry_run) && retain_for.present?
end
def oldest_active_date
(Date.today - retain_for).beginning_of_month
end
def connection def connection
ActiveRecord::Base.connection ActiveRecord::Base.connection
end end
......
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
module Gitlab module Gitlab
module Database module Database
module Partitioning module Partitioning
class PartitionCreator class PartitionManager
def self.register(model) def self.register(model)
raise ArgumentError, "Only models with a #partitioning_strategy can be registered." unless model.respond_to?(:partitioning_strategy) raise ArgumentError, "Only models with a #partitioning_strategy can be registered." unless model.respond_to?(:partitioning_strategy)
...@@ -15,7 +15,7 @@ module Gitlab ...@@ -15,7 +15,7 @@ module Gitlab
end end
LEASE_TIMEOUT = 1.minute LEASE_TIMEOUT = 1.minute
LEASE_KEY = 'database_partition_creation_%s' MANAGEMENT_LEASE_KEY = 'database_partition_management_%s'
attr_reader :models attr_reader :models
...@@ -23,23 +23,25 @@ module Gitlab ...@@ -23,23 +23,25 @@ module Gitlab
@models = models @models = models
end end
def create_partitions def sync_partitions
Gitlab::AppLogger.info("Checking state of dynamic postgres partitions") Gitlab::AppLogger.info("Checking state of dynamic postgres partitions")
models.each do |model| models.each do |model|
# Double-checking before getting the lease: # Double-checking before getting the lease:
# The prevailing situation is no missing partitions # The prevailing situation is no missing partitions and no extra partitions
next if missing_partitions(model).empty? next if missing_partitions(model).empty? && extra_partitions(model).empty?
only_with_exclusive_lease(model) do only_with_exclusive_lease(model, lease_key: MANAGEMENT_LEASE_KEY) do
partitions_to_create = missing_partitions(model) partitions_to_create = missing_partitions(model)
create(partitions_to_create) unless partitions_to_create.empty?
next if partitions_to_create.empty? if Feature.enabled?(:partition_pruning_dry_run)
partitions_to_detach = extra_partitions(model)
create(model, partitions_to_create) detach(partitions_to_detach) unless partitions_to_detach.empty?
end
end end
rescue StandardError => e rescue StandardError => e
Gitlab::AppLogger.error("Failed to create partition(s) for #{model.table_name}: #{e.class}: #{e.message}") Gitlab::AppLogger.error("Failed to create / detach partition(s) for #{model.table_name}: #{e.class}: #{e.message}")
end end
end end
...@@ -51,15 +53,22 @@ module Gitlab ...@@ -51,15 +53,22 @@ module Gitlab
model.partitioning_strategy.missing_partitions model.partitioning_strategy.missing_partitions
end end
def only_with_exclusive_lease(model) def extra_partitions(model)
lease = Gitlab::ExclusiveLease.new(LEASE_KEY % model.table_name, timeout: LEASE_TIMEOUT) return [] unless Feature.enabled?(:partition_pruning_dry_run)
return [] unless connection.table_exists?(model.table_name)
model.partitioning_strategy.extra_partitions
end
def only_with_exclusive_lease(model, lease_key:)
lease = Gitlab::ExclusiveLease.new(lease_key % model.table_name, timeout: LEASE_TIMEOUT)
yield if lease.try_obtain yield if lease.try_obtain
ensure ensure
lease&.cancel lease&.cancel
end end
def create(model, partitions) def create(partitions)
connection.transaction do connection.transaction do
with_lock_retries do with_lock_retries do
partitions.each do |partition| partitions.each do |partition|
...@@ -71,6 +80,18 @@ module Gitlab ...@@ -71,6 +80,18 @@ module Gitlab
end end
end end
def detach(partitions)
connection.transaction do
with_lock_retries do
partitions.each { |p| detach_one_partition(p) }
end
end
end
def detach_one_partition(partition)
Gitlab::AppLogger.info("Planning to detach #{partition.partition_name} for table #{partition.table}")
end
def with_lock_retries(&block) def with_lock_retries(&block)
Gitlab::Database::WithLockRetries.new( Gitlab::Database::WithLockRetries.new(
klass: self.class, klass: self.class,
......
...@@ -6,7 +6,7 @@ module Gitlab ...@@ -6,7 +6,7 @@ module Gitlab
class PartitionMonitoring class PartitionMonitoring
attr_reader :models attr_reader :models
def initialize(models = PartitionCreator.models) def initialize(models = PartitionManager.models)
@models = models @models = models
end end
......
...@@ -118,7 +118,7 @@ namespace :gitlab do ...@@ -118,7 +118,7 @@ namespace :gitlab do
desc 'Create missing dynamic database partitions' desc 'Create missing dynamic database partitions'
task create_dynamic_partitions: :environment do task create_dynamic_partitions: :environment do
Gitlab::Database::Partitioning::PartitionCreator.new.create_partitions Gitlab::Database::Partitioning::PartitionManager.new.sync_partitions
end end
# This is targeted towards deploys and upgrades of GitLab. # This is targeted towards deploys and upgrades of GitLab.
......
...@@ -71,6 +71,18 @@ RSpec.describe Gitlab::Database::Partitioning::MonthlyStrategy do ...@@ -71,6 +71,18 @@ RSpec.describe Gitlab::Database::Partitioning::MonthlyStrategy do
model.create!(created_at: Date.parse('2020-06-15')) model.create!(created_at: Date.parse('2020-06-15'))
end end
context 'when pruning partitions before June 2020' do
subject { described_class.new(model, partitioning_key, retain_for: 1.month).missing_partitions }
it 'does not include the missing partition from May 2020 because it would be dropped' do
expect(subject).not_to include(Gitlab::Database::Partitioning::TimePartition.new(model.table_name, '2020-05-01', '2020-06-01'))
end
it 'detects the missing partition for 1 month ago (July 2020)' do
expect(subject).to include(Gitlab::Database::Partitioning::TimePartition.new(model.table_name, '2020-07-01', '2020-08-01'))
end
end
it 'detects the gap and the missing partition in May 2020' do it 'detects the gap and the missing partition in May 2020' do
expect(subject).to include(Gitlab::Database::Partitioning::TimePartition.new(model.table_name, '2020-05-01', '2020-06-01')) expect(subject).to include(Gitlab::Database::Partitioning::TimePartition.new(model.table_name, '2020-05-01', '2020-06-01'))
end end
...@@ -108,6 +120,19 @@ RSpec.describe Gitlab::Database::Partitioning::MonthlyStrategy do ...@@ -108,6 +120,19 @@ RSpec.describe Gitlab::Database::Partitioning::MonthlyStrategy do
SQL SQL
end end
context 'when pruning partitions before June 2020' do
subject { described_class.new(model, partitioning_key, retain_for: 1.month).missing_partitions }
it 'detects exactly the set of partitions from June 2020 to March 2021' do
months = %w[2020-07-01 2020-08-01 2020-09-01 2020-10-01 2020-11-01 2020-12-01 2021-01-01 2021-02-01 2021-03-01]
expected = months[..-2].zip(months.drop(1)).map do |(from, to)|
Gitlab::Database::Partitioning::TimePartition.new(model.table_name, from, to)
end
expect(subject).to match_array(expected)
end
end
it 'detects the missing catch-all partition at the beginning' do it 'detects the missing catch-all partition at the beginning' do
expect(subject).to include(Gitlab::Database::Partitioning::TimePartition.new(model.table_name, nil, '2020-08-01')) expect(subject).to include(Gitlab::Database::Partitioning::TimePartition.new(model.table_name, nil, '2020-08-01'))
end end
...@@ -150,4 +175,100 @@ RSpec.describe Gitlab::Database::Partitioning::MonthlyStrategy do ...@@ -150,4 +175,100 @@ RSpec.describe Gitlab::Database::Partitioning::MonthlyStrategy do
end end
end end
end end
describe '#extra_partitions' do
let(:model) do
Class.new(ActiveRecord::Base) do
self.table_name = 'partitioned_test'
self.primary_key = :id
end
end
let(:partitioning_key) { :created_at }
let(:table_name) { :partitioned_test }
around do |example|
travel_to(Date.parse('2020-08-22')) { example.run }
end
describe 'with existing partitions' do
before do
ActiveRecord::Base.connection.execute(<<~SQL)
CREATE TABLE #{table_name}
(id serial not null, created_at timestamptz not null, PRIMARY KEY (id, created_at))
PARTITION BY RANGE (created_at);
CREATE TABLE #{Gitlab::Database::DYNAMIC_PARTITIONS_SCHEMA}.partitioned_test_000000
PARTITION OF #{table_name}
FOR VALUES FROM (MINVALUE) TO ('2020-05-01');
CREATE TABLE #{Gitlab::Database::DYNAMIC_PARTITIONS_SCHEMA}.partitioned_test_202005
PARTITION OF #{table_name}
FOR VALUES FROM ('2020-05-01') TO ('2020-06-01');
CREATE TABLE #{Gitlab::Database::DYNAMIC_PARTITIONS_SCHEMA}.partitioned_test_202006
PARTITION OF #{table_name}
FOR VALUES FROM ('2020-06-01') TO ('2020-07-01')
SQL
end
context 'without a time retention policy' do
subject { described_class.new(model, partitioning_key).extra_partitions }
it 'has no extra partitions to prune' do
expect(subject).to eq([])
end
end
context 'with a time retention policy that excludes no partitions' do
subject { described_class.new(model, partitioning_key, retain_for: 4.months).extra_partitions }
it 'has no extra partitions to prune' do
expect(subject).to eq([])
end
end
context 'with a time retention policy of 3 months' do
subject { described_class.new(model, partitioning_key, retain_for: 3.months).extra_partitions }
it 'prunes the unbounded partition ending 2020-05-01' do
min_value_to_may = Gitlab::Database::Partitioning::TimePartition.new(model.table_name, nil, '2020-05-01',
partition_name: 'partitioned_test_000000')
expect(subject).to contain_exactly(min_value_to_may)
end
context 'when the feature flag is toggled off' do
before do
stub_feature_flags(partition_pruning_dry_run: false)
end
it 'is empty' do
expect(subject).to eq([])
end
end
end
context 'with a time retention policy of 2 months' do
subject { described_class.new(model, partitioning_key, retain_for: 2.months).extra_partitions }
it 'prunes the unbounded partition and the partition for May-June' do
expect(subject).to contain_exactly(
Gitlab::Database::Partitioning::TimePartition.new(model.table_name, nil, '2020-05-01', partition_name: 'partitioned_test_000000'),
Gitlab::Database::Partitioning::TimePartition.new(model.table_name, '2020-05-01', '2020-06-01', partition_name: 'partitioned_test_202005')
)
end
context 'when the feature flag is toggled off' do
before do
stub_feature_flags(partition_pruning_dry_run: false)
end
it 'is empty' do
expect(subject).to eq([])
end
end
end
end
end
end end
...@@ -2,8 +2,9 @@ ...@@ -2,8 +2,9 @@
require 'spec_helper' require 'spec_helper'
RSpec.describe Gitlab::Database::Partitioning::PartitionCreator do RSpec.describe Gitlab::Database::Partitioning::PartitionManager do
include Database::PartitioningHelpers include Database::PartitioningHelpers
include Database::TableSchemaHelpers
include ExclusiveLeaseHelpers include ExclusiveLeaseHelpers
describe '.register' do describe '.register' do
...@@ -14,12 +15,12 @@ RSpec.describe Gitlab::Database::Partitioning::PartitionCreator do ...@@ -14,12 +15,12 @@ RSpec.describe Gitlab::Database::Partitioning::PartitionCreator do
end end
end end
describe '#create_partitions (mocked)' do context 'creating partitions (mocked)' do
subject { described_class.new(models).create_partitions } subject(:sync_partitions) { described_class.new(models).sync_partitions }
let(:models) { [model] } let(:models) { [model] }
let(:model) { double(partitioning_strategy: partitioning_strategy, table_name: table) } let(:model) { double(partitioning_strategy: partitioning_strategy, table_name: table) }
let(:partitioning_strategy) { double(missing_partitions: partitions) } let(:partitioning_strategy) { double(missing_partitions: partitions, extra_partitions: []) }
let(:table) { "some_table" } let(:table) { "some_table" }
before do before do
...@@ -27,7 +28,7 @@ RSpec.describe Gitlab::Database::Partitioning::PartitionCreator do ...@@ -27,7 +28,7 @@ RSpec.describe Gitlab::Database::Partitioning::PartitionCreator do
allow(ActiveRecord::Base.connection).to receive(:table_exists?).with(table).and_return(true) allow(ActiveRecord::Base.connection).to receive(:table_exists?).with(table).and_return(true)
allow(ActiveRecord::Base.connection).to receive(:execute).and_call_original allow(ActiveRecord::Base.connection).to receive(:execute).and_call_original
stub_exclusive_lease(described_class::LEASE_KEY % table, timeout: described_class::LEASE_TIMEOUT) stub_exclusive_lease(described_class::MANAGEMENT_LEASE_KEY % table, timeout: described_class::LEASE_TIMEOUT)
end end
let(:partitions) do let(:partitions) do
...@@ -41,7 +42,7 @@ RSpec.describe Gitlab::Database::Partitioning::PartitionCreator do ...@@ -41,7 +42,7 @@ RSpec.describe Gitlab::Database::Partitioning::PartitionCreator do
expect(ActiveRecord::Base.connection).to receive(:execute).with(partitions.first.to_sql) expect(ActiveRecord::Base.connection).to receive(:execute).with(partitions.first.to_sql)
expect(ActiveRecord::Base.connection).to receive(:execute).with(partitions.second.to_sql) expect(ActiveRecord::Base.connection).to receive(:execute).with(partitions.second.to_sql)
subject sync_partitions
end end
context 'error handling with 2 models' do context 'error handling with 2 models' do
...@@ -52,21 +53,21 @@ RSpec.describe Gitlab::Database::Partitioning::PartitionCreator do ...@@ -52,21 +53,21 @@ RSpec.describe Gitlab::Database::Partitioning::PartitionCreator do
] ]
end end
let(:strategy1) { double('strategy1', missing_partitions: nil) } let(:strategy1) { double('strategy1', missing_partitions: nil, extra_partitions: []) }
let(:strategy2) { double('strategy2', missing_partitions: partitions) } let(:strategy2) { double('strategy2', missing_partitions: partitions, extra_partitions: []) }
it 'still creates partitions for the second table' do it 'still creates partitions for the second table' do
expect(strategy1).to receive(:missing_partitions).and_raise('this should never happen (tm)') expect(strategy1).to receive(:missing_partitions).and_raise('this should never happen (tm)')
expect(ActiveRecord::Base.connection).to receive(:execute).with(partitions.first.to_sql) expect(ActiveRecord::Base.connection).to receive(:execute).with(partitions.first.to_sql)
expect(ActiveRecord::Base.connection).to receive(:execute).with(partitions.second.to_sql) expect(ActiveRecord::Base.connection).to receive(:execute).with(partitions.second.to_sql)
subject sync_partitions
end end
end end
end end
describe '#create_partitions' do context 'creating partitions' do
subject { described_class.new([my_model]).create_partitions } subject(:sync_partitions) { described_class.new([my_model]).sync_partitions }
let(:connection) { ActiveRecord::Base.connection } let(:connection) { ActiveRecord::Base.connection }
let(:my_model) do let(:my_model) do
...@@ -88,9 +89,73 @@ RSpec.describe Gitlab::Database::Partitioning::PartitionCreator do ...@@ -88,9 +89,73 @@ RSpec.describe Gitlab::Database::Partitioning::PartitionCreator do
end end
it 'creates partitions' do it 'creates partitions' do
expect { subject }.to change { find_partitions(my_model.table_name, schema: Gitlab::Database::DYNAMIC_PARTITIONS_SCHEMA).size }.from(0) expect { sync_partitions }.to change { find_partitions(my_model.table_name, schema: Gitlab::Database::DYNAMIC_PARTITIONS_SCHEMA).size }.from(0)
end
end
context 'detaching partitions (mocked)' do
subject(:sync_partitions) { manager.sync_partitions }
let(:manager) { described_class.new(models) }
let(:models) { [model] }
let(:model) { double(partitioning_strategy: partitioning_strategy, table_name: table)}
let(:partitioning_strategy) { double(extra_partitions: extra_partitions, missing_partitions: []) }
let(:table) { "foo" }
before do
allow(ActiveRecord::Base.connection).to receive(:table_exists?).and_call_original
allow(ActiveRecord::Base.connection).to receive(:table_exists?).with(table).and_return(true)
stub_exclusive_lease(described_class::MANAGEMENT_LEASE_KEY % table, timeout: described_class::LEASE_TIMEOUT)
end
let(:extra_partitions) do
[
instance_double(Gitlab::Database::Partitioning::TimePartition, table: table, partition_name: 'foo1'),
instance_double(Gitlab::Database::Partitioning::TimePartition, table: table, partition_name: 'foo2')
]
end
subject context 'with the partition_pruning_dry_run feature flag enabled' do
before do
stub_feature_flags(partition_pruning_dry_run: true)
end
it 'detaches each extra partition' do
extra_partitions.each { |p| expect(manager).to receive(:detach_one_partition).with(p) }
sync_partitions
end
context 'error handling' do
let(:models) do
[
double(partitioning_strategy: error_strategy, table_name: table),
model
]
end
let(:error_strategy) { double(extra_partitions: nil, missing_partitions: []) }
it 'still drops partitions for the other model' do
expect(error_strategy).to receive(:extra_partitions).and_raise('injected error!')
extra_partitions.each { |p| expect(manager).to receive(:detach_one_partition).with(p) }
sync_partitions
end
end
end
context 'with the partition_pruning_dry_run feature flag disabled' do
before do
stub_feature_flags(partition_pruning_dry_run: false)
end
it 'returns immediately' do
expect(manager).not_to receive(:detach)
sync_partitions
end
end end
end end
end end
...@@ -14,6 +14,16 @@ RSpec.describe PartitionedTable do ...@@ -14,6 +14,16 @@ RSpec.describe PartitionedTable do
end end
end end
context 'with keyword arguments passed to the strategy' do
subject { my_class.partitioned_by(key, strategy: :monthly, retain_for: 3.months) }
it 'passes the keyword arguments to the strategy' do
expect(Gitlab::Database::Partitioning::MonthlyStrategy).to receive(:new).with(my_class, key, retain_for: 3.months).and_call_original
subject
end
end
it 'assigns the MonthlyStrategy as the partitioning strategy' do it 'assigns the MonthlyStrategy as the partitioning strategy' do
subject subject
...@@ -27,7 +37,7 @@ RSpec.describe PartitionedTable do ...@@ -27,7 +37,7 @@ RSpec.describe PartitionedTable do
end end
it 'registers itself with the PartitionCreator' do it 'registers itself with the PartitionCreator' do
expect(Gitlab::Database::Partitioning::PartitionCreator).to receive(:register).with(my_class) expect(Gitlab::Database::Partitioning::PartitionManager).to receive(:register).with(my_class)
subject subject
end end
......
# frozen_string_literal: true
require "spec_helper"
RSpec.describe Database::PartitionManagementWorker do
describe '#perform' do
subject { described_class.new.perform }
let(:manager) { instance_double('PartitionManager', sync_partitions: nil) }
let(:monitoring) { instance_double('PartitionMonitoring', report_metrics: nil) }
before do
allow(Gitlab::Database::Partitioning::PartitionManager).to receive(:new).and_return(manager)
allow(Gitlab::Database::Partitioning::PartitionMonitoring).to receive(:new).and_return(monitoring)
end
it 'delegates to PartitionManager' do
expect(manager).to receive(:sync_partitions)
subject
end
it 'reports partition metrics' do
expect(monitoring).to receive(:report_metrics)
subject
end
end
end
# frozen_string_literal: true # frozen_string_literal: true
#
require "spec_helper" require 'spec_helper'
RSpec.describe PartitionCreationWorker do RSpec.describe PartitionCreationWorker do
describe '#perform' do subject { described_class.new.perform }
subject { described_class.new.perform }
let(:creator) { instance_double('PartitionCreator', create_partitions: nil) }
let(:monitoring) { instance_double('PartitionMonitoring', report_metrics: nil) }
before do
allow(Gitlab::Database::Partitioning::PartitionCreator).to receive(:new).and_return(creator)
allow(Gitlab::Database::Partitioning::PartitionMonitoring).to receive(:new).and_return(monitoring)
end
it 'delegates to PartitionCreator' do let(:management_worker) { double }
expect(creator).to receive(:create_partitions)
subject describe '#perform' do
end it 'forwards to the Database::PartitionManagementWorker' do
expect(Database::PartitionManagementWorker).to receive(:new).and_return(management_worker)
it 'reports partition metrics' do expect(management_worker).to receive(:perform)
expect(monitoring).to receive(:report_metrics)
subject subject
end end
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment