prometheus.rb 2.04 KB
Newer Older
1
2
3
4
5
6
7
require 'prometheus/client'

module Gitlab
  module Metrics
    module Prometheus
      include Gitlab::CurrentSettings

8
9
10
      REGISTRY_MUTEX = Mutex.new
      PROVIDER_MUTEX = Mutex.new

11
      def metrics_folder_present?
12
13
14
15
16
        multiprocess_files_dir = ::Prometheus::Client.configuration.multiprocess_files_dir

        multiprocess_files_dir &&
          ::Dir.exist?(multiprocess_files_dir) &&
          ::File.writable?(multiprocess_files_dir)
17
18
      end

19
      def prometheus_metrics_enabled?
20
21
22
        # force disable prometheus_metrics until
        # https://gitlab.com/gitlab-org/prometheus-client-mmap/merge_requests/11 is ready
        false
23
24
25
      end

      def registry
26
27
28
29
30
        return @registry if @registry

        REGISTRY_MUTEX.synchronize do
          @registry ||= ::Prometheus::Client.registry
        end
31
32
33
      end

      def counter(name, docstring, base_labels = {})
34
        safe_provide_metric(:counter, name, docstring, base_labels)
35
36
37
      end

      def summary(name, docstring, base_labels = {})
38
        safe_provide_metric(:summary, name, docstring, base_labels)
39
40
      end

41
      def gauge(name, docstring, base_labels = {}, multiprocess_mode = :all)
42
        safe_provide_metric(:gauge, name, docstring, base_labels, multiprocess_mode)
43
44
45
      end

      def histogram(name, docstring, base_labels = {}, buckets = ::Prometheus::Client::Histogram::DEFAULT_BUCKETS)
46
47
48
49
50
51
52
53
54
55
        safe_provide_metric(:histogram, name, docstring, base_labels, buckets)
      end

      private

      def safe_provide_metric(method, name, *args)
        metric = provide_metric(name)
        return metric if metric

        PROVIDER_MUTEX.synchronize do
56
          provide_metric(name) || registry.method(method).call(name, *args)
57
        end
58
59
60
61
62
63
64
65
66
      end

      def provide_metric(name)
        if prometheus_metrics_enabled?
          registry.get(name)
        else
          NullMetric.new
        end
      end
67
68
69
70

      def prometheus_metrics_enabled_unmemoized
        metrics_folder_present? && current_application_settings[:prometheus_metrics_enabled] || false
      end
71
72
    end
  end
73
end