destroy_service.rb 6.51 KB
Newer Older
1
2
# frozen_string_literal: true

Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
3
module Projects
4
  class DestroyService < BaseService
5
6
    include Gitlab::ShellAdapter

7
    DestroyError = Class.new(StandardError)
8

Douwe Maan's avatar
Douwe Maan committed
9
    DELETED_FLAG = '+deleted'.freeze
10

Stan Hu's avatar
Stan Hu committed
11
    def async_execute
12
13
      project.update_attribute(:pending_delete, true)
      job_id = ProjectDestroyWorker.perform_async(project.id, current_user.id, params)
14
      Rails.logger.info("User #{current_user.id} scheduled destruction of project #{project.full_path} with job ID #{job_id}")
15
16
    end

17
    def execute
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
18
19
      return false unless can?(current_user, :remove_project, project)

20
21
22
      # Flush the cache for both repositories. This has to be done _before_
      # removing the physical repositories as some expiration code depends on
      # Git data (e.g. a list of branch names).
23
      flush_caches(project)
24

25
26
      Projects::UnlinkForkService.new(project, current_user).execute

27
28
29
30
31
32
33
      # The project is not necessarily a fork, so update the fork network originating
      # from this project
      if fork_network = project.root_of_fork_network
        fork_network.update(root_project: nil,
                            deleted_root_project_name: project.full_name)
      end

34
      attempt_destroy_transaction(project)
35

36
      system_hook_service.execute_hooks_for(project, :destroy)
37
      log_info("Project \"#{project.full_path}\" was removed")
38

39
40
      current_user.invalidate_personal_projects_count

41
      true
42
43
    rescue => error
      attempt_rollback(project, error.message)
44
      false
45
46
47
48
    rescue Exception => error # rubocop:disable Lint/RescueException
      # Project.transaction can raise Exception
      attempt_rollback(project, error.message)
      raise
49
50
    end

51
52
53
54
55
    def attempt_repositories_rollback
      return unless @project

      flush_caches(@project)

56
      unless rollback_repository(removal_path(repo_path), repo_path)
57
58
59
        raise_error('Failed to restore project repository. Please contact the administrator.')
      end

60
      unless rollback_repository(removal_path(wiki_path), wiki_path)
61
62
63
64
        raise_error('Failed to restore wiki repository. Please contact the administrator.')
      end
    end

65
    private
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
66

67
    def repo_path
68
      project.disk_path
69
70
71
    end

    def wiki_path
Nick Thomas's avatar
Nick Thomas committed
72
      project.wiki.disk_path
73
74
75
76
77
78
79
80
81
82
83
84
    end

    def trash_repositories!
      unless remove_repository(repo_path)
        raise_error('Failed to remove project repository. Please try again or contact administrator.')
      end

      unless remove_repository(wiki_path)
        raise_error('Failed to remove wiki repository. Please try again or contact administrator.')
      end
    end

85
    def remove_repository(path)
86
87
88
      # There is a possibility project does not have repository or wiki
      return true unless repo_exists?(path)

89
      new_path = removal_path(path)
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
90

91
      if mv_repository(path, new_path)
92
        log_info(%Q{Repository "#{path}" moved to "#{new_path}" for project "#{project.full_path}"})
93
94
95

        project.run_after_commit do
          # self is now project
96
          GitlabShellWorker.perform_in(5.minutes, :remove_repository, self.repository_storage, new_path)
97
        end
98
99
100
101
      else
        false
      end
    end
Vinnie Okada's avatar
Vinnie Okada committed
102

103
104
105
106
107
108
109
    def rollback_repository(old_path, new_path)
      # There is a possibility project does not have repository or wiki
      return true unless repo_exists?(old_path)

      mv_repository(old_path, new_path)
    end

110
    # rubocop: disable CodeReuse/ActiveRecord
111
112
113
    def repo_exists?(path)
      gitlab_shell.exists?(project.repository_storage, path + '.git')
    end
114
    # rubocop: enable CodeReuse/ActiveRecord
115

116
    # rubocop: disable CodeReuse/ActiveRecord
117
    def mv_repository(from_path, to_path)
118
      return true unless gitlab_shell.exists?(project.repository_storage, from_path + '.git')
119

120
      gitlab_shell.mv_repository(project.repository_storage, from_path, to_path)
121
    end
122
    # rubocop: enable CodeReuse/ActiveRecord
123

124
125
126
    def attempt_rollback(project, message)
      return unless project

127
128
129
      # It's possible that the project was destroyed, but some after_commit
      # hook failed and caused us to end up here. A destroyed model will be a frozen hash,
      # which cannot be altered.
Lin Jen-Shin's avatar
Lin Jen-Shin committed
130
      project.update(delete_error: message, pending_delete: false) unless project.destroyed?
131

132
133
134
135
      log_error("Deletion failed on #{project.full_path} with the following message: #{message}")
    end

    def attempt_destroy_transaction(project)
136
137
138
139
      unless remove_registry_tags
        raise_error('Failed to remove some tags in project container registry. Please try again or contact administrator.')
      end

140
      Project.transaction do
141
        log_destroy_event
142
        trash_repositories!
143

144
145
146
147
148
149
150
        # Rails attempts to load all related records into memory before
        # destroying: https://github.com/rails/rails/issues/22510
        # This ensures we delete records in batches.
        #
        # Exclude container repositories because its before_destroy would be
        # called multiple times, and it doesn't destroy any database records.
        project.destroy_dependent_associations_in_batches(exclude: [:container_repositories])
151
152
153
154
        project.destroy!
      end
    end

155
156
157
158
    def log_destroy_event
      log_info("Attempting to destroy #{project.full_path} (#{project.id})")
    end

159
160
161
162
163
164
165
166
167
168
169
    def remove_registry_tags
      return false unless remove_legacy_registry_tags

      project.container_repositories.find_each do |container_repository|
        service = Projects::ContainerRepository::DestroyService.new(project, current_user)
        service.execute(container_repository)
      end

      true
    end

170
171
172
173
174
175
176
    ##
    # This method makes sure that we correctly remove registry tags
    # for legacy image repository (when repository path equals project path).
    #
    def remove_legacy_registry_tags
      return true unless Gitlab.config.registry.enabled

177
      ::ContainerRepository.build_root_repository(project).tap do |repository|
178
        break repository.has_tags? ? repository.delete_tags! : true
179
180
181
      end
    end

182
183
184
185
186
187
188
189
190
191
192
193
    def raise_error(message)
      raise DestroyError.new(message)
    end

    # Build a path for removing repositories
    # We use `+` because its not allowed by GitLab so user can not create
    # project with name cookies+119+deleted and capture someone stalled repository
    #
    # gitlab/cookies.git -> gitlab/cookies+119+deleted.git
    #
    def removal_path(path)
      "#{path}+#{project.id}#{DELETED_FLAG}"
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
194
    end
195

196
    def flush_caches(project)
197
      project.repository.before_delete
198

199
      Repository.new(wiki_path, project, disk_path: repo_path).before_delete
200
201

      Projects::ForksCountService.new(project).delete_cache
202
    end
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
203
204
  end
end