Read about our upcoming Code of Conduct on this issue

prometheus_adapter.rb 1.94 KB
Newer Older
1
2
# frozen_string_literal: true

3
4
5
6
7
module PrometheusAdapter
  extend ActiveSupport::Concern

  included do
    include ReactiveCaching
8
9
    # We can't prepend outside of this model due to the use of `included`, so this must stay here.
    prepend_if_ee('EE::PrometheusAdapter') # rubocop: disable Cop/InjectEnterpriseEditionModule
10
11
12
13
14
15
16
17
18

    self.reactive_cache_lease_timeout = 30.seconds
    self.reactive_cache_refresh_interval = 30.seconds
    self.reactive_cache_lifetime = 1.minute

    def prometheus_client
      raise NotImplementedError
    end

19
20
21
22
23
24
25
26
    # This is a light-weight check if a prometheus client is properly configured.
    def configured?
      raise NotImplemented
    end

    # This is a heavy-weight check if a prometheus is properly configured and accesible from GitLab.
    # This actually sends a request to an external service and often it could take a long time,
    # Please consider using `configured?` instead if the process is running on unicorn/puma threads.
27
28
29
30
31
32
33
    def can_query?
      prometheus_client.present?
    end

    def query(query_name, *args)
      return unless can_query?

34
35
      query_class = query_klass_for(query_name)
      query_args = build_query_args(*args)
36

37
      with_reactive_cache(query_class.name, *query_args, &query_class.method(:transform_reactive_result))
38
39
40
41
42
43
    end

    # Cache metrics for specific environment
    def calculate_reactive_cache(query_class_name, *args)
      return unless prometheus_client

44
      data = Object.const_get(query_class_name, false).new(prometheus_client).query(*args)
45
46
47
48
49
50
51
52
      {
        success: true,
        data: data,
        last_update: Time.now.utc
      }
    rescue Gitlab::PrometheusClient::Error => err
      { success: false, result: err.message }
    end
53
54

    def query_klass_for(query_name)
55
      Gitlab::Prometheus::Queries.const_get("#{query_name.to_s.classify}Query", false)
56
57
58
    end

    def build_query_args(*args)
59
      args.map { |arg| arg.respond_to?(:id) ? arg.id : arg }
60
    end
61
62
  end
end