summaryrefslogtreecommitdiff
path: root/lib/gitlab/database/async_indexes/index_destructor.rb
blob: fe05872b87a2651e06227a5bb89321fadb5892fe (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
# frozen_string_literal: true

module Gitlab
  module Database
    module AsyncIndexes
      class IndexDestructor
        include ExclusiveLeaseGuard

        TIMEOUT_PER_ACTION = 1.day

        def initialize(async_index)
          @async_index = async_index
        end

        def perform
          try_obtain_lease do
            if !index_exists?
              log_index_info('Skipping dropping as the index does not exist')
            else
              log_index_info('Dropping async index')

              retries = Gitlab::Database::WithLockRetriesOutsideTransaction.new(
                connection: connection,
                timing_configuration: Gitlab::Database::Reindexing::REMOVE_INDEX_RETRY_CONFIG,
                klass: self.class,
                logger: Gitlab::AppLogger
              )

              retries.run(raise_on_exhaustion: false) do
                connection.execute(async_index.definition)
              end

              log_index_info('Finished dropping async index')
            end

            async_index.destroy
          end
        end

        private

        attr_reader :async_index

        def index_exists?
          connection.indexes(async_index.table_name).any? { |index| index.name == async_index.name }
        end

        def connection
          @connection ||= async_index.connection
        end

        def lease_timeout
          TIMEOUT_PER_ACTION
        end

        def lease_key
          [super, async_index.connection_db_config.name].join('/')
        end

        def log_index_info(message)
          Gitlab::AppLogger.info(message: message, table_name: async_index.table_name, index_name: async_index.name)
        end
      end
    end
  end
end