housekeeping_service.rb 1023 Bytes
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 if !try_obtain_lease
Jacob Vosmaer's avatar
Jacob Vosmaer committed
26

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

    def needed?
      @project.pushes_since_gc >= 10
    end

    def increment!
37
      @project.increment!(:pushes_since_gc)
38
39
40
41
42
43
44
    end

    private

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