在我们的部署脚本中,我们使用以下代码片段重新启动独角兽:
desc "Zero downtime restart of Unicorn"
task :restart do
run "kill -s USR2 unicorn_pid"
end
主进程分叉,启动新工作人员,然后杀死旧工作人员。但现在似乎新主人杀死了旧主人并在新孩子完全启动之前接管了任何新连接。preload_app false
由于我们使用新工作人员禁用了应用程序的预加载,因此启动大约需要 30 - 60 秒。在此期间,新连接/网站挂起。如何避免这种情况,所以只有在新的子节点完全启动并准备好服务器请求时才让新的主节点接管?:)
更新:
我的 unicorn.rb 看起来像这样:
# name of application
application = "myapp"
# environment specific stuff
case ENV["RAILS_ENV"]
when "integration", "staging"
worker_processes 1
when "production"
worker_processes 4
else
raise "Invalid runtime environment '#{ENV["RAILS_ENV"]}'"
end
# set directories
base_dir = "/srv/#{application}/current"
shared_path = "/srv/#{application}/shared"
working_directory base_dir
# maximum runtime of requests
timeout 300
# multiple listen directives are allowed
listen "#{shared_path}/unicorn.sock", :backlog => 64
# location of pid file
pid "#{shared_path}/pids/unicorn.pid"
# location of log files
stdout_path "#{shared_path}/log/unicorn.log"
stderr_path "#{shared_path}/log/unicorn.err"
# combine REE with "preload_app true" for memory savings
# http://rubyenterpriseedition.com/faq.html#adapt_apps_for_cow
preload_app false
if GC.respond_to?(:copy_on_write_friendly=)
GC.copy_on_write_friendly = true
end
before_exec do |server|
# see http://unicorn.bogomips.org/Sandbox.html
ENV["BUNDLE_GEMFILE"] = "#{base_dir}/Gemfile"
end
before_fork do |server, worker|
# the following is highly recomended for "preload_app true"
if defined?(ActiveRecord::Base)
ActiveRecord::Base.connection.disconnect!
end
if defined?(Sequel::Model)
Sequel::DATABASES.each{ |db| db.disconnect }
end
# This allows a new master process to incrementally
# phase out the old master process with SIGTTOU to avoid a
# thundering herd (especially in the "preload_app false" case)
# when doing a transparent upgrade. The last worker spawned
# will then kill off the old master process with a SIGQUIT.
old_pid = "#{server.config[:pid]}.oldbin"
if old_pid != server.pid
begin
sig = (worker.nr + 1) >= server.worker_processes ? :QUIT : :TTOU
Process.kill(sig, 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|
if defined?(ActiveRecord::Base)
ActiveRecord::Base.establish_connection
end
end
我认为主要问题是没有child_ready
钩子。和before_fork
被after_hook
称为“为时过早”。我想我可以在钩子中添加一些逻辑after_fork
来以某种方式检测孩子何时准备好......但我希望有一个更简单的解决方案?:)