summaryrefslogtreecommitdiff
path: root/app/services/projects/housekeeping_service.rb
blob: bccd67d3dbf49df02c1cf15ca1ef104cd7eda8e1 (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
# Projects::HousekeepingService class
#
# Used for git housekeeping
#
# Ex.
#   Projects::HousekeepingService.new(project).execute
#
module Projects
  class HousekeepingService < BaseService
    include Gitlab::ShellAdapter

    LEASE_TIMEOUT = 3600

    class LeaseTaken < StandardError
      def to_s
        "Somebody already triggered housekeeping for this project in the past #{LEASE_TIMEOUT / 60} minutes"
      end
    end

    def initialize(project)
      @project = project
    end

    def execute
      raise LeaseTaken if !try_obtain_lease

      GitlabShellWorker.perform_async(:gc, @project.path_with_namespace)
    ensure
      @project.update_column(:pushes_since_gc, 0)
    end

    def needed?
      @project.pushes_since_gc >= 10
    end

    def increment!
      @project.increment!(:pushes_since_gc)
    end

    private

    def try_obtain_lease
      lease = ::Gitlab::ExclusiveLease.new("project_housekeeping:#{@project.id}", timeout: LEASE_TIMEOUT)
      lease.try_obtain
    end
  end
end