Module: Daemonism

Included in:
Daemonite
Defined in:
lib/daemonite.rb

Constant Summary collapse

DAEMONISM_DEFAULT_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_cmds    => [],
  :runtime_opts    => [],
  :runtime_proc    => nil,
  :cmdl_info       => nil,
  :cmdl_parsing    => true,
  :cmdl_operation  => 'start',
  :kill_amount     => 100
}
@@daemonism_restart =
false

Instance Method Summary collapse

Instance Method Details

#daemonism(opts = {}, &block) ⇒ Object



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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
# File 'lib/daemonite.rb', line 40

def daemonism(opts={},&block)
  @at_exit = nil
  @at_startup = nil
  @at_setup = nil

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

  # set more default options and do other stuff
  opts[:block] = nil
  instance_exec(opts,&block) if block_given?


  ########################################################################################################################
  # 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_cmds].length > 0 ? '|' : '') + opts[:runtime_cmds].map{|ro| ro[0]}.join('|') + "\n"
      opts[:runtime_opts].each do |ro|
        opt.on(*ro)
      end
      opt.on("--verbose", "-v", "Do not daemonize. Write ouput to console.") { opts[:verbose] = true }
      opt.on("--config=FNAME", "-cFNAME", "Config file location.") { |f,a|
        if File.exists?(opts[:basepath] + '/' + f)
          opts.merge!(Psych::load_file(opts[:basepath] + '/' + f))
        end
      }
      opt.on("--help", "-h", "This text.") { puts opt; ::Kernel::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_cmds].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_cmds].map{|ro| ro[0] }).include?(ARGV[0])
      puts ARGV.options
      ::Kernel::exit
    end
    opts[:cmdl_operation] = ARGV[0]
  end
  ########################################################################################################################
  opts[:runtime_proc].call(opts) unless opts[:runtime_proc].nil?

  ########################################################################################################################
  # call this if you want to change important things such as pidfile after parsing (but before any formal start)
  ########################################################################################################################
  @at_setup.call(opts) if @at_setup

  ########################################################################################################################
  # 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
  unless @@daemonism_restart
    if opts[:cmdl_operation] == "info" && status.call == false
      puts "Server #{opts[:cmdl_info].nil? ? '' : '(' + opts[:cmdl_info].to_s + ') '}not running"
      ::Kernel::exit
    end
    if opts[:cmdl_operation] == "info" && status.call == true
      puts "Server #{opts[:cmdl_info].nil? ? '' : '(' + opts[:cmdl_info].to_s + ') '}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
      ::Kernel::exit
    end
    if %w{start}.include?(opts[:cmdl_operation]) && status.call == true
      puts "Server #{opts[:cmdl_info].nil? ? '' : '(' + opts[:cmdl_info].to_s + ') '}already started"
      ::Kernel::exit
    end
  end

  ########################################################################################################################
  # stop/restart server
  ########################################################################################################################
  unless @@daemonism_restart
    if %w{stop restart}.include?(opts[:cmdl_operation])
      if status.call == false
        puts "Server #{opts[:cmdl_info].nil? ? '' : '(' + opts[:cmdl_info].to_s + ') '}maybe not started?"
      else
        puts "Server #{opts[:cmdl_info].nil? ? '' : '(' + opts[:cmdl_info].to_s + ') '}stopped"
        puts "Waiting while server goes down ..."
        count = 0
        while status.call
          if count > opts[:kill_amount]
            Process.kill "SIGKILL", pid
            File.unlink(opts[:basepath] + '/' + opts[:pidfile])
          else
            if opts[:cmdl_operation] == 'stop'
              Process.kill "SIGTERM", pid
            else
              Process.kill "SIGHUP", pid
            end
          end
          count += 1
          sleep 0.3
        end
      end
      ::Kernel::exit unless opts[:cmdl_operation] == "restart"
    end
  end

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

    retain = $stdout.dup
    Process.daemon unless opts[:verbose]
    retain.puts "Server #{opts[:cmdl_info].nil? ? '' : '(' + opts[:cmdl_info].to_s + ') '}started as PID:#{Process.pid}"
    File.write(opts[:basepath] + '/' + opts[:pidfile],Process.pid) # after daemon, so that we get the forked pid
    Dir.chdir(opts[:basepath])
    ::Kernel::at_exit do
      File.unlink(opts[:basepath] + '/' + opts[:pidfile])
      @at_exit.call(opts) if @at_exit
    end
  end
end

#exitObject



190
# File 'lib/daemonite.rb', line 190

def exit; :exit; end

#on(event, &blk) ⇒ Object Also known as: at



180
181
182
183
184
185
186
187
188
189
# File 'lib/daemonite.rb', line 180

def on(event,&blk)
  case event
    when :exit
      @at_exit = blk
    when :startup
      @at_startup = blk
    when :setup
      @at_setup = blk
  end
end

#on_exit(&blk) ⇒ Object Also known as: at_exit



193
194
195
# File 'lib/daemonite.rb', line 193

def on_exit(&blk)
  on :exit, &blk
end

#on_setup(&blk) ⇒ Object Also known as: at_setup



199
200
201
# File 'lib/daemonite.rb', line 199

def on_setup(&blk)
  on :setup, &blk
end

#on_startup(&blk) ⇒ Object Also known as: at_startup



196
197
198
# File 'lib/daemonite.rb', line 196

def on_startup(&blk)
  on :startup, &blk
end

#setupObject



192
# File 'lib/daemonite.rb', line 192

def setup; :setup; end

#startupObject



191
# File 'lib/daemonite.rb', line 191

def startup; :startup; end

#use(blk) ⇒ Object



202
203
204
# File 'lib/daemonite.rb', line 202

def use(blk)
  instance_eval(&blk)
end