Attributes
Public Class Methods
new(worker, log_file, seconds_between_runs = DEFAULT_SLEEP_SECONDS)
# File lib/harbor/daemon.rb, line 16 16: def initialize(worker, log_file, seconds_between_runs = DEFAULT_SLEEP_SECONDS) 17: @worker = worker 18: 19: # The template may include the tag %PID to be replaced with 20: # the PID of the forked worker process. Don't use @log_file 21: # directly, use self.log_file 22: @log_file_template = log_file 23: 24: @seconds_between_runs = seconds_between_runs 25: end
Public Instance Methods
cleanup!()
# File lib/harbor/daemon.rb, line 94 94: def cleanup! 95: worker.cleanup! if worker.respond_to?(:cleanup!) 96: end
detach()
# File lib/harbor/daemon.rb, line 35 35: def detach 36: srand 37: fork and exit 38: Process.setsid # detach -- we want to be able to close our shell! 39: 40: unless self.log_file.is_a?(::File) 41: log_directory = ::File.dirname(self.log_file) 42: ::File.mkdir_p(log_directory) unless ::File.directory?(log_directory) 43: end 44: 45: redirect_io(@log_file) 46: end
log_file()
# File lib/harbor/daemon.rb, line 27 27: def log_file 28: @log_file ||= if @log_file_template.is_a?(::File) 29: @log_file_template 30: else 31: @log_file_template.gsub('%PID', Process.pid.to_s) 32: end 33: end
run()
# File lib/harbor/daemon.rb, line 48 48: def run 49: @restart = false 50: @alive = true 51: 52: # graceful restart 53: trap(:HUP) do 54: logger.info "Restarting gracefully." if logger 55: @restart = true 56: @alive = nil 57: @worker.alive = nil 58: end 59: 60: # graceful shutdown 61: trap(:QUIT) do 62: logger.info "Shutting down gracefully." if logger 63: @alive = nil 64: @worker.alive = nil 65: end 66: 67: # quick exit 68: [:TERM, :INT].each do |sig| 69: trap(sig) do 70: logger.info "Shutting down NOW" if logger 71: cleanup! 72: 73: exit!(0) 74: end 75: end 76: 77: begin 78: @worker.run 79: sleep(@seconds_between_runs) if @alive 80: end while @alive 81: 82: if @restart 83: logger.info "Starting new daemon..." 84: fork do 85: Dir.chdir(START_CONTEXT[:cwd]) 86: exec(START_CONTEXT[:cmd], *START_CONTEXT[:argv]) 87: end 88: end 89: 90: logger.info "Shutting down..." if logger 91: cleanup! 92: end