summaryrefslogtreecommitdiff
path: root/lib/gitlab/background_migration/update_jira_tracker_data_deployment_type_based_on_url.rb
blob: 6d59a5c86518449b051248b2070da06c803259f6 (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
# frozen_string_literal: true

# rubocop: disable Style/Documentation
module Gitlab
  module BackgroundMigration
    class UpdateJiraTrackerDataDeploymentTypeBasedOnUrl < Gitlab::BackgroundMigration::BatchedMigrationJob
      feature_category :database

      # rubocop: disable Gitlab/NamespacedClass
      class JiraTrackerData < ActiveRecord::Base
        self.table_name = "jira_tracker_data"
        self.inheritance_column = :_type_disabled

        include ::Integrations::BaseDataFields
        attr_encrypted :url, encryption_options
        attr_encrypted :api_url, encryption_options

        enum deployment_type: { unknown: 0, server: 1, cloud: 2 }, _prefix: :deployment
      end
      # rubocop: enable Gitlab/NamespacedClass

      # https://rubular.com/r/uwgK7k9KH23efa
      JIRA_CLOUD_REGEX = %r{^https?://[A-Za-z0-9](?:[A-Za-z0-9\-]{0,61}[A-Za-z0-9])?\.atlassian\.net$}ix.freeze

      def perform
        cloud = []
        server = []
        unknown = []

        trackers_data.each do |tracker_data|
          client_url = tracker_data.api_url.presence || tracker_data.url

          if client_url.blank?
            unknown << tracker_data
          elsif client_url.match?(JIRA_CLOUD_REGEX)
            cloud << tracker_data
          else
            server << tracker_data
          end
        end

        cloud_mappings = cloud.index_with do
          { deployment_type: 2 }
        end

        server_mappings = server.index_with do
          { deployment_type: 1 }
        end

        unknown_mappings = unknown.index_with do
          { deployment_type: 0 }
        end

        mappings = cloud_mappings.merge(server_mappings, unknown_mappings)

        update_records(mappings)
      end

      private

      def update_records(mappings)
        return if mappings.empty?

        ::Gitlab::Database::BulkUpdate.execute(%i[deployment_type], mappings)
      end

      # rubocop: disable CodeReuse/ActiveRecord
      def trackers_data
        @trackers_data ||= JiraTrackerData
          .where(deployment_type: 'unknown')
          .where(batch_column => start_id..end_id)
      end
      # rubocop: enable CodeReuse/ActiveRecord
    end
  end
end