Class: Mode::Connector::Daemonizer

Inherits:
Object
  • Object
show all
Defined in:
lib/mode/connector/daemonizer.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Daemonizer

Returns a new instance of Daemonizer.



12
13
14
15
16
17
# File 'lib/mode/connector/daemonizer.rb', line 12

def initialize(options = {})
  @args = options[:args] || []
  @timeout = options[:timeout] || 10
  @pid_file = options[:pid_file] || default_pid_file
  @executable = options[:executable] || default_executable
end

Instance Attribute Details

#argsObject (readonly)

Returns the value of attribute args.



7
8
9
# File 'lib/mode/connector/daemonizer.rb', line 7

def args
  @args
end

#executableObject (readonly)

Returns the value of attribute executable.



10
11
12
# File 'lib/mode/connector/daemonizer.rb', line 10

def executable
  @executable
end

#pid_fileObject (readonly)

Returns the value of attribute pid_file.



9
10
11
# File 'lib/mode/connector/daemonizer.rb', line 9

def pid_file
  @pid_file
end

#timeoutObject (readonly)

Returns the value of attribute timeout.



8
9
10
# File 'lib/mode/connector/daemonizer.rb', line 8

def timeout
  @timeout
end

Instance Method Details

#alive?Boolean

Returns:

  • (Boolean)


19
20
21
22
23
24
25
26
27
28
# File 'lib/mode/connector/daemonizer.rb', line 19

def alive?
  return false unless pid
  Process.kill(0, pid)
  true
rescue Errno::ESRCH, TypeError # PID is NOT running or is zombied
  false
rescue Errno::EPERM
  STDERR.puts "Permission denied for process #{pid}!";
  false
end

#restartObject



30
31
32
33
34
35
36
# File 'lib/mode/connector/daemonizer.rb', line 30

def restart
  begin
    stop
  ensure
    start
  end
end

#startObject



38
39
40
41
42
43
44
45
46
47
48
# File 'lib/mode/connector/daemonizer.rb', line 38

def start
  abort "Mode connector already running" if alive?
  abort "Insufficient permissions to start Mode connector" unless File.executable?(executable)

  if pid = Spoon.spawnp(executable, *args.collect(&:to_s))
    create_pid(pid)
    STDOUT.puts "Mode connector running with pid #{pid}"
  else
    Process.setsid
  end
end

#stopObject



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/mode/connector/daemonizer.rb', line 50

def stop
  abort "Mode connector not running, nothing to stop" unless alive?

  begin
    STDOUT.puts "Stopping process #{pid}..."

    Timeout.timeout(timeout) do
      Process.kill("TERM", pid)
      sleep 1 while alive?
    end
  rescue Timeout::Error
    STDERR.puts "Graceful shutdown timeout, sending KILL signal"
    Process.kill("KILL", pid)
    sleep 0.1 while alive?
  end

  remove_pid
  STDOUT.puts "Mode connector stopped."
end