BigW Consortium Gitlab

current_settings.rb 2.65 KB
Newer Older
1 2 3
module Gitlab
  module CurrentSettings
    def current_application_settings
4 5 6 7 8 9
      if RequestStore.active?
        RequestStore.fetch(:current_application_settings) { ensure_application_settings! }
      else
        ensure_application_settings!
      end
    end
10

11
    delegate :sidekiq_throttling_enabled?, to: :current_application_settings
12

13
    def fake_application_settings(defaults = ::ApplicationSetting.defaults)
14
      FakeApplicationSettings.new(defaults)
15
    end
16

17 18 19
    private

    def ensure_application_settings!
20
      return in_memory_application_settings if ENV['IN_MEMORY_APPLICATION_SETTINGS'] == 'true'
21

22
      cached_application_settings || uncached_application_settings
23
    end
24

25
    def cached_application_settings
26
      begin
27
        ::ApplicationSetting.cached
28
      rescue ::Redis::BaseError, ::Errno::ENOENT
29
        # In case Redis isn't running or the Redis UNIX socket file is not available
30 31 32
      end
    end

33 34 35 36
    def uncached_application_settings
      return fake_application_settings unless connect_to_db?

      # This loads from the database into the cache, so handle Redis errors
37
      begin
38
        db_settings = ::ApplicationSetting.current
39 40 41
      rescue ::Redis::BaseError, ::Errno::ENOENT
        # In case Redis isn't running or the Redis UNIX socket file is not available
      end
42 43 44 45 46 47

      # If there are pending migrations, it's possible there are columns that
      # need to be added to the application settings. To prevent Rake tasks
      # and other callers from failing, use any loaded settings and return
      # defaults for missing columns.
      if ActiveRecord::Migrator.needs_migration?
48
        defaults = ::ApplicationSetting.defaults
49 50 51 52 53 54
        defaults.merge!(db_settings.attributes.symbolize_keys) if db_settings.present?
        return fake_application_settings(defaults)
      end

      return db_settings if db_settings.present?

55
      ::ApplicationSetting.create_from_defaults || in_memory_application_settings
56
    end
57

58
    def in_memory_application_settings
59
      @in_memory_application_settings ||= ::ApplicationSetting.new(::ApplicationSetting.defaults)
60
    rescue ActiveRecord::StatementInvalid, ActiveRecord::UnknownAttributeError
61 62
      # In case migrations the application_settings table is not created yet,
      # we fallback to a simple OpenStruct
63 64 65
      fake_application_settings
    end

66
    def connect_to_db?
67 68 69 70
      # When the DBMS is not available, an exception (e.g. PG::ConnectionBad) is raised
      active_db_connection = ActiveRecord::Base.connection.active? rescue false

      active_db_connection &&
71
        ActiveRecord::Base.connection.table_exists?('application_settings')
72 73
    rescue ActiveRecord::NoDatabaseError
      false
74
    end
75 76
  end
end