From ffa2465cbf3f8cba3d750cf7213b7648b2147c31 Mon Sep 17 00:00:00 2001 From: Douglas Barbosa Alexandre <dbalexandre@gmail.com> Date: Wed, 24 May 2017 23:29:35 -0300 Subject: [PATCH] Dynamically sets the database connection for Geo::BaseRegistry model If Gitlab::Geo.secondary? changes, we need to reinitialize the connection properly in the model to avoid requiring a full unicorn restart. --- app/models/geo/base_registry.rb | 28 ++++++++++++++++++++++++++-- lib/gitlab/geo.rb | 4 ++++ 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/app/models/geo/base_registry.rb b/app/models/geo/base_registry.rb index 7d10b5db7931..4f07388fe68e 100644 --- a/app/models/geo/base_registry.rb +++ b/app/models/geo/base_registry.rb @@ -1,7 +1,31 @@ class Geo::BaseRegistry < ActiveRecord::Base self.abstract_class = true - if Gitlab::Geo.configured? && (Gitlab::Geo.secondary? || Rails.env.test?) - establish_connection Rails.configuration.geo_database + # If Gitlab::Geo.secondary? changes, we need to reinitialize the connection + # properly in the model to avoid requiring a full unicorn restart. + def self.retrieve_connection + set_connection! if should_change_connection? + connection_handler.retrieve_connection(self) + end + + private + + def self.set_connection! + if Gitlab::Geo.tracking_connection_available? + establish_connection Rails.configuration.geo_database + else + establish_connection "#{Rails.env}".to_sym + end + end + + def self.should_change_connection? + using_master_connection? && Gitlab::Geo.tracking_connection_available? + end + + def self.using_master_connection? + master_connection = ActiveRecord::Base.connection_config[:database] + tracking_connection = Geo::BaseRegistry.connection_config[:database] + + master_connection === tracking_connection end end diff --git a/lib/gitlab/geo.rb b/lib/gitlab/geo.rb index f6661b03c11e..3d188bfbc9c2 100644 --- a/lib/gitlab/geo.rb +++ b/lib/gitlab/geo.rb @@ -46,6 +46,10 @@ def self.configured? Rails.configuration.respond_to?(:geo_database) end + def self.tracking_connection_available? + self.cache_value(:tracking_connection_available) { self.configured? && (self.secondary? || Rails.env.test?) } + end + def self.license_allows? ::License.current&.feature_available?(:geo) end -- GitLab