Module: Worker::Daemonizer

Defined in:
lib/buzzcore/thread_utils.rb

Class Method Summary collapse

Class Method Details

.daemonize(aWorkerClass, aConfig = {}) ⇒ Object

Assists in making a daemon script from a Worker. If a block is given, it is assumed to create the worker and return it. Otherwise the Worker is created with no arguments from aWorkerClass Either way, the worker is only created when starting



521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
# File 'lib/buzzcore/thread_utils.rb', line 521

def self.daemonize(aWorkerClass,aConfig={})
  case !ARGV.empty? && ARGV[0]
  when 'start'
    worker = block_given? ? yield(aWorkerClass) : aWorkerClass.new
    if aConfig['no_fork']
      start_no_fork(worker)  
    else
      start(worker)
    end
  when 'stop'
    stop(aWorkerClass)
  when 'restart'
    stop(aWorkerClass)
    worker = block_given? ? yield(aWorkerClass) : aWorkerClass.new
    start(worker)
  else
    puts "Invalid command. Please specify start, stop or restart."
    exit
  end
end

.start(aWorker) ⇒ Object



562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
# File 'lib/buzzcore/thread_utils.rb', line 562

def self.start(aWorker)
  fork do
    Process.setsid
    if child_pid = fork
      Process.detach(child_pid)
    else
      PidFile.store(aWorker.class.pid_filename, Process.pid)
      Dir.chdir(aWorker.class::TempDirectory)
      File.umask 0000
      STDIN.reopen "/dev/null"
      STDOUT.reopen "/dev/null", "a" # problems here
      STDERR.reopen STDOUT
      trap('TERM') do 
        puts "Daemonizer::start TERM"
        aWorker.stop
        aWorker.wait_for_stopped()
        exit
      end
      trap('HUP','IGNORE') # ignore SIGHUP - required for Capistrano
      aWorker.main_proc
    end
  end
end

.start_no_fork(aWorker) ⇒ Object



542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
# File 'lib/buzzcore/thread_utils.rb', line 542

def self.start_no_fork(aWorker)
  PidFile.store(aWorker.class.pid_filename, Process.pid)
  Dir.chdir(aWorker.class::TempDirectory)
  trap('TERM') do 
    begin
      puts "Daemonizer::start_no_fork TERM"
      #puts aWorker.inspect
      aWorker.stop
      puts "after worker stop"
      aWorker.wait_for_stopped()
      puts "after worker stop wait"
    rescue Exception => e
      puts "Exception: "+e.inspect
    end
    exit
  end
  trap('HUP','IGNORE') unless is_windows?  # ignore SIGHUP - required for Capistrano
  aWorker.main_proc
end

.stop(aWorkerClass) ⇒ Object



586
587
588
589
590
591
592
593
594
# File 'lib/buzzcore/thread_utils.rb', line 586

def self.stop(aWorkerClass)
  if !File.file?(aWorkerClass.pid_filename)
    puts "Pid file not found. Is the aWorker started?"
    exit
  end
  pid = PidFile.recall(aWorkerClass.pid_filename)
  pid && Process.kill("TERM", pid)
  FileUtils.rm(aWorkerClass.pid_filename)
end