rails_cache.rb 2.62 KB
Newer Older
1 2 3 4
module Gitlab
  module Metrics
    module Subscribers
      # Class for tracking the total time spent in Rails cache calls
5
      # http://guides.rubyonrails.org/active_support_instrumentation.html
6 7 8 9
      class RailsCache < ActiveSupport::Subscriber
        attach_to :active_support

        def cache_read(event)
10
          observe(:read, event.duration)
11 12 13 14 15

          return unless current_transaction
          return if event.payload[:super_operation] == :fetch

          if event.payload[:hit]
16
            current_transaction.increment(:cache_read_hit_count, 1, false)
17
          else
18
            metric_cache_misses_total.increment(current_transaction.labels)
19
            current_transaction.increment(:cache_read_miss_count, 1, false)
20
          end
21 22 23
        end

        def cache_write(event)
24
          observe(:write, event.duration)
25 26 27
        end

        def cache_delete(event)
28
          observe(:delete, event.duration)
29 30 31
        end

        def cache_exist?(event)
32
          observe(:exists, event.duration)
33 34
        end

35 36 37
        def cache_fetch_hit(event)
          return unless current_transaction

38
          current_transaction.increment(:cache_read_hit_count, 1)
39 40 41 42 43
        end

        def cache_generate(event)
          return unless current_transaction

44
          metric_cache_misses_total.increment(current_transaction.labels)
45
          current_transaction.increment(:cache_read_miss_count, 1)
46 47
        end

48
        def observe(key, duration)
49 50
          return unless current_transaction

51
          metric_cache_operation_duration_seconds.observe(current_transaction.labels.merge({ operation: key }), duration / 1000.0)
52 53
          current_transaction.increment(:cache_duration, duration, false)
          current_transaction.increment(:cache_count, 1, false)
54 55
          current_transaction.increment("cache_#{key}_duration".to_sym, duration, false)
          current_transaction.increment("cache_#{key}_count".to_sym, 1, false)
56 57 58 59 60 61 62
        end

        private

        def current_transaction
          Transaction.current
        end
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79

        def metric_cache_operation_duration_seconds
          @metric_cache_operation_duration_seconds ||= Gitlab::Metrics.histogram(
            :gitlab_cache_operation_duration_seconds,
            'Cache access time',
            Transaction::BASE_LABELS.merge({ action: nil }),
            [0.001, 0.002, 0.005, 0.01, 0.02, 0.05, 0.1, 0.500, 2.0, 10.0]
          )
        end

        def metric_cache_misses_total
          @metric_cache_misses_total ||= Gitlab::Metrics.counter(
            :gitlab_cache_misses_total,
            'Cache read miss',
            Transaction::BASE_LABELS
          )
        end
80 81 82 83
      end
    end
  end
end