Skip to content

Instantly share code, notes, and snippets.

@gmontard
Created July 16, 2013 07:04
Show Gist options
  • Save gmontard/6006428 to your computer and use it in GitHub Desktop.
Save gmontard/6006428 to your computer and use it in GitHub Desktop.
Unicorn Conf for Zero downtime Deploy !
require "redis"
worker_processes 8
preload_app true
timeout 600
listen '/tmp/vodeclic.sock', :backlog => 1024
pid '/tmp/vodeclic.pid'
##
# REE
# http://www.rubyenterpriseedition.com/faq.html#adapt_apps_for_cow
if GC.respond_to?(:copy_on_write_friendly=)
GC.copy_on_write_friendly = true
end
before_exec do |server|
ENV["BUNDLE_GEMFILE"] = "/home/vodeclic/public_html/vodeclic/current/Gemfile"
end
before_fork do |server, worker|
##
# When sent a USR2, Unicorn will suffix its pidfile with .oldbin and
# immediately start loading up a new version of itself (loaded with a new
# version of our app). When this new Unicorn is completely loaded
# it will begin spawning workers. The first worker spawned will check to
# see if an .oldbin pidfile exists. If so, this means we've just booted up
# a new Unicorn and need to tell the old one that it can now die. To do so
# we send it a QUIT.
#
# Using this method we get 0 downtime deploys.
# Disconnect since the database connection will not carry over
if defined? ActiveRecord::Base
ActiveRecord::Base.connection_handler.clear_all_connections!
end
old_pid = '/tmp/vodeclic.pid.oldbin'
if File.exists?(old_pid) && server.pid != old_pid
begin
Process.kill("QUIT", File.read(old_pid).to_i)
rescue Errno::ENOENT, Errno::ESRCH
# someone else did our job for us
end
end
end
after_fork do |server, worker|
##
# Unicorn master loads the app then forks off workers - because of the way
# Unix forking works, we need to make sure we aren't using any of the parent's
# sockets, e.g. db connection
# Start up the database connection again in the worker
if defined?(ActiveRecord::Base)
ActiveRecord::Base.establish_connection
end
#CHIMNEY.client.connect_to_server
# Redis and Memcached would go here but their connections are established
# on demand, so the master never opens a socket
if Rails.cache.is_a?(ActiveSupport::Cache::MemCacheStore)
Rails.cache.instance_variable_get(:@data).reset
end
Redis.current.quit
##
# Unicorn master is started as root, which is fine, but let's
# drop the workers to git:git
begin
uid, gid = Process.euid, Process.egid
user, group = 'vodeclic', 'vodeclic'
target_uid = Etc.getpwnam(user).uid
target_gid = Etc.getgrnam(group).gid
worker.tmp.chown(target_uid, target_gid)
if uid != target_uid || gid != target_gid
Process.initgroups(user, target_gid)
Process::GID.change_privilege(target_gid)
Process::UID.change_privilege(target_uid)
end
rescue => e
if RAILS_ENV == 'development'
STDERR.puts "couldn't change user, oh well"
else
raise e
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment