APPS_ROOT = Dir.glob("/var/www/apps/*/current/config/app.god") # Helper Methods def unicorn(w, config, options = {}) rails_root = options[:rails_root] rails_env = options[:rails_env] || 'production' unicorn_group = options[:app] || options[:name] || 'default' unicorn_name = "#{unicorn_group}-unicorn" unicorn_bin = options[:bin_unicorn] || 'bootup_unicorn_rails' unicorn_pid = options[:unicorn_pid] || "#{rails_root}/log/unicorn.pid" unicorn_config = "#{rails_root}/config/unicorn.rb" unicorn_start = options[:start_cmd] || "cd #{rails_root} && #{unicorn_bin} -c #{unicorn_config} -E #{rails_env} -D" # QUIT gracefully shuts down workers unicorn_stop = options[:stop_cmd] || "kill -QUIT `cat #{unicorn_pid}`" # USR2 causes the master to re-create itself and spawn a new worker pool unicorn_restart = options[:restart_cmd] || "kill -USR2 `cat #{unicorn_pid}`" w.name = unicorn_name w.group = unicorn_group w.start = unicorn_start w.stop = unicorn_stop w.restart = unicorn_restart w.start_grace = 20.seconds w.restart_grace = 20.seconds w.pid_file = unicorn_pid w.behavior(:clean_pid_file) generic_monitor(w, config, rails_root, options) end def generic_monitor(w, config, rails_root, options = {}) w.uid = options[:user] || 'deploy' w.gid = options[:group] || 'www-data' w.interval = 60.seconds # default # determine the state on startup w.transition(:init, { true => :up, false => :start }) do |on| on.condition(:process_running) do |c| c.running = true end end # determine when process has finished starting w.transition([:start, :restart], :up) do |on| on.condition(:process_running) do |c| c.running = true end # failsafe on.condition(:tries) do |c| c.times = 5 c.transition = :start end end # start if process is not running w.transition(:up, :start) do |on| on.condition(:process_exits) do |c| end end # restart if memory or cpu is too high w.transition(:up, :restart) do |on| on.condition(:memory_usage) do |c| c.interval = 20 c.above = options[:memory_limit] || 150.megabytes c.times = [3, 5] end on.condition(:cpu_usage) do |c| c.interval = 20 c.above = options[:cpu_limit] || 50.percent c.times = [3, 5] end end # lifecycle w.lifecycle do |on| on.condition(:flapping) do |c| c.to_state = [:start, :restart] c.times = 5 c.within = 5.minute c.transition = :unmonitored c.retry_in = 10.minutes c.retry_times = 5 c.retry_within = 2.hours end end end God.log_level = :info puts "God is loading the apps now..." APPS_ROOT.each do |app| begin puts "Loading app: #{app}" God.load app puts "Done" rescue Exception => e puts "Failed! #{e}" end end