summaryrefslogtreecommitdiff
path: root/config/initializers/load_balancing.rb
blob: 290481f72963f7ff6a314a68e68b7e5336716bf7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# frozen_string_literal: true

Gitlab::Application.configure do |config|
  config.middleware.use(Gitlab::Database::LoadBalancing::RackMiddleware)

  # We need re-rerun the setup when code reloads in development
  config.reloader.to_prepare do
    if Rails.env.development? || Rails.env.test?
      Gitlab::Database::LoadBalancing.base_models.each do |model|
        Gitlab::Database::LoadBalancing::Setup.new(model).setup
      end
    end
  end
end

Gitlab::Database::LoadBalancing.base_models.each do |model|
  # The load balancer needs to be configured immediately, and re-configured
  # after forking. This ensures queries that run before forking use the load
  # balancer, and queries running after a fork don't run into any errors when
  # using dead database connections.
  #
  # See https://gitlab.com/gitlab-org/gitlab/-/merge_requests/63485 for more
  # information.
  Gitlab::Database::LoadBalancing::Setup.new(model).setup

  Rails.application.reloader.to_prepare do
    if Rails.env.development?
      Gitlab::Database::LoadBalancing::Setup.new(model).setup
    end
  end

  # Database queries may be run before we fork, so we must set up the load
  # balancer as early as possible. When we do fork, we need to make sure all the
  # hosts are disconnected.
  Gitlab::Cluster::LifecycleEvents.on_before_fork do
    # When forking, we don't want to wait until the connections aren't in use
    # any more, as this could delay the boot cycle.
    model.load_balancer.disconnect!(timeout: 0)
  end

  # Service discovery only needs to run in the worker processes, as the main one
  # won't be running many (if any) database queries.
  Gitlab::Cluster::LifecycleEvents.on_worker_start do
    Gitlab::Database::LoadBalancing::Setup
      .new(model, start_service_discovery: true)
      .setup
  end
end