summaryrefslogtreecommitdiff
path: root/lib/gitlab/daemon.rb
blob: bd14c7eece3fee3fc40255ea40ab4e6039a57548 (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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
module Gitlab
  class Daemon
    def self.initialize_instance(*args)
      raise "#{name} singleton instance already initialized" if @instance

      @instance = new(*args)
      Kernel.at_exit(&@instance.method(:stop))
      @instance
    end

    def self.instance
      @instance ||= initialize_instance
    end

    attr_reader :thread

    def thread?
      !thread.nil?
    end

    def initialize
      @mutex = Mutex.new
    end

    def enabled?
      true
    end

    def start
      return unless enabled?

      @mutex.synchronize do
        break thread if thread?

        @thread = Thread.new { start_working }
      end
    end

    def stop
      @mutex.synchronize do
        break unless thread?

        stop_working

        if thread
          thread.wakeup if thread.alive?
          thread.join unless Thread.current == thread
          @thread = nil
        end
      end
    end

    private

    def start_working
      raise NotImplementedError
    end

    def stop_working
      # no-ops
    end
  end
end