Skip to content

Instantly share code, notes, and snippets.

@rubytastic
Created September 27, 2013 22:33
Show Gist options
  • Save rubytastic/0eb452d8b644b0c593f1 to your computer and use it in GitHub Desktop.
Save rubytastic/0eb452d8b644b0c593f1 to your computer and use it in GitHub Desktop.
require 'new_relic/recipes'
require 'bundler/capistrano'
require './config/boot'
require 'whenever/capistrano'
require 'rvm/capistrano'
require 'bundler/capistrano'
set :application, "books"
set :whenever_command, "bundle exec whenever"
set :rvm_type, :system
set :rvm_ruby_string, 'ruby-2.0.0-head@books'
set :scm, :git
#set :repository, "root@xxx:/srv/books.git"
set :repository, "/srv/books.git"
#set :deploy_via, :copy
set :branch, "origin/master"
set :migrate_target, :current
set :ssh_options, {:forward_agent => true}
set :rails_env, "production"
set :deploy_to, "/srv/books"
set :normalize_asset_timestamps, false
set :keep_releases, 2
after "deploy:update", "deploy:cleanup"
set :user, "root"
set :group, ""
set :use_sudo, false
default_run_options[:pty] = true
#set :port, 5984
#ssh_options[:port] = 5984
set :port, 22
ssh_options[:port] = 22
role :web, "109.74.206.195"
role :app, "109.74.206.195"
role :db, "109.74.206.195", :primary => true
set(:latest_release) { fetch(:current_path) }
set(:release_path) { fetch(:current_path) }
set(:current_release) { fetch(:current_path) }
set(:current_revision) { capture("cd #{current_path}; git rev-parse --short HEAD").strip }
set(:latest_revision) { capture("cd #{current_path}; git rev-parse --short HEAD").strip }
set(:previous_revision) { capture("cd #{current_path}; git rev-parse --short HEAD@{1}").strip }
default_environment["RAILS_ENV"] = 'production'
before :deploy, 'mysql:backup'
# "newrelic:notice_deployment", temp disable newrelic deployments
after "deploy:update", "deploy:rvm:trust_rvmrc"
namespace :deploy do
namespace :assets do
task :precompile, :roles => :web, :except => {:no_release => true} do
# Check if assets have changed. If not, don't run the precompile task - it takes a long time.
force_compile = false
changed_asset_count = 0
begin
from = source.next_revision(current_revision)
asset_locations = 'app/assets/'
changed_asset_count = capture("cd #{latest_release} && #{source.local.log(from)} #{asset_locations} | wc -l").to_i
rescue Exception => e
logger.info "Error: #{e}, forcing precompile"
force_compile = false
end
if changed_asset_count > 0 || force_compile
logger.info "#{changed_asset_count} assets have changed. Pre-compiling"
run %Q{cd #{latest_release} && #{rake} RAILS_ENV=#{rails_env} #{asset_env} assets:precompile}
else
logger.info "#{changed_asset_count} assets have changed. Skipping asset pre-compilation"
end
end
#task :precompile, :roles => :web, :except => {:no_release => true} do
# run %Q{cd #{latest_release} && #{rake} RAILS_ENV=#{rails_env} #{asset_env} assets:precompile}
#end
end
namespace :web do
task :disable, :roles => :web do
require 'erb'
on_rollback { run "rm #{shared_path}/system/maintenance.html" }
template = File.read('app/views/layouts/maintenance.html')
page = ERB.new(template).result(binding)
put page, "#{shared_path}/system/maintenance.html", :mode => 0644
end
end
namespace :db do
desc "Reset production database"
task :reset do
run "cd #{current_release}"
run "cd #{current_release}; #{rake} db:reset;"
run "cd #{current_release}; rake db:schema:load"
run "cd #{current_release}; rake db:seed"
run "cd #{current_release}; rake db:seed_fu"
run "cd #{current_release}; rake log:clear"
end
end
namespace :rvm do
task :trust_rvmrc do
run "rvm rvmrc trust #{release_path}"
end
end
desc "Deploy your application"
task :default do
deploy.god.stop
deploy.god.start
cleanlog
update
migrate
#sitemap
end
desc "Setup your git-based deployment app."
task :setup, :except => {:no_release => true} do
dirs = [deploy_to, shared_path]
dirs += shared_children.map { |d| File.join(shared_path, d) }
run "#{try_sudo} mkdir -p #{dirs.join(' ')} && #{try_sudo} chmod g+w #{dirs.join(' ')}"
run "git clone #{repository} #{current_path}"
end
task :cold do
update
migrate
end
desc "Clearing the production log"
task :cleanlog do
run "cd #{current_path}; rake log:clear"
end
desc "Refresh the sitemap."
task :sitemap do
run "cd #{current_path}; rake sitemap:refresh"
end
task :update do
transaction do
update_code
end
end
desc "Update the deployed code."
task :update_code, :except => {:no_release => true} do
run "cd #{current_path}; git fetch origin; git reset --hard #{branch}"
finalize_update
end
desc "Update the database (overwritten to avoid symlink)"
task :migrations do
transaction do
update_code
end
migrate
restart
end
task :finalize_update, :except => {:no_release => true} do
run "chmod -R g+w #{latest_release}" if fetch(:group_writable, true)
# mkdir -p is making sure that the directories are there for some SCM's that don't
# save empty folders
# ln -sf #{shared_path}/database.yml #{latest_release}/config/database.yml
run <<-CMD
rm -rf #{latest_release}/log #{latest_release}/public/system #{latest_release}/tmp/pids &&
mkdir -p #{latest_release}/public &&
mkdir -p #{latest_release}/tmp &&
ln -s #{shared_path}/log #{latest_release}/log &&
ln -s #{shared_path}/system #{latest_release}/public/system &&
ln -s #{shared_path}/pids #{latest_release}/tmp/pids
CMD
if fetch(:normalize_asset_timestamps, true)
stamp = Time.now.utc.strftime("%Y%m%d%H%M.%S")
asset_paths = fetch(:public_children, %w(images stylesheets javascripts)).map { |p| "#{latest_release}/public/#{p}" }.join(" ")
run "find #{asset_paths} -exec touch -t #{stamp} {} ';'; true", :env => {"TZ" => "UTC"}
end
end
desc "Zero-downtime restart of Unicorn"
task :restart, :except => {:no_release => true} do
run "#{try_sudo} touch #{File.join(current_path, 'tmp', 'restart.txt')}"
run "kill -s USR2 `cat /srv/books/shared/tmp/pids/unicorn.pid`"
deploy.god.stop
deploy.god.start
end
desc "reload the database with seed data"
task :seed do
run "cd #{current_path}; bundle exec rake db:seed RAILS_ENV=#{rails_env}"
end
desc "Start unicorn"
task :start, :except => {:no_release => true} do
run "cd #{current_path} ; bundle exec unicorn_rails -c config/unicorn.rb -D"
deploy.god.start
end
desc "Stop unicorn"
task :stop, :except => {:no_release => true} do
run "kill -s QUIT `cat /srv/books/shared/tmp/pids/unicorn.pid`"
end
namespace :god do
desc "Manages the God Process Monitoring daemon"
[:stop, :start, :restart].each do |action|
desc "#{action.to_s.capitalize} God Process Monitoring"
task action, :roles => :web do
invoke_command "/etc/init.d/god #{action.to_s}", :via => run_method
end
end
end
namespace :rollback do
desc "Moves the repo back to the previous version of HEAD"
task :repo, :except => {:no_release => true} do
set :branch, "HEAD@{1}"
deploy.default
end
desc "Rewrite reflog so HEAD@{1} will continue to point to at the next previous release."
task :cleanup, :except => {:no_release => true} do
run "cd #{current_path}; git reflog delete --rewrite HEAD@{1}; git reflog delete --rewrite HEAD@{1}"
end
desc "Rolls back to the previously deployed version."
task :default do
rollback.repo
rollback.cleanup
end
end
end
namespace :mysql do
desc "performs a backup (using mysqldump) in app shared dir"
task :backup, :roles => :db, :only => {:primary => true} do
filename = "#{application}.db_backup.#{Time.now.to_f}.sql.bz2"
filename2 = "#{application}_im.db_backup.#{Time.now.to_f}.sql.bz2"
filepath = "#{shared_path}/backup/#{filename}"
filepath2 = "#{shared_path}/backup/#{filename2}"
text = capture "cat #{deploy_to}/current/config/database.yml"
yaml = YAML::load(text)
on_rollback { run "rm #{filepath}" }
on_rollback { run "rm #{filepath2}" }
run "mysqldump -u #{yaml['production']['username']} -p #{yaml['production']['database']} | bzip2 -c > #{filepath}" do |ch, stream, out|
ch.send_data "#{yaml['production']['password']}\n" if out =~ /^Enter password:/
end
run "mysqldump -u #{yaml['production']['username']} -p books_im | bzip2 -c > #{filepath2}" do |ch, stream, out|
ch.send_data "#{yaml['production']['password']}\n" if out =~ /^Enter password:/
end
end
end
def run_rake(cmd)
run "cd #{current_path}; #{rake} #{cmd}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment