Skip to content

Commit

Permalink
Add options and daemonization to server
Browse files Browse the repository at this point in the history
  • Loading branch information
Mat Brown committed Apr 1, 2010
1 parent 71ffc0a commit 9b57f4c
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 2 deletions.
23 changes: 21 additions & 2 deletions bin/rake-server
@@ -1,5 +1,24 @@
#!/usr/bin/env ruby

require 'optparse'
require File.join(File.dirname(__FILE__), '..', 'lib', 'rake_server')

RakeServer::Server.run(ARGV)
options = {}
OptionParser.new do |opts|
opts.banner = "Usage: rake-server [options] [startup-tasks] (start|stop|run)"

opts.on("-q", "--quiet", "Don't output anything") { |q| options[:quiet] = q }
opts.on("-h", "--host [HOST]", "Host to listen on") { |h| options[:host] = h }
opts.on("-p", "--port [PORT]", "Port to listen on") { |p| options[:port] = p }
end.parse!

command = ARGV.shift
case command
when 'start'
RakeServer::Server.start(ARGV, options)
when 'run'
RakeServer::Server.run(ARGV, options)
when 'stop'
RakeServer::Server.stop(options)
else
abort("Unknown command #{command.inspect}")
end
31 changes: 31 additions & 0 deletions lib/rake_server/server.rb
Expand Up @@ -10,14 +10,45 @@
module RakeServer
class Server < EventMachine::Protocols::LineAndTextProtocol
class <<self
def start(eager_tasks, options = {})
pid_file = File.join(pid_dir(options), "rake-server.pid")
pid = fork do
fork do
File.open(pid_file, 'w') { |f| f << Process.pid }
run(eager_tasks, options)
end
end
Process.waitpid(pid)
end

def stop(options = {})
pid_file = File.join(pid_dir(options), "rake-server.pid")
pid = IO.read(pid_file).to_i
Process.kill("TERM", pid)
FileUtils.rm(pid_file)
end

def run(eager_tasks, options = {})
options = DEFAULT_OPTIONS.merge(options)
EventMachine.run do
Rake.application.init
Rake.application.load_rakefile
eager_tasks.each { |task| Rake.application[task].invoke }
EventMachine.start_server(options[:host], options[:port], self)
unless options[:quiet]
puts "rake-server listening on #{options[:host]}:#{options[:port]}"
end
end
end

private

def pid_dir(options)
pid_dir = options[:pid_dir] || File.join(Dir.pwd, 'tmp', 'pids')
unless File.directory?(pid_dir)
raise "PID dir #{pid_dir} does not exist -- can't daemonize"
end
pid_dir
end
end

Expand Down
1 change: 1 addition & 0 deletions tmp/.gitignore
@@ -0,0 +1 @@
*

0 comments on commit 9b57f4c

Please sign in to comment.