summaryrefslogtreecommitdiff
path: root/lib/gitlab/metrics/subscribers/active_record.rb
blob: e53ac00e77f02047fac282110f6aa7c4ec6957f6 (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
# frozen_string_literal: true

module Gitlab
  module Metrics
    module Subscribers
      # Class for tracking the total query duration of a transaction.
      class ActiveRecord < ActiveSupport::Subscriber
        attach_to :active_record

        IGNORABLE_SQL = %w{BEGIN COMMIT}.freeze
        DB_COUNTERS = %i{db_count db_write_count db_cached_count}.freeze

        def sql(event)
          # Mark this thread as requiring a database connection. This is used
          # by the Gitlab::Metrics::Samplers::ThreadsSampler to count threads
          # using a connection.
          Thread.current[:uses_db_connection] = true

          return unless current_transaction

          payload = event.payload
          return if payload[:name] == 'SCHEMA' || IGNORABLE_SQL.include?(payload[:sql])

          current_transaction.observe(:gitlab_sql_duration_seconds, event.duration / 1000.0) do
            buckets [0.05, 0.1, 0.25]
          end

          increment_db_counters(payload)
        end

        def self.db_counter_payload
          return {} unless Gitlab::SafeRequestStore.active?

          DB_COUNTERS.map do |counter|
            [counter, Gitlab::SafeRequestStore[counter].to_i]
          end.to_h
        end

        private

        def select_sql_command?(payload)
          payload[:sql].match(/\A((?!(.*[^\w'"](DELETE|UPDATE|INSERT INTO)[^\w'"])))(WITH.*)?(SELECT)((?!(FOR UPDATE|FOR SHARE)).)*$/i)
        end

        def increment_db_counters(payload)
          increment(:db_count)

          if payload.fetch(:cached, payload[:name] == 'CACHE')
            increment(:db_cached_count)
          end

          increment(:db_write_count) unless select_sql_command?(payload)
        end

        def increment(counter)
          current_transaction.increment("gitlab_transaction_#{counter}_total".to_sym, 1)

          if Gitlab::SafeRequestStore.active?
            Gitlab::SafeRequestStore[counter] = Gitlab::SafeRequestStore[counter].to_i + 1
          end
        end

        def current_transaction
          Transaction.current
        end
      end
    end
  end
end