gitaly_client.rb 10.3 KB
Newer Older
1 2
require 'base64'

3 4 5 6
require 'gitaly'

module Gitlab
  module GitalyClient
7 8 9 10 11 12
    module MigrationStatus
      DISABLED = 1
      OPT_IN = 2
      OPT_OUT = 3
    end

13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
    class TooManyInvocationsError < StandardError
      attr_reader :call_site, :invocation_count, :max_call_stack

      def initialize(call_site, invocation_count, max_call_stack, most_invoked_stack)
        @call_site = call_site
        @invocation_count = invocation_count
        @max_call_stack = max_call_stack
        stacks = most_invoked_stack.join('\n') if most_invoked_stack

        msg = "GitalyClient##{call_site} called #{invocation_count} times from single request. Potential n+1?"
        msg << "\nThe following call site called into Gitaly #{max_call_stack} times:\n#{stacks}\n" if stacks

        super(msg)
      end
    end

29
    SERVER_VERSION_FILE = 'GITALY_SERVER_VERSION'.freeze
30
    MAXIMUM_GITALY_CALLS = 30
31
    CLIENT_NAME = (Sidekiq.server? ? 'gitlab-sidekiq' : 'gitlab-web').freeze
32

Jacob Vosmaer's avatar
Jacob Vosmaer committed
33 34
    MUTEX = Mutex.new
    private_constant :MUTEX
35

36
    class << self
37
      attr_accessor :query_time, :migrate_histogram
38 39 40
    end

    self.query_time = 0
41
    self.migrate_histogram = Gitlab::Metrics.histogram(:gitaly_migrate_call_duration, "Gitaly migration call execution timings")
42

Jacob Vosmaer's avatar
Jacob Vosmaer committed
43 44 45 46 47 48 49 50 51
    def self.stub(name, storage)
      MUTEX.synchronize do
        @stubs ||= {}
        @stubs[storage] ||= {}
        @stubs[storage][name] ||= begin
          klass = Gitaly.const_get(name.to_s.camelcase.to_sym).const_get(:Stub)
          addr = address(storage)
          addr = addr.sub(%r{^tcp://}, '') if URI(addr).scheme == 'tcp'
          klass.new(addr, :this_channel_is_insecure)
52 53
        end
      end
54 55
    end

Jacob Vosmaer's avatar
Jacob Vosmaer committed
56 57 58 59
    def self.clear_stubs!
      MUTEX.synchronize do
        @stubs = nil
      end
60 61
    end

Jacob Vosmaer's avatar
Jacob Vosmaer committed
62 63 64
    def self.address(storage)
      params = Gitlab.config.repositories.storages[storage]
      raise "storage not found: #{storage.inspect}" if params.nil?
65

Jacob Vosmaer's avatar
Jacob Vosmaer committed
66 67 68 69
      address = params['gitaly_address']
      unless address.present?
        raise "storage #{storage.inspect} is missing a gitaly_address"
      end
70

Jacob Vosmaer's avatar
Jacob Vosmaer committed
71 72
      unless URI(address).scheme.in?(%w(tcp unix))
        raise "Unsupported Gitaly address: #{address.inspect} does not use URL scheme 'tcp' or 'unix'"
73 74
      end

Jacob Vosmaer's avatar
Jacob Vosmaer committed
75
      address
76 77
    end

Jacob Vosmaer's avatar
Jacob Vosmaer committed
78 79
    # All Gitaly RPC call sites should use GitalyClient.call. This method
    # makes sure that per-request authentication headers are set.
80 81 82 83 84 85 86 87 88 89 90 91
    #
    # This method optionally takes a block which receives the keyword
    # arguments hash 'kwargs' that will be passed to gRPC. This allows the
    # caller to modify or augment the keyword arguments. The block must
    # return a hash.
    #
    # For example:
    #
    # GitalyClient.call(storage, service, rpc, request) do |kwargs|
    #   kwargs.merge(deadline: Time.now + 10)
    # end
    #
92
    def self.call(storage, service, rpc, request)
93
      start = Process.clock_gettime(Process::CLOCK_MONOTONIC)
94 95
      enforce_gitaly_request_limits(:call)

96 97 98
      kwargs = request_kwargs(storage)
      kwargs = yield(kwargs) if block_given?
      stub(service, storage).__send__(rpc, request, kwargs) # rubocop:disable GitlabSecurity/PublicSend
99 100
    ensure
      self.query_time += Process.clock_gettime(Process::CLOCK_MONOTONIC) - start
101
    end
102

103
    def self.request_kwargs(storage)
104
      encoded_token = Base64.strict_encode64(token(storage).to_s)
105 106 107 108 109 110 111 112 113 114
      metadata = {
        'authorization' => "Bearer #{encoded_token}",
        'client_name' => CLIENT_NAME
      }

      feature_stack = Thread.current[:gitaly_feature_stack]
      feature = feature_stack && feature_stack[0]
      metadata['call_site'] = feature.to_s if feature

      { metadata: metadata }
115 116 117 118 119 120 121 122 123
    end

    def self.token(storage)
      params = Gitlab.config.repositories.storages[storage]
      raise "storage not found: #{storage.inspect}" if params.nil?

      params['gitaly_token'].presence || Gitlab.config.gitaly['token']
    end

124 125 126
    # Evaluates whether a feature toggle is on or off
    def self.feature_enabled?(feature_name, status: MigrationStatus::OPT_IN)
      # Disabled features are always off!
127
      return false if status == MigrationStatus::DISABLED
128

129
      feature = Feature.get("gitaly_#{feature_name}")
130

131 132 133 134 135 136 137 138 139
      # If the feature has been set, always evaluate
      if Feature.persisted?(feature)
        if feature.percentage_of_time_value > 0
          # Probabilistically enable this feature
          return Random.rand() * 100 < feature.percentage_of_time_value
        end

        return feature.enabled?
      end
140

141 142 143 144 145 146 147 148 149
      # If the feature has not been set, the default depends
      # on it's status
      case status
      when MigrationStatus::OPT_OUT
        true
      when MigrationStatus::OPT_IN
        opt_into_all_features?
      else
        false
150
      end
151
    end
152

153 154 155 156
    # opt_into_all_features? returns true when the current environment
    # is one in which we opt into features automatically
    def self.opt_into_all_features?
      Rails.env.development? || ENV["GITALY_FEATURE_DEFAULT_ON"] == "1"
157
    end
158
    private_class_method :opt_into_all_features?
159

160
    def self.migrate(feature, status: MigrationStatus::OPT_IN)
161 162 163 164
      # Enforce limits at both the `migrate` and `call` sites to ensure that
      # problems are not hidden by a feature being disabled
      enforce_gitaly_request_limits(:migrate)

165
      is_enabled  = feature_enabled?(feature, status: status)
166 167 168 169
      metric_name = feature.to_s
      metric_name += "_gitaly" if is_enabled

      Gitlab::Metrics.measure(metric_name) do
170 171
        # Some migrate calls wrap other migrate calls
        allow_n_plus_1_calls do
172 173 174
          feature_stack = Thread.current[:gitaly_feature_stack] ||= []
          feature_stack.unshift(feature)
          begin
175
            start = Process.clock_gettime(Process::CLOCK_MONOTONIC)
176 177
            yield is_enabled
          ensure
178 179
            total_time = Process.clock_gettime(Process::CLOCK_MONOTONIC) - start
            migrate_histogram.observe({ gitaly_enabled: is_enabled, feature: feature }, total_time)
180 181 182
            feature_stack.shift
            Thread.current[:gitaly_feature_stack] = nil if feature_stack.empty?
          end
183 184 185 186 187 188 189 190 191 192 193 194 195
        end
      end
    end

    # Ensures that Gitaly is not being abuse through n+1 misuse etc
    def self.enforce_gitaly_request_limits(call_site)
      # Only count limits in request-response environments (not sidekiq for example)
      return unless RequestStore.active?

      # This is this actual number of times this call was made. Used for information purposes only
      actual_call_count = increment_call_count("gitaly_#{call_site}_actual")

      # Do no enforce limits in production
196
      return if Rails.env.production? || ENV["GITALY_DISABLE_REQUEST_LIMITS"]
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264

      # Check if this call is nested within a allow_n_plus_1_calls
      # block and skip check if it is
      return if get_call_count(:gitaly_call_count_exception_block_depth) > 0

      # This is the count of calls outside of a `allow_n_plus_1_calls` block
      # It is used for enforcement but not statistics
      permitted_call_count = increment_call_count("gitaly_#{call_site}_permitted")

      count_stack

      return if permitted_call_count <= MAXIMUM_GITALY_CALLS

      raise TooManyInvocationsError.new(call_site, actual_call_count, max_call_count, max_stacks)
    end

    def self.allow_n_plus_1_calls
      return yield unless RequestStore.active?

      begin
        increment_call_count(:gitaly_call_count_exception_block_depth)
        yield
      ensure
        decrement_call_count(:gitaly_call_count_exception_block_depth)
      end
    end

    def self.get_call_count(key)
      RequestStore.store[key] || 0
    end
    private_class_method :get_call_count

    def self.increment_call_count(key)
      RequestStore.store[key] ||= 0
      RequestStore.store[key] += 1
    end
    private_class_method :increment_call_count

    def self.decrement_call_count(key)
      RequestStore.store[key] -= 1
    end
    private_class_method :decrement_call_count

    # Returns an estimate of the number of Gitaly calls made for this
    # request
    def self.get_request_count
      return 0 unless RequestStore.active?

      gitaly_migrate_count = get_call_count("gitaly_migrate_actual")
      gitaly_call_count = get_call_count("gitaly_call_actual")

      # Using the maximum of migrate and call_count will provide an
      # indicator of how many Gitaly calls will be made, even
      # before a feature is enabled. This provides us with a single
      # metric, but not an exact number, but this tradeoff is acceptable
      if gitaly_migrate_count > gitaly_call_count
        gitaly_migrate_count
      else
        gitaly_call_count
      end
    end

    def self.reset_counts
      return unless RequestStore.active?

      %w[migrate call].each do |call_site|
        RequestStore.store["gitaly_#{call_site}_actual"] = 0
        RequestStore.store["gitaly_#{call_site}_permitted"] = 0
265 266
      end
    end
267 268 269 270 271

    def self.expected_server_version
      path = Rails.root.join(SERVER_VERSION_FILE)
      path.read.chomp
    end
272

273 274 275 276
    def self.timestamp(t)
      Google::Protobuf::Timestamp.new(seconds: t.to_i)
    end

277
    def self.encode(s)
278 279
      return "" if s.nil?

280 281
      s.dup.force_encoding(Encoding::ASCII_8BIT)
    end
282

283 284 285 286
    def self.encode_repeated(a)
      Google::Protobuf::RepeatedField.new(:bytes, a.map { |s| self.encode(s) } )
    end

287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
    # Count a stack. Used for n+1 detection
    def self.count_stack
      return unless RequestStore.active?

      stack_string = caller.drop(1).join("\n")

      RequestStore.store[:stack_counter] ||= Hash.new

      count = RequestStore.store[:stack_counter][stack_string] || 0
      RequestStore.store[:stack_counter][stack_string] = count + 1
    end
    private_class_method :count_stack

    # Returns a count for the stack which called Gitaly the most times. Used for n+1 detection
    def self.max_call_count
      return 0 unless RequestStore.active?

      stack_counter = RequestStore.store[:stack_counter]
      return 0 unless stack_counter

      stack_counter.values.max
    end
    private_class_method :max_call_count

    # Returns the stacks that calls Gitaly the most times. Used for n+1 detection
    def self.max_stacks
      return nil unless RequestStore.active?

      stack_counter = RequestStore.store[:stack_counter]
      return nil unless stack_counter

      max = max_call_count
      return nil if max.zero?

      stack_counter.select { |_, v| v == max }.keys
    end
    private_class_method :max_stacks
324 325
  end
end