summaryrefslogtreecommitdiff
path: root/lib/gitlab/database/load_balancing/host_list.rb
blob: aa7315217320d1c87c8d49f0b3985b83c9e1658c (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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# frozen_string_literal: true

module Gitlab
  module Database
    module LoadBalancing
      # A list of database hosts to use for connections.
      class HostList
        # hosts - The list of secondary hosts to add.
        def initialize(hosts = [])
          @hosts = hosts.shuffle
          @index = 0
          @mutex = Mutex.new
          @hosts_gauge = Gitlab::Metrics.gauge(:db_load_balancing_hosts, 'Current number of load balancing hosts')

          set_metrics!
        end

        def hosts
          @mutex.synchronize { @hosts.dup }
        end

        def shuffle
          @mutex.synchronize do
            unsafe_shuffle
          end
        end

        def length
          @mutex.synchronize { @hosts.length }
        end

        def host_names_and_ports
          @mutex.synchronize { @hosts.map { |host| [host.host, host.port] } }
        end

        def hosts=(hosts)
          @mutex.synchronize do
            ::Gitlab::Database::LoadBalancing::Logger.info(
              event: :host_list_update,
              message: "Updating the host list for service discovery",
              host_list_length: hosts.length,
              old_host_list_length: @hosts.length
            )
            @hosts = hosts
            unsafe_shuffle
          end

          set_metrics!
        end

        # Sets metrics before returning next host
        def next
          next_host.tap do |_|
            set_metrics!
          end
        end

        private

        def unsafe_shuffle
          @hosts = @hosts.shuffle
          @index = 0
        end

        # Returns the next available host.
        #
        # Returns a Gitlab::Database::LoadBalancing::Host instance, or nil if no
        # hosts were available.
        def next_host
          @mutex.synchronize do
            break if @hosts.empty?

            started_at = @index

            loop do
              host = @hosts[@index]
              @index = (@index + 1) % @hosts.length

              break host if host.online?

              # Return nil once we have cycled through all hosts and none were
              # available.
              break if @index == started_at
            end
          end
        end

        def set_metrics!
          @hosts_gauge.set({}, @hosts.length)
        end
      end
    end
  end
end