class Fluent::Daemonizer

Public Class Methods

daemonize(pid_path, args = [], &block) click to toggle source
# File lib/fluent/daemonizer.rb, line 21
def self.daemonize(pid_path, args = [], &block)
  new.daemonize(pid_path, args, &block)
end

Public Instance Methods

daemonize(pid_path, args = []) { || ... } click to toggle source
# File lib/fluent/daemonizer.rb, line 25
def daemonize(pid_path, args = [])
  pid_fullpath = File.absolute_path(pid_path)
  check_pidfile(pid_fullpath)

  begin
    Process.daemon(false, false)

    File.write(pid_fullpath, Process.pid.to_s)

    # install signal and set process name are performed by supervisor
    install_at_exit_handlers(pid_fullpath)

    yield
  rescue NotImplementedError
    daemonize_with_spawn(pid_fullpath, args)
  end
end

Private Instance Methods

check_pidfile(pid_path) click to toggle source
# File lib/fluent/daemonizer.rb, line 53
def check_pidfile(pid_path)
  if File.exist?(pid_path)
    if !File.readable?(pid_path) || !File.writable?(pid_path)
      raise Fluent::ConfigError, "Cannot access pid file: #{pid_path}"
    end

    pid =
      begin
        Integer(File.read(pid_path), 10)
      rescue TypeError, ArgumentError
        return # ignore
      end

    begin
      Process.kill(0, pid)
      raise Fluent::ConfigError, "pid(#{pid}) is running"
    rescue Errno::EPERM
      raise Fluent::ConfigError, "pid(#{pid}) is running"
    rescue Errno::ESRCH
    end
  else
    unless File.writable?(File.dirname(pid_path))
      raise Fluent::ConfigError, "Cannot access directory for pid file: #{File.dirname(pid_path)}"
    end
  end
end
daemonize_with_spawn(pid_fullpath, args) click to toggle source
# File lib/fluent/daemonizer.rb, line 45
def daemonize_with_spawn(pid_fullpath, args)
  pid = Process.spawn(*['fluentd'].concat(args))

  File.write(pid_fullpath, pid.to_s)

  pid
end
install_at_exit_handlers(pidfile) click to toggle source
# File lib/fluent/daemonizer.rb, line 80
def install_at_exit_handlers(pidfile)
  at_exit do
    if File.exist?(pidfile)
      File.delete(pidfile)
    end
  end
end