housekeeping_service.rb 1.25 KB
Newer Older
1
2
3
4
5
# Projects::HousekeepingService class
#
# Used for git housekeeping
#
# Ex.
6
#   Projects::HousekeepingService.new(project).execute
7
8
9
10
11
#
module Projects
  class HousekeepingService < BaseService
    include Gitlab::ShellAdapter

12
13
    LEASE_TIMEOUT = 3600

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

20
21
22
23
24
    def initialize(project)
      @project = project
    end

    def execute
25
      raise LeaseTaken unless try_obtain_lease
Jacob Vosmaer's avatar
Jacob Vosmaer committed
26

27
      GitlabShellOneShotWorker.perform_async(:gc, @project.repository_storage_path, @project.path_with_namespace)
28
    ensure
29
30
31
      Gitlab::Metrics.measure(:reset_pushes_since_gc) do
        @project.update_column(:pushes_since_gc, 0)
      end
Jacob Vosmaer's avatar
Jacob Vosmaer committed
32
33
34
35
36
37
38
    end

    def needed?
      @project.pushes_since_gc >= 10
    end

    def increment!
39
40
41
      Gitlab::Metrics.measure(:increment_pushes_since_gc) do
        @project.increment!(:pushes_since_gc)
      end
42
43
44
45
46
    end

    private

    def try_obtain_lease
47
48
49
50
      Gitlab::Metrics.measure(:obtain_housekeeping_lease) do
        lease = ::Gitlab::ExclusiveLease.new("project_housekeeping:#{@project.id}", timeout: LEASE_TIMEOUT)
        lease.try_obtain
      end
51
52
53
    end
  end
end