Created
June 2, 2021 02:59
-
-
Save zelic91/38510fa7f3662c8b3c1739ee008bac68 to your computer and use it in GitHub Desktop.
Ruby standalone daemon base app
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class BaseExec | |
def initialize() | |
@prefix = self.class.name.underscore | |
@pid_file = Rails.root.join("pids/#{@prefix}.pid") | |
@log_file = Rails.root.join("logs/#{@prefix}.log") | |
end | |
def run! | |
if ARGV[0].present? | |
handle_commands() | |
puts "[#{@prefix}] STOPPED" | |
exit | |
end | |
check_pid() | |
daemonize() | |
write_pid() | |
puts "[#{@prefix}] STARTING ..." | |
redirect_output() | |
end | |
def write_pid | |
begin | |
dir = File.dirname(@pid_file) | |
FileUtils.mkdir_p(dir) unless File.exist?(dir) | |
File.open(@pid_file, ::File::CREAT | ::File::EXCL | ::File::WRONLY) do |file| | |
file.write("#{Process.pid}") | |
end | |
at_exit { File.delete(@pid_file) if File.exists?(@pid_file) } | |
rescue Errno::EEXIST | |
check_pid() | |
retry | |
end | |
end | |
def check_pid | |
status = pid_status() | |
case status | |
when :running, :not_owned | |
puts "Another instance is running. Check #{@pid_file}." | |
exit(1) | |
when :dead | |
File.delete(@pid_file) | |
end | |
end | |
def pid_status | |
return :exited unless File.exists?(@pid_file) | |
pid = ::File.read(@pid_file).to_i | |
return :dead if pid == 0 | |
Process.kill(0, pid) | |
return :running | |
rescue Errno::ESRCH | |
:dead | |
rescue Errno::EPERM | |
:not_owned | |
end | |
def daemonize | |
Process.daemon | |
end | |
def redirect_output | |
FileUtils.mkdir_p(File.dirname(@log_file), mode: 0777) | |
FileUtils.touch(@log_file) | |
File.chmod(0777, @log_file) | |
$stderr.reopen(@log_file, 'w') | |
$stdout.reopen($stderr) | |
$stdout.sync = $stderr.sync = true | |
end | |
def handle_commands() | |
case ARGV[0] | |
when 'stop' | |
stop() | |
end | |
end | |
def stop() | |
status = pid_status() | |
case status | |
when :running, :not_owned | |
pid = ::File.read(@pid_file).to_i | |
Process.kill('QUIT', pid) | |
when :dead | |
File.delete(@pid_file) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment