Class: Daemons::Application

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

Constant Summary collapse

SIGNAL =
(RUBY_PLATFORM =~ /win32/ ? 'KILL' : 'TERM')

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(group, add_options = {}, pid = nil) ⇒ Application

Returns a new instance of Application.


25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/daemons/application.rb', line 25

def initialize(group, add_options = {}, pid = nil)
  @group = group
  @options = group.options.dup
  @options.update(add_options)

  @dir_mode = @dir = @script = nil

  @force_kill_waittime = @options[:force_kill_waittime] || 20

  @show_status_callback = method(:default_show_status)

  unless @pid = pid
    if @options[:no_pidfiles]
      @pid = PidMem.new
    elsif dir = pidfile_dir
      @pid = PidFile.new(dir, @group.app_name, @group.multiple)
    else
      @pid = PidMem.new
    end
  end
end

Instance Attribute Details

#app_argvObject

Returns the value of attribute app_argv


11
12
13
# File 'lib/daemons/application.rb', line 11

def app_argv
  @app_argv
end

#controller_argvObject

Returns the value of attribute controller_argv


12
13
14
# File 'lib/daemons/application.rb', line 12

def controller_argv
  @controller_argv
end

#groupObject (readonly)

the ApplicationGroup the application belongs to


18
19
20
# File 'lib/daemons/application.rb', line 18

def group
  @group
end

#optionsObject (readonly)

my private options


21
22
23
# File 'lib/daemons/application.rb', line 21

def options
  @options
end

#pidObject (readonly)

the Pid instance belonging to this application


15
16
17
# File 'lib/daemons/application.rb', line 15

def pid
  @pid
end

Instance Method Details

#change_privilegeObject


51
52
53
54
55
# File 'lib/daemons/application.rb', line 51

def change_privilege
  user = options[:user]
  group = options[:group]
  CurrentProcess.change_privilege(user, group) if user
end

#default_show_status(daemon = self) ⇒ Object


439
440
441
442
443
# File 'lib/daemons/application.rb', line 439

def default_show_status(daemon = self)
  running = daemon.running?

  puts "#{group.app_name}: #{running ? '' : 'not '}running#{(running and daemon.pid.exist?) ? ' [pid ' + daemon.pid.pid.to_s + ']' : ''}#{(daemon.pid.exist? and not running) ? ' (but pid-file exists: ' + daemon.pid.pid.to_s + ')' : ''}"
end

#exception_logObject

This is a nice little function for debugging purposes: In case a multi-threaded ruby script exits due to an uncaught exception it may be difficult to find out where the exception came from because one cannot catch exceptions that are thrown in threads other than the main thread.

This function searches for all exceptions in memory and outputs them to STDERR (if it is connected) and to a log file in the pid-file directory.


331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
# File 'lib/daemons/application.rb', line 331

def exception_log
  return unless logfile

  require 'logger'

  l_file = Logger.new(logfile)

  # the code below finds the last exception
  e = nil

  ObjectSpace.each_object do |o|
    if ::Exception === o
      e = o
    end
  end

  l_file.info '*** below you find the most recent exception thrown, this will be likely (but not certainly) the exception that made the application exit abnormally ***'
  l_file.error e

  l_file.info '*** below you find all exception objects found in memory, some of them may have been thrown in your application, others may just be in memory because they are standard exceptions ***'

  # this code logs every exception found in memory
  ObjectSpace.each_object do |o|
    if ::Exception === o
      l_file.error o
    end
  end

  l_file.close
end

#logdirObject


65
66
67
68
69
70
71
# File 'lib/daemons/application.rb', line 65

def logdir
  logdir = options[:log_dir]
  unless logdir
    logdir = options[:dir_mode] == :system ? '/var/log' : pidfile_dir
  end
  logdir
end

#logfileObject


93
94
95
# File 'lib/daemons/application.rb', line 93

def logfile
  logdir ? File.join(logdir, logfilename) : nil
end

#logfilenameObject


85
86
87
88
89
90
91
# File 'lib/daemons/application.rb', line 85

def logfilename
  filename = options[:logfilename]
  unless filename
    filename = @group.app_name + '.log'
  end
  filename
end

#output_logfileObject


81
82
83
# File 'lib/daemons/application.rb', line 81

def output_logfile
  (options[:log_output] && logdir) ? File.join(logdir, output_logfilename) : nil
end

#output_logfilenameObject


73
74
75
76
77
78
79
# File 'lib/daemons/application.rb', line 73

def output_logfilename
  filename = options[:output_logfilename]
  unless filename
    filename = @group.app_name + '.output'
  end
  filename
end

#pidfile_dirObject


61
62
63
# File 'lib/daemons/application.rb', line 61

def pidfile_dir
  Pid.dir(@dir_mode || @group.dir_mode, @dir || @group.dir, @script || @group.script)
end

#reloadObject


309
310
311
312
313
314
315
316
317
318
319
320
# File 'lib/daemons/application.rb', line 309

def reload
  if @pid.pid == 0
    zap
    start
  else
    begin
      Process.kill('HUP', @pid.pid)
    rescue
      # ignore
    end
  end
end

#running?Boolean

This function implements a (probably too simle) method to detect whether the program with the pid found in the pid-file is still running. It just searches for the pid in the output of ps ax, which is probably not a good idea in some cases. Alternatives would be to use a direct access method the unix process control system.

Returns:

  • (Boolean)

452
453
454
455
456
457
458
# File 'lib/daemons/application.rb', line 452

def running?
  if @pid.exist?
    return Pid.running?(@pid.pid)
  end

  false
end

#scriptObject


57
58
59
# File 'lib/daemons/application.rb', line 57

def script
  @script || @group.script
end

#show_statusObject


435
436
437
# File 'lib/daemons/application.rb', line 435

def show_status
  @show_status_callback.call(self)
end

#show_status_callback=(function) ⇒ Object


47
48
49
# File 'lib/daemons/application.rb', line 47

def show_status_callback=(function)
  @show_status_callback = method(function)
end

#start(restart = false) ⇒ Object


280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
# File 'lib/daemons/application.rb', line 280

def start(restart = false)
  change_privilege

  unless restart
    @group.create_monitor(self) unless options[:ontop]  # we don't monitor applications in the foreground
  end

  case options[:mode]
    when :none
      # this is only used to daemonize the currently running process
      start_none
    when :exec
      start_exec
    when :load
      start_load
    when :proc
      start_proc
    else
      start_load
  end
end

#start_execObject


140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
# File 'lib/daemons/application.rb', line 140

def start_exec
  if options[:backtrace]
    puts 'option :backtrace is not supported with :mode => :exec, ignoring'
  end

  unless options[:ontop]
    Daemonize.daemonize(output_logfile, @group.app_name)
  else
    Daemonize.simulate(output_logfile)
  end

  # note that we cannot remove the pid file if we run in :ontop mode (i.e. 'ruby ctrl_exec.rb run')
  @pid.pid = Process.pid

  ENV['DAEMONS_ARGV'] = @controller_argv.join(' ')
  # haven't tested yet if this is really passed to the exec'd process...

  started
  Kernel.exec(script, *(@app_argv || []))
end

#start_loadObject


161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
# File 'lib/daemons/application.rb', line 161

def start_load
  unless options[:ontop]
    Daemonize.daemonize(output_logfile, @group.app_name)
  else
    Daemonize.simulate(output_logfile)
  end

  @pid.pid = Process.pid

  # We need this to remove the pid-file if the applications exits by itself.
  # Note that <tt>at_exit</tt> will only be run if the applications exits by calling
  # <tt>exit</tt>, and not if it calls <tt>exit!</tt> (so please don't call <tt>exit!</tt>
  # in your application!
  #
  at_exit do
    begin; @pid.cleanup; rescue ::Exception; end

    # If the option <tt>:backtrace</tt> is used and the application did exit by itself
    # create a exception log.
    if options[:backtrace] && !options[:ontop] && !$daemons_sigterm
      begin; exception_log; rescue ::Exception; end
    end

  end

  # This part is needed to remove the pid-file if the application is killed by
  # daemons or manually by the user.
  # Note that the applications is not supposed to overwrite the signal handler for
  # 'TERM'.
  #
  $daemons_stop_proc = options[:stop_proc]
  trap(SIGNAL) do
    begin
      if $daemons_stop_proc
        $daemons_stop_proc.call
      end
      rescue ::Exception
    end

    begin; @pid.cleanup; rescue ::Exception; end
    $daemons_sigterm = true

    if options[:hard_exit]
      exit!
    else
      exit
    end
  end

  # Now we really start the script...
  $DAEMONS_ARGV = @controller_argv
  ENV['DAEMONS_ARGV'] = @controller_argv.join(' ')

  ARGV.clear
  ARGV.concat @app_argv if @app_argv

  started
  # TODO: begin - rescue - end around this and exception logging
  load script
end

#start_noneObject

this function is only used to daemonize the currently running process (Daemons.daemonize)


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
# File 'lib/daemons/application.rb', line 98

def start_none
  unless options[:ontop]
    Daemonize.daemonize(output_logfile, @group.app_name)
  else
    Daemonize.simulate(output_logfile)
  end

  @pid.pid = Process.pid

  # We need this to remove the pid-file if the applications exits by itself.
  # Note that <tt>at_text</tt> will only be run if the applications exits by calling
  # <tt>exit</tt>, and not if it calls <tt>exit!</tt> (so please don't call <tt>exit!</tt>
  # in your application!
  #
  at_exit do
    begin; @pid.cleanup; rescue ::Exception; end

    # If the option <tt>:backtrace</tt> is used and the application did exit by itself
    # create a exception log.
    if options[:backtrace] && !options[:ontop] && !$daemons_sigterm
      begin; exception_log; rescue ::Exception; end
    end

  end

  # This part is needed to remove the pid-file if the application is killed by
  # daemons or manually by the user.
  # Note that the applications is not supposed to overwrite the signal handler for
  # 'TERM'.
  #
  trap(SIGNAL) do
    begin; @pid.cleanup; rescue ::Exception; end
    $daemons_sigterm = true

    if options[:hard_exit]
      exit!
    else
      exit
    end
  end
end

#start_procObject


222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
# File 'lib/daemons/application.rb', line 222

def start_proc
  return unless p = options[:proc]

  myproc = proc do

    # We need this to remove the pid-file if the applications exits by itself.
    # Note that <tt>at_text</tt> will only be run if the applications exits by calling
    # <tt>exit</tt>, and not if it calls <tt>exit!</tt> (so please don't call <tt>exit!</tt>
    # in your application!
    #
    at_exit do
      begin; @pid.cleanup; rescue ::Exception; end

      # If the option <tt>:backtrace</tt> is used and the application did exit by itself
      # create a exception log.
      if options[:backtrace] && !options[:ontop] && !$daemons_sigterm
        begin; exception_log; rescue ::Exception; end
      end

    end

    # This part is needed to remove the pid-file if the application is killed by
    # daemons or manually by the user.
    # Note that the applications is not supposed to overwrite the signal handler for
    # 'TERM'.
    #
    $daemons_stop_proc = options[:stop_proc]
    trap(SIGNAL) do
      begin
        if $daemons_stop_proc
          $daemons_stop_proc.call
        end
        rescue ::Exception
      end

      begin; @pid.cleanup; rescue ::Exception; end
      $daemons_sigterm = true

      if options[:hard_exit]
        exit!
      else
        exit
      end
    end
    p.call
  end

  unless options[:ontop]
    @pid.pid = Daemonize.call_as_daemon(myproc, output_logfile, @group.app_name)

  else
    Daemonize.simulate(output_logfile)

    myproc.call
  end
  started
end

#startedObject


302
303
304
305
306
307
# File 'lib/daemons/application.rb', line 302

def started
  if pid = @pid.pid
    puts "#{group.app_name}: process with pid #{pid} started."
    STDOUT.flush
  end
end

#stop(no_wait = false) ⇒ Object


362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
# File 'lib/daemons/application.rb', line 362

def stop(no_wait = false)
  unless running?
    zap
    return
  end

  pid = @pid.pid

  # Catch errors when trying to kill a process that doesn't
  # exist. This happens when the process quits and hasn't been
  # restarted by the monitor yet. By catching the error, we allow the
  # pid file clean-up to occur.
  begin
    Process.kill(SIGNAL, pid)
  rescue Errno::ESRCH => e
    puts "#{e} #{pid}"
    puts 'deleting pid-file.'
  end

  unless no_wait
    if @force_kill_waittime > 0
      puts "#{group.app_name}: trying to stop process with pid #{pid}..."
      STDOUT.flush

      begin
        Timeout.timeout(@force_kill_waittime, TimeoutError) do
          while Pid.running?(pid)
            sleep(0.2)
          end
        end
      rescue TimeoutError
        puts "#{group.app_name}: process with pid #{pid} won't stop, we forcefully kill it..."
        STDOUT.flush

        begin
          Process.kill('KILL', pid)
        rescue Errno::ESRCH
        end

        begin
          Timeout.timeout(20, TimeoutError) do
            while Pid.running?(pid)
              sleep(1)
            end
          end
        rescue TimeoutError
          puts "#{group.app_name}: unable to forcefully kill process with pid #{pid}."
          STDOUT.flush
        end
      end
    end

  end

  sleep(0.1)
  unless Pid.running?(pid)
    # We try to remove the pid-files by ourselves, in case the application
    # didn't clean it up.
    begin; @pid.cleanup; rescue ::Exception; end

    puts "#{group.app_name}: process with pid #{pid} successfully stopped."
    STDOUT.flush
  end
end

#zapObject


427
428
429
# File 'lib/daemons/application.rb', line 427

def zap
  @pid.cleanup
end

#zap!Object


431
432
433
# File 'lib/daemons/application.rb', line 431

def zap!
  begin; @pid.cleanup; rescue ::Exception; end
end