housekeeping_service.rb 1.48 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
      Gitlab::Metrics.measure(:reset_pushes_since_gc) do
30
        update_pushes_since_gc(0)
31
      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
      Gitlab::Metrics.measure(:increment_pushes_since_gc) do
40
        update_pushes_since_gc(@project.pushes_since_gc + 1)
41
      end
42 43 44 45
    end

    private

46 47 48 49 50 51
    def update_pushes_since_gc(new_value)
      if Gitlab::ExclusiveLease.new("project_housekeeping:update_pushes_since_gc:#{project.id}", timeout: 60).try_obtain
        @project.update_column(:pushes_since_gc, new_value)
      end
    end

52
    def try_obtain_lease
53 54 55 56
      Gitlab::Metrics.measure(:obtain_housekeeping_lease) do
        lease = ::Gitlab::ExclusiveLease.new("project_housekeeping:#{@project.id}", timeout: LEASE_TIMEOUT)
        lease.try_obtain
      end
57 58 59
    end
  end
end