summaryrefslogtreecommitdiff
path: root/app/models/clusters/integrations/prometheus.rb
blob: 899529ff49f8c679841fb8810d8a2300bd5bc9f5 (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
# frozen_string_literal: true

module Clusters
  module Integrations
    class Prometheus < ApplicationRecord
      include ::Clusters::Concerns::PrometheusClient
      include AfterCommitQueue

      self.table_name = 'clusters_integration_prometheus'
      self.primary_key = :cluster_id

      belongs_to :cluster, class_name: 'Clusters::Cluster', foreign_key: :cluster_id

      validates :cluster, presence: true
      validates :enabled, inclusion: { in: [true, false] }

      # Periodically checked and kept up to date for Monitor demo projects
      enum health_status: {
        unknown: 0,
        healthy: 1,
        unhealthy: 2
      }

      attr_encrypted :alert_manager_token,
        mode: :per_attribute_iv,
        key: Settings.attr_encrypted_db_key_base_32,
        algorithm: 'aes-256-gcm'

      default_value_for(:alert_manager_token) { SecureRandom.hex }

      scope :enabled, -> { where(enabled: true) }

      after_destroy do
        run_after_commit do
          deactivate_project_integrations
        end
      end

      after_save do
        next unless enabled_before_last_save != enabled

        run_after_commit do
          if enabled
            activate_project_integrations
          else
            deactivate_project_integrations
          end
        end
      end

      def available?
        enabled?
      end

      private

      def activate_project_integrations
        ::Clusters::Applications::ActivateIntegrationWorker
          .perform_async(cluster_id, ::Integrations::Prometheus.to_param)
      end

      def deactivate_project_integrations
        ::Clusters::Applications::DeactivateIntegrationWorker
          .perform_async(cluster_id, ::Integrations::Prometheus.to_param)
      end
    end
  end
end