class Eyecare::Daemon

Attributes

err[RW]
out[RW]
pid_file[RW]

Public Class Methods

new(options = {}) click to toggle source
# File lib/eyecare/daemon.rb, line 7
def initialize(options = {})
  options = Hash[pid_file: options] if options.is_a?(String)
  @pid_file = options[:pid_file]
end
start(options = {}) { || ... } click to toggle source
# File lib/eyecare/daemon.rb, line 12
def self.start(options = {}, &block)
  return false unless block_given?
  daemon = self.new(options)

  begin
    daemon.send(:cleanup) if daemon.stale_pid?
    if daemon.started?
      puts 'Already started'
      return false
    end

    print 'Starting...'
    Process.daemon(nil, true)
    daemon.send(:write_pid)

    trap('INT') { exit(0) }
    at_exit { daemon.send(:cleanup) }
  rescue StandardError => e
    puts 'Error: Start failed'
    puts e.message
  end

  puts "OK\n"
  yield
end
stop(daemon) click to toggle source
# File lib/eyecare/daemon.rb, line 38
def self.stop(daemon)
  daemon = Daemon.new(pid_file: daemon) if daemon.is_a?(String)

  begin
    unless daemon.started?
      puts 'Not started or pid file is missing'
      return false
    end

    print 'Stopping...'
    pid = daemon.pid
    return false unless daemon.running?
    Process.kill('INT', pid)
    puts 'OK'
  rescue StandardError => e
    puts 'Error: Stop failed'
    puts e.inspect
  end
end

Public Instance Methods

pid() click to toggle source
# File lib/eyecare/daemon.rb, line 66
def pid
  read_pid rescue 0
end
running?() click to toggle source
# File lib/eyecare/daemon.rb, line 70
def running?
  process_running?(pid)
end
stale_pid?() click to toggle source
# File lib/eyecare/daemon.rb, line 62
def stale_pid?
  !process_running?(read_pid) rescue false
end
started?() click to toggle source
# File lib/eyecare/daemon.rb, line 58
def started?
  File.file?(pid_file)
end

Private Instance Methods

cleanup() click to toggle source
# File lib/eyecare/daemon.rb, line 80
def cleanup
  File.unlink(pid_file) rescue false
end
process_running?(pid) click to toggle source
# File lib/eyecare/daemon.rb, line 75
def process_running?(pid)
  return false unless pid && pid != 0
  system("kill -s 0 #{pid}")
end
read_pid() click to toggle source
# File lib/eyecare/daemon.rb, line 84
def read_pid
  pid = nil
  File.open(pid_file, 'r') do |f|
    pid = f.read
  end
  pid.to_i
end
write_pid() click to toggle source
# File lib/eyecare/daemon.rb, line 92
def write_pid
  FileUtils.mkdir_p(File.dirname(pid_file))

  pid = Process.pid
  File.open(pid_file, 'w') do |f|
    f.write(pid)
  end
end