Skip to content

Instantly share code, notes, and snippets.

@telent
Created May 28, 2011 21:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save telent/997241 to your computer and use it in GitHub Desktop.
Save telent/997241 to your computer and use it in GitHub Desktop.
Thin-Prefork - a real-world example
#!/usr/bin/env ruby
require 'rticulate'
require 'thin/prefork'
require 'thin/prefork/project'
require 'projectr/watch_changes'
debugging = ARGV.member?("-d")
if debugging then
stderr=$stderr.dup
rack_workers=1
else
stderr=IO.popen("logger -t 'rticulate' -p local1.info","w")
stderr.sync=true
rack_workers=Env['rack_workers'] || 3
end
url=URI.parse(Env['rackurl'])
pid=Env['pidfile']
# this trick from http://stackoverflow.com/questions/42566
local_addr=UDPSocket.open {|s| s.connect('10.0.0.1',1); s.addr.last }
module NotifyVarnish
def on_register
# the master process needs its own db handle which children don't
# interfere with when they call DB.disconnect on startup
@db ||= Sequel.connect(Env['database'])
@db << "insert into varnish_backends (address) values ('#{@host}:#{@port}');"
@db << "notify varnish;"
super
end
def on_start
# existing database connctions were opened by parent, so shut them down
# cos they won't work anyway
DB.disconnect
end
def on_unregister
@db << "delete from varnish_backends where address = '#{@host}:#{@port}';"
@db << "notify varnish;"
super
end
end
project=Projectr::Project[:rticulate]
project.load!
server=Thin::Prefork::Project.new(:app=>Rticulate.app,
:project=>project,
:host=>local_addr, :port=>url.port,
:stderr=>stderr,
:pid_file=>pid,
:worker_mixins=>NotifyVarnish,
:num_workers=>rack_workers)
Signal.trap("TERM") do
warn "Terminating children"
server.stop!
exit 0
end
Signal.trap("HUP") do
warn "Reloading"
server.reload!
end
if Env['environment']=='development' then
server.add_io_handler(project.watch_changes) do |o|
if o.changed_files.present? then
server.reload!
end
end
end
server.run!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment