2018-10-22 03:00:50 -04:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2017-08-07 13:13:02 -04:00
|
|
|
module Gitlab
|
|
|
|
class Daemon
|
|
|
|
def self.initialize_instance(*args)
|
|
|
|
raise "#{name} singleton instance already initialized" if @instance
|
2017-11-14 04:02:39 -05:00
|
|
|
|
2017-08-07 13:13:02 -04:00
|
|
|
@instance = new(*args)
|
|
|
|
Kernel.at_exit(&@instance.method(:stop))
|
|
|
|
@instance
|
|
|
|
end
|
|
|
|
|
2019-09-17 05:06:11 -04:00
|
|
|
def self.instance(*args)
|
|
|
|
@instance ||= initialize_instance(*args)
|
2017-08-07 13:13:02 -04:00
|
|
|
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
|
2018-04-18 05:19:40 -04:00
|
|
|
break thread if thread?
|
2017-08-07 13:13:02 -04:00
|
|
|
|
|
|
|
@thread = Thread.new { start_working }
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def stop
|
|
|
|
@mutex.synchronize do
|
2018-04-18 05:19:40 -04:00
|
|
|
break unless thread?
|
2017-08-07 13:13:02 -04:00
|
|
|
|
|
|
|
stop_working
|
|
|
|
|
|
|
|
if thread
|
|
|
|
thread.wakeup if thread.alive?
|
2019-08-21 05:32:45 -04:00
|
|
|
begin
|
|
|
|
thread.join unless Thread.current == thread
|
|
|
|
rescue Exception # rubocop:disable Lint/RescueException
|
|
|
|
end
|
2017-08-07 13:13:02 -04:00
|
|
|
@thread = nil
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def start_working
|
|
|
|
raise NotImplementedError
|
|
|
|
end
|
|
|
|
|
|
|
|
def stop_working
|
|
|
|
# no-ops
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|