instrumentation.rb 5.84 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11
module Gitlab
  module Metrics
    # Module for instrumenting methods.
    #
    # This module allows instrumenting of methods without having to actually
    # alter the target code (e.g. by including modules).
    #
    # Example usage:
    #
    #     Gitlab::Metrics::Instrumentation.instrument_method(User, :by_login)
    module Instrumentation
12 13
      SERIES = 'method_calls'

14 15
      PROXY_IVAR = :@__gitlab_instrumentation_proxy

16 17 18 19
      def self.configure
        yield self
      end

20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
      # Instruments a class method.
      #
      # mod  - The module to instrument as a Module/Class.
      # name - The name of the method to instrument.
      def self.instrument_method(mod, name)
        instrument(:class, mod, name)
      end

      # Instruments an instance method.
      #
      # mod  - The module to instrument as a Module/Class.
      # name - The name of the method to instrument.
      def self.instrument_instance_method(mod, name)
        instrument(:instance, mod, name)
      end

36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
      # Recursively instruments all subclasses of the given root module.
      #
      # This can be used to for example instrument all ActiveRecord models (as
      # these all inherit from ActiveRecord::Base).
      #
      # This method can optionally take a block to pass to `instrument_methods`
      # and `instrument_instance_methods`.
      #
      # root - The root module for which to instrument subclasses. The root
      #        module itself is not instrumented.
      def self.instrument_class_hierarchy(root, &block)
        visit = root.subclasses

        until visit.empty?
          klass = visit.pop

          instrument_methods(klass, &block)
          instrument_instance_methods(klass, &block)

          klass.subclasses.each { |c| visit << c }
        end
      end

59
      # Instruments all public and private methods of a module.
60
      #
61 62 63 64 65
      # This method optionally takes a block that can be used to determine if a
      # method should be instrumented or not. The block is passed the receiving
      # module and an UnboundMethod. If the block returns a non truthy value the
      # method is not instrumented.
      #
66 67
      # mod - The module to instrument.
      def self.instrument_methods(mod)
68 69
        methods = mod.methods(false) + mod.private_methods(false)
        methods.each do |name|
70 71
          method = mod.method(name)

72 73 74 75 76
          if method.owner == mod.singleton_class
            if !block_given? || block_given? && yield(mod, method)
              instrument_method(mod, name)
            end
          end
77 78 79
        end
      end

80
      # Instruments all public and private instance methods of a module.
81
      #
82 83
      # See `instrument_methods` for more information.
      #
84 85
      # mod - The module to instrument.
      def self.instrument_instance_methods(mod)
86 87
        methods = mod.instance_methods(false) + mod.private_instance_methods(false)
        methods.each do |name|
88 89
          method = mod.instance_method(name)

90 91 92 93 94
          if method.owner == mod
            if !block_given? || block_given? && yield(mod, method)
              instrument_instance_method(mod, name)
            end
          end
95 96 97
        end
      end

98 99 100 101 102 103 104 105 106 107 108 109
      # Returns true if a module is instrumented.
      #
      # mod - The module to check
      def self.instrumented?(mod)
        mod.instance_variable_defined?(PROXY_IVAR)
      end

      # Returns the proxy module (if any) of `mod`.
      def self.proxy_module(mod)
        mod.instance_variable_get(PROXY_IVAR)
      end

110 111 112 113 114
      # Instruments a method.
      #
      # type - The type (:class or :instance) of method to instrument.
      # mod  - The module containing the method.
      # name - The name of the method to instrument.
115 116 117
      def self.instrument(type, mod, name)
        return unless Metrics.enabled?

118 119
        name   = name.to_sym
        target = type == :instance ? mod : mod.singleton_class
120

121 122 123
        if type == :instance
          target = mod
          label  = "#{mod.name}##{name}"
124
          method = mod.instance_method(name)
125 126 127
        else
          target = mod.singleton_class
          label  = "#{mod.name}.#{name}"
128 129 130
          method = mod.method(name)
        end

131 132 133 134 135 136
        unless instrumented?(target)
          target.instance_variable_set(PROXY_IVAR, Module.new)
        end

        proxy_module = self.proxy_module(target)

137 138 139 140 141 142 143 144 145 146
        # Some code out there (e.g. the "state_machine" Gem) checks the arity of
        # a method to make sure it only passes arguments when the method expects
        # any. If we were to always overwrite a method to take an `*args`
        # signature this would break things. As a result we'll make sure the
        # generated method _only_ accepts regular arguments if the underlying
        # method also accepts them.
        if method.arity == 0
          args_signature = '&block'
        else
          args_signature = '*args, &block'
147 148
        end

149
        proxy_module.class_eval <<-EOF, __FILE__, __LINE__ + 1
150
          def #{name}(#{args_signature})
151 152 153
            trans = Gitlab::Metrics::Instrumentation.transaction

            if trans
154 155 156 157
              start     = Time.now
              cpu_start = Gitlab::Metrics::System.cpu_time
              retval    = super
              duration  = (Time.now - start) * 1000.0
158

159
              if duration >= Gitlab::Metrics.method_call_threshold
160 161
                cpu_duration = Gitlab::Metrics::System.cpu_time - cpu_start

162
                trans.add_metric(Gitlab::Metrics::Instrumentation::SERIES,
163
                                 { duration: duration, cpu_duration: cpu_duration },
164 165
                                 method: #{label.inspect})
              end
166 167 168

              retval
            else
169
              super
170
            end
171
          end
172
        EOF
173 174

        target.prepend(proxy_module)
175
      end
176 177 178 179 180 181

      # Small layer of indirection to make it easier to stub out the current
      # transaction.
      def self.transaction
        Transaction.current
      end
182 183 184
    end
  end
end