Class: Dctl::Daemon

Inherits:
Object
  • Object
show all
Includes:
Daemonize
Defined in:
lib/dctl/daemon.rb

Overview

This class is used to perform daemon commands.

Constant Summary

Constants included from Daemonize

Daemonize::VERSION

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Daemonize

daemonize, safefork

Constructor Details

#initialize(cmd, pidpath, check = true) ⇒ Daemon

Returns a new instance of Daemon.



10
11
12
13
14
15
16
17
18
# File 'lib/dctl/daemon.rb', line 10

def initialize(cmd, pidpath, check=true)
  @app_path = File.expand_path(Daemon::which(cmd) || cmd)
  if check
    raise Errno::EISDIR, @app_path if File.directory? @app_path
    raise Errno::ENOENT, @app_path until File.file? @app_path
    raise Errno::EACCES, @app_path until File.executable? @app_path
  end
  @pidfile = PidFile.new pidpath, File.basename(cmd)
end

Class Method Details

.which(prog_name) ⇒ Object



20
21
22
# File 'lib/dctl/daemon.rb', line 20

def self.which(prog_name)
  ENV["PATH"].split(':').map { |p| File.join p, prog_name }.find { |p| File.file? p and File.executable? p }
end

Instance Method Details

#restart(args = [], stdin = '/dev/null', stdout = '/dev/null', stderr = '/dev/null') ⇒ Object



36
37
38
# File 'lib/dctl/daemon.rb', line 36

def restart(args=[], stdin='/dev/null', stdout='/dev/null', stderr='/dev/null')
  stop ; sleep 2 ; start(args, stdin, stdout, stderr)
end

#run(args = []) ⇒ Object



44
45
46
47
# File 'lib/dctl/daemon.rb', line 44

def run(args = [])
  @pidfile.write
  exec "#{@app_path} #{args.join ' '}"
end

#start(args = [], stdin = '/dev/null', stdout = '/dev/null', stderr = '/dev/null') ⇒ Object



24
25
26
27
28
29
# File 'lib/dctl/daemon.rb', line 24

def start(args=[], stdin='/dev/null', stdout='/dev/null', stderr='/dev/null')
  @pidfile.write
  daemonize(stdin, stdout, stderr)
  @pidfile.delete
  run args
end

#statusObject



49
50
51
52
53
# File 'lib/dctl/daemon.rb', line 49

def status
  (pid = @pidfile.read) rescue return :unhandled
  Process.kill 0, pid rescue return :not_running
  :running
end

#stopObject



31
32
33
34
# File 'lib/dctl/daemon.rb', line 31

def stop
  Process.kill 'TERM', @pidfile.read
  zap
end

#zapObject



40
41
42
# File 'lib/dctl/daemon.rb', line 40

def zap
  @pidfile.delete
end