summaryrefslogtreecommitdiff
path: root/db/post_migrate/20190809072552_set_self_monitoring_project_alerting_token.rb
blob: 0c4faebc54827e97b3e924651b17fe1c59a43dd1 (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
# frozen_string_literal: true

class SetSelfMonitoringProjectAlertingToken < ActiveRecord::Migration[5.2]
  DOWNTIME = false

  module Migratable
    module Alerting
      class ProjectAlertingSetting < ApplicationRecord
        self.table_name = 'project_alerting_settings'

        belongs_to :project

        validates :token, presence: true

        attr_encrypted :token,
          mode: :per_attribute_iv,
          key: Settings.attr_encrypted_db_key_base_truncated,
          algorithm: 'aes-256-gcm'

        before_validation :ensure_token

        private

        def ensure_token
          self.token ||= generate_token
        end

        def generate_token
          SecureRandom.hex
        end
      end
    end

    class Project < ApplicationRecord
      has_one :alerting_setting, inverse_of: :project, class_name: 'Alerting::ProjectAlertingSetting'
    end

    class ApplicationSetting < ApplicationRecord
      self.table_name = 'application_settings'

      belongs_to :instance_administration_project, class_name: 'Project'

      def self.current_without_cache
        last
      end
    end
  end

  def setup_alertmanager_token(project)
    return unless License.feature_available?(:prometheus_alerts)

    project.create_alerting_setting!
  end

  def up
    Gitlab.ee do
      project = Migratable::ApplicationSetting.current_without_cache&.instance_administration_project

      if project
        setup_alertmanager_token(project)
      end
    end
  end

  def down
    Gitlab.ee do
      Migratable::ApplicationSetting.current_without_cache
        &.instance_administration_project
        &.alerting_setting
        &.destroy!
    end
  end
end