Module: ActsAsFerret::Server::UnixDaemon

Included in:
Server
Defined in:
lib/acts_as_ferret/server/unix_daemon.rb

Overview

methods for becoming a daemon on Unix-like operating systems

Instance Method Summary collapse

Instance Method Details

#ensure_stoppedObject



61
62
63
64
65
66
67
68
69
70
# File 'lib/acts_as_ferret/server/unix_daemon.rb', line 61

def ensure_stopped
  if pid = read_pid_file
    if process_exists(pid)
      raise "ferret_server may already be running, a pid file exists: #{@cfg.pid_file} and a ferret_server process exists with matching pid #{pid}"
    else
      $stdout.puts("removing stale pid file...")
      File.unlink(@cfg.pid_file) if File.exist?(@cfg.pid_file)
    end
  end
end

#platform_daemon(&block) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
# File 'lib/acts_as_ferret/server/unix_daemon.rb', line 8

def platform_daemon (&block)
  safefork do
    write_pid_file
    trap("TERM") { exit(0) }
    sess_id = Process.setsid
    STDIN.reopen("/dev/null")
    STDOUT.reopen("#{Rails.root}/log/ferret_server.out", "a")
    STDERR.reopen(STDOUT)
    block.call
  end
end

#process_exists(pid) ⇒ Object

Check for existence of ferret_server process with PID from pid file checked on ubuntu and OSX only



75
76
77
78
79
80
# File 'lib/acts_as_ferret/server/unix_daemon.rb', line 75

def process_exists(pid)
  ps = IO.popen("ps -fp #{pid}", "r")
  process = ps.to_a[1]
  ps.close
  process =~ /ferret_server/
end

#read_pid_fileObject



56
57
58
# File 'lib/acts_as_ferret/server/unix_daemon.rb', line 56

def read_pid_file
  File.read(@cfg.pid_file).to_i if File.exist?(@cfg.pid_file)
end

#safefork(&block) ⇒ Object



37
38
39
40
41
42
43
44
45
# File 'lib/acts_as_ferret/server/unix_daemon.rb', line 37

def safefork (&block)
  @fork_tries ||= 0
  fork(&block)
rescue Errno::EWOULDBLOCK
  raise if @fork_tries >= 20
  @fork_tries += 1
  sleep 5
  retry
end

#stopObject

stop the daemon, nicely at first, and then forcefully if necessary



22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/acts_as_ferret/server/unix_daemon.rb', line 22

def stop
  pid = read_pid_file
  raise "ferret_server doesn't appear to be running" unless pid
  $stdout.puts("stopping ferret server...")
  Process.kill("TERM", pid)
  30.times { Process.kill(0, pid); sleep(0.5) }
  $stdout.puts("using kill -9 #{pid}")
  Process.kill(9, pid)
rescue Errno::ESRCH => e
  $stdout.puts("process #{pid} has stopped")
ensure
  File.unlink(@cfg.pid_file) if File.exist?(@cfg.pid_file)
end

#write_pid_fileObject

create the PID file and install an at_exit handler



49
50
51
52
53
# File 'lib/acts_as_ferret/server/unix_daemon.rb', line 49

def write_pid_file
  ensure_stopped
  open(@cfg.pid_file, "w") {|f| f << Process.pid << "\n"}
  at_exit { File.unlink(@cfg.pid_file) if read_pid_file == Process.pid }
end