2018-12-13 13:39:08 +05:30
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2017-09-10 17:25:29 +05:30
|
|
|
module Gitlab
|
|
|
|
class Daemon
|
|
|
|
def self.initialize_instance(*args)
|
|
|
|
raise "#{name} singleton instance already initialized" if @instance
|
2018-03-17 18:26:18 +05:30
|
|
|
|
2017-09-10 17:25:29 +05:30
|
|
|
@instance = new(*args)
|
|
|
|
Kernel.at_exit(&@instance.method(:stop))
|
|
|
|
@instance
|
|
|
|
end
|
|
|
|
|
2019-12-04 20:38:33 +05:30
|
|
|
def self.instance(*args)
|
|
|
|
@instance ||= initialize_instance(*args)
|
2017-09-10 17:25:29 +05:30
|
|
|
end
|
|
|
|
|
|
|
|
attr_reader :thread
|
|
|
|
|
|
|
|
def thread?
|
|
|
|
!thread.nil?
|
|
|
|
end
|
|
|
|
|
|
|
|
def initialize
|
|
|
|
@mutex = Mutex.new
|
|
|
|
end
|
|
|
|
|
|
|
|
def enabled?
|
|
|
|
true
|
|
|
|
end
|
|
|
|
|
2019-12-26 22:10:19 +05:30
|
|
|
def thread_name
|
|
|
|
self.class.name.demodulize.underscore
|
|
|
|
end
|
|
|
|
|
2017-09-10 17:25:29 +05:30
|
|
|
def start
|
|
|
|
return unless enabled?
|
|
|
|
|
|
|
|
@mutex.synchronize do
|
2018-10-15 14:42:47 +05:30
|
|
|
break thread if thread?
|
2017-09-10 17:25:29 +05:30
|
|
|
|
2019-12-21 20:55:43 +05:30
|
|
|
if start_working
|
2019-12-26 22:10:19 +05:30
|
|
|
@thread = Thread.new do
|
|
|
|
Thread.current.name = thread_name
|
|
|
|
run_thread
|
|
|
|
end
|
2019-12-21 20:55:43 +05:30
|
|
|
end
|
2017-09-10 17:25:29 +05:30
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def stop
|
|
|
|
@mutex.synchronize do
|
2018-10-15 14:42:47 +05:30
|
|
|
break unless thread?
|
2017-09-10 17:25:29 +05:30
|
|
|
|
|
|
|
stop_working
|
|
|
|
|
|
|
|
if thread
|
|
|
|
thread.wakeup if thread.alive?
|
2019-12-04 20:38:33 +05:30
|
|
|
begin
|
|
|
|
thread.join unless Thread.current == thread
|
|
|
|
rescue Exception # rubocop:disable Lint/RescueException
|
|
|
|
end
|
2017-09-10 17:25:29 +05:30
|
|
|
@thread = nil
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
2019-12-21 20:55:43 +05:30
|
|
|
# Executed in lock context before starting thread
|
|
|
|
# Needs to return success
|
2017-09-10 17:25:29 +05:30
|
|
|
def start_working
|
2019-12-21 20:55:43 +05:30
|
|
|
true
|
|
|
|
end
|
|
|
|
|
|
|
|
# Executed in separate thread
|
|
|
|
def run_thread
|
2017-09-10 17:25:29 +05:30
|
|
|
raise NotImplementedError
|
|
|
|
end
|
|
|
|
|
2019-12-21 20:55:43 +05:30
|
|
|
# Executed in lock context
|
2017-09-10 17:25:29 +05:30
|
|
|
def stop_working
|
|
|
|
# no-ops
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|