Class: Daemonite

Inherits:
Object
  • Object
show all
Defined in:
lib/daemonite.rb

Constant Summary collapse

OPTS =
{
  :mode            => :debug,
  :verbose         => false,
  :basepath        => File.expand_path(File.dirname($0)),
  :pidfile         => File.basename($0,'.rb') + '.pid',
  :pidwrite        => true,
  :conffile        => File.basename($0,'.rb') + '.conf',
  :runtime_options => [],
  :cmdl_parsing    => true,
  :cmdl_operation  => 'start'
}

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}, &block) ⇒ Daemonite

Returns a new instance of Daemonite.



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
# File 'lib/daemonite.rb', line 34

def initialize(opts={},&block)
  @opts = OPTS.merge(opts)

  if File.exists?(@opts[:basepath] + '/' + @opts[:conffile])
    @opts.merge!(Psych::load_file(@opts[:basepath] + '/' + @opts[:conffile]))
  end

  ########################################################################################################################
  # parse arguments
  ########################################################################################################################
  if @opts[:cmdl_parsing]
    @opts[:cmdl_operation] = "start"
    ARGV.options { |opt|
      opt.summary_indent = ' ' * 4
      opt.banner = "Usage:\n#{opt.summary_indent}ruby #{$PROGRAM_NAME} [options] start|stop|restart|info" + (@opts[:runtime_options].length > 0 ? '|' : '') + @opts[:runtime_options].map{|ro| ro[0]}.join('|') + "\n"
      opt.on("--verbose", "-v", "Do not daemonize. Write ouput to console.") { @opts[:verbose] = true }
      opt.on("--help", "-h", "This text.") { puts opt; exit }
      opt.separator(opt.summary_indent + "start|stop|restart|info".ljust(opt.summary_width+1) + "Do operation start, stop, restart or get information.")
      @opts[:runtime_options].each do |ro|
        opt.separator(opt.summary_indent + ro[0].ljust(opt.summary_width+1) + ro[1])
      end
      opt.parse!
    }
    unless (%w{start stop restart info} + @opts[:runtime_options].map{|ro| ro[0] }).include?(ARGV[0])
      puts ARGV.options
      exit
    end
    @opts[:cmdl_operation] = ARGV[0]
    @at_exit = nil
  end
  ########################################################################################################################

  @opts[:repeat] = nil
  instance_exec(@opts,&block) if block_given?

  ########################################################################################################################
  # status and info
  ########################################################################################################################
  pid = File.read(@opts[:basepath] + '/' + @opts[:pidfile]).to_i rescue pid = -1
  status = Proc.new do
    begin
      Process.getpgid pid
      true
    rescue Errno::ESRCH
      false
    end
  end
  if @opts[:cmdl_operation] == "info" && status.call == false
    puts "Server not running"
    exit
  end
  if @opts[:cmdl_operation] == "info" && status.call == true
    puts "Server running as #{pid}"
    begin
      stats = `ps -o "vsz,rss,lstart,time" -p #{pid}`.split("\n")[1].strip.split(/ +/)
      puts "Virtual:  #{"%0.2f" % (stats[0].to_f/1024)} MiB"
      puts "Resident: #{"%0.2f" % (stats[1].to_f/1024)} MiB"
      puts "Started:  #{stats[2..-2].join(' ')}"
      puts "CPU Time: #{stats.last}"
    rescue
    end
    exit
  end
  if %w{start}.include?(@opts[:cmdl_operation]) && status.call == true
    puts "Server already started"
    exit
  end

  ########################################################################################################################
  # stop/restart server
  ########################################################################################################################
  if %w{stop restart}.include?(@opts[:cmdl_operation])
    if status.call == false
      puts "Server maybe not started?"
    else
      puts "Server stopped"
      puts "Waiting while server goes down ..."
      while status.call
        Process.kill "SIGTERM", pid
        sleep 0.3
      end
    end
    exit unless @opts[:cmdl_operation] == "restart"
  end

  ########################################################################################################################
  # go through user defined startup thingis
  ########################################################################################################################
  @opts[:runtime_options].each do |ro|
    ro[2].call(status.call) if @opts[:cmdl_operation] == ro[0]
  end

  puts "Server started as PID:#{Process.pid}"
  File.write(@opts[:basepath] + '/' + @opts[:pidfile],Process.pid)
  Process.daemon(@opts[:basepath]) unless @opts[:verbose]
  Dir.chdir(@opts[:basepath])
  ::Kernel::at_exit do
    File.unlink(@opts[:basepath] + '/' + @opts[:pidfile])
    @at_exit.call if @at_exit
  end
end

Instance Method Details

#at_exit(&blk) ⇒ Object



139
140
141
# File 'lib/daemonite.rb', line 139

def at_exit(&blk)
  @at_exit = blk
end

#loop!Object



143
144
145
146
147
148
149
150
151
# File 'lib/daemonite.rb', line 143

def loop!
  begin
    loop do
      @opts[:repeat].call(@opts)
    end unless @opts[:repeat].nil?
  rescue => e
    puts "Server stopped due to error (PID:#{Process.pid})"
  end
end

#run(&block) ⇒ Object



136
137
138
# File 'lib/daemonite.rb', line 136

def run(&block)
  @opts[:repeat] = block
end