summaryrefslogtreecommitdiff
path: root/app/models/integrations/prometheus.rb
blob: 2f0995e9ab0680523e254cd1f09089ac71c32c3f (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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
# frozen_string_literal: true

module Integrations
  class Prometheus < BaseMonitoring
    include PrometheusAdapter
    include Gitlab::Utils::StrongMemoize

    field :manual_configuration,
      type: 'checkbox',
      title: -> { s_('PrometheusService|Active') },
      help: -> { s_('PrometheusService|Select this checkbox to override the auto configuration settings with your own settings.') },
      required: true

    field :api_url,
      title: 'API URL',
      placeholder: -> { s_('PrometheusService|https://prometheus.example.com/') },
      help: -> { s_('PrometheusService|The Prometheus API base URL.') },
      required: true

    field :google_iap_audience_client_id,
      title: 'Google IAP Audience Client ID',
      placeholder: -> { s_('PrometheusService|IAP_CLIENT_ID.apps.googleusercontent.com') },
      help: -> { s_('PrometheusService|The ID of the IAP-secured resource.') },
      required: false

    field :google_iap_service_account_json,
      type: 'textarea',
      title: 'Google IAP Service Account JSON',
      placeholder: -> { s_('PrometheusService|{ "type": "service_account", "project_id": ... }') },
      help: -> { s_('PrometheusService|The contents of the credentials.json file of your service account.') },
      required: false

    # We need to allow the self-monitoring project to connect to the internal
    # Prometheus instance.
    # Since the internal Prometheus instance is usually a localhost URL, we need
    # to allow localhost URLs when the following conditions are true:
    # 1. project is the self-monitoring project.
    # 2. api_url is the internal Prometheus URL.
    with_options presence: true do
      validates :api_url, public_url: true, if: ->(object) { object.manual_configuration? && !object.allow_local_api_url? }
      validates :api_url, url: true, if: ->(object) { object.manual_configuration? && object.allow_local_api_url? }
    end

    before_save :synchronize_service_state

    after_save :clear_reactive_cache!

    after_commit :track_events

    scope :preload_project, -> { preload(:project) }

    def show_active_box?
      false
    end

    def title
      'Prometheus'
    end

    def description
      s_('PrometheusService|Monitor application health with Prometheus metrics and dashboards')
    end

    def self.to_param
      'prometheus'
    end

    # Check we can connect to the Prometheus API
    def test(*args)
      return { success: false, result: 'Prometheus configuration error' } unless prometheus_client

      prometheus_client.ping
      { success: true, result: 'Checked API endpoint' }
    rescue Gitlab::PrometheusClient::Error => e
      { success: false, result: e }
    end

    def prometheus_client
      return unless should_return_client?

      options = prometheus_client_default_options.merge(
        allow_local_requests: allow_local_api_url?
      )

      if behind_iap? && iap_client
        # Adds the Authorization header
        options[:headers] = iap_client.apply({})
      end

      Gitlab::PrometheusClient.new(api_url, options)
    end

    def prometheus_available?
      return false unless project

      project.all_clusters.enabled.eager_load(:integration_prometheus).any? do |cluster|
        cluster.integration_prometheus_available?
      end
    end

    def allow_local_api_url?
      allow_local_requests_from_web_hooks_and_services? ||
      (self_monitoring_project? && internal_prometheus_url?)
    end

    def configured?
      should_return_client?
    end

    alias_method :google_iap_service_account_json_raw, :google_iap_service_account_json
    private :google_iap_service_account_json_raw

    MASKED_VALUE = '*' * 8

    def google_iap_service_account_json
      json = google_iap_service_account_json_raw
      return json unless json.present?

      Gitlab::Json.parse(json)
        .then { |hash| hash.transform_values { MASKED_VALUE } }
        .then { |hash| Gitlab::Json.generate(hash) }
    rescue Gitlab::Json.parser_error
      json
    end

    private

    delegate :allow_local_requests_from_web_hooks_and_services?, to: :current_settings, private: true

    def self_monitoring_project?
      project && project.id == current_settings.self_monitoring_project_id
    end

    def internal_prometheus_url?
      api_url.present? && api_url == ::Gitlab::Prometheus::Internal.uri
    end

    def should_return_client?
      api_url.present? && manual_configuration? && active? && valid?
    end

    def current_settings
      Gitlab::CurrentSettings.current_application_settings
    end

    def synchronize_service_state
      self.active = prometheus_available? || manual_configuration?

      true
    end

    def track_events
      if enabled_manual_prometheus?
        Gitlab::Tracking.event('cluster:services:prometheus', 'enabled_manual_prometheus')
      elsif disabled_manual_prometheus?
        Gitlab::Tracking.event('cluster:services:prometheus', 'disabled_manual_prometheus')
      end

      true
    end

    def enabled_manual_prometheus?
      manual_configuration_changed? && manual_configuration?
    end

    def disabled_manual_prometheus?
      manual_configuration_changed? && !manual_configuration?
    end

    def behind_iap?
      manual_configuration? && google_iap_audience_client_id.present? && google_iap_service_account_json.present?
    end

    def clean_google_iap_service_account
      json = google_iap_service_account_json_raw
      return unless json.present?

      Gitlab::Json.parse(json).except('token_credential_uri')
    rescue Gitlab::Json.parser_error
      {}
    end

    def iap_client
      @iap_client ||= Google::Auth::Credentials
        .new(clean_google_iap_service_account, target_audience: google_iap_audience_client_id)
        .client
    rescue StandardError
      nil
    end
    strong_memoize_attr :iap_client
  end
end