Skip to content

Instantly share code, notes, and snippets.

@dyoder
Created October 13, 2008 21:59
Show Gist options
  • Save dyoder/16615 to your computer and use it in GitHub Desktop.
Save dyoder/16615 to your computer and use it in GitHub Desktop.
module Waves
module Servers
class Base
attr_accessor :application, :host, :port, :server
# returns the PID of the server process
def self.run( application, host, port )
fork { new( application, host, port ).run }
end
def initialize( application, host, port )
@application = application; @host = host ; @port = port
end
# starts server, retrying every few seconds until it succeeds
def run
connect = false
until connect do
begin
call { |server| @server = server ; start }
rescue
Waves::Logger.error e.to_s
sleep 4
end
connect = true
end
end
def start
Waves::Logger.info "Waves server started on #{host}:#{port}."
safe_trap('INT') { stop }
end
def stop
server.stop if server.respond_to? :stop
Waves::Logger.info "Waves server on #{host}:#{port} stopped."
end
end
end
end
module Pages
module Configurations
class Production < Default
reloadable []
log :level => :info, :output => ( :log / 'log.out' )
host '0.0.0.0'
ports [ 3000 ]
application do
run ::Waves::Dispatchers::Default.new
end
server Waves::Servers::Mongrel
end
end
end
require 'live_console'
module Waves
class Manager < Runtime
def self.run( options )
@manager = new( options )
@manager.start
end
def start
daemonize if options[ :daemon ]
set_traps ; start_logger ; start_console
start_debugger if options[ :debugger ]
start_servers ; Process.waitall
end
def stop
Waves::Logger.info "Manager shutting down ..."
@console.stop ; stop_servers ; exit
end
def restart
stop_servers ; start_servers
end
def daemonize
pwd = Dir.pwd ; exit if fork ; Dir.chdir( pwd )
File.umask 0000 ; STDIN.reopen( '/dev/null') ;
STDOUT.reopen( '/dev/null', 'a' ) ; STDERR.reopen( STDOUT )
end
def set_traps
safe_trap( 'HUP' ) { @manager.restart }
safe_trap( 'INT' ) { @manager.stop }
end
def start_logger
Waves::Logger.start
Waves::Logger.info "Waves #{Waves.version} starting up ..."
end
def start_console
@console = LiveConsole.new( config.console )
@console.run
end
def start_debugger
require 'ruby-debug' ; Debugger.start
Debugger.settings[:autoeval] = true if Debugger.respond_to?(:settings)
Waves::Logger.info "ruby-debug enabled"
end
def start_servers
@pids = ( config.ports or [ config.port ] ).map do | port |
config.server.run( config.application, config.host, port )
end
end
def stop_servers
@pids.each { | pid | Process.kill( 'INT', pid ) }
end
end
end
module Waves
module Servers
class Mongrel < Base
def call
Rack::Handler::Mongrel.run( application, :Host => host, :Port => port ) { |server| yield server if block_given? }
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment