augustash / capistrano-ash

August Ash recipes for Capistrano
http://augustash.com
MIT License
73 stars 12 forks source link

Add exception handling to backup:cleanup task #37

Closed grafikchaos closed 11 years ago

grafikchaos commented 11 years ago

I don't know if it was caused by deploying to multiple servers that had different number of releases or what but there was an error that was occurring when attempting to fix permissions on the files and directories before removing them.

I know our Drupal recipe complains about that quite a bit (mostly due to the chaos modules changing ownership of directories) but I can't think of any important reason why I a failure in a pruning/cleanup task should block a deployment.

namespace :backup do
  desc <<-DESC
    Clean up old backups. By default, the last 10 backups are kept on each \
    server (though you can change this with the keep_backups variable). All \
    other backups are removed from the servers. By default, this \
    will use sudo to clean up the old backups, but if sudo is not available \
    for your environment, set the :use_sudo variable to false instead.
  DESC
  task :cleanup, :except => { :no_release => true } do
    count = fetch(:keep_backups, 10).to_i
    if count >= backups.length
      logger.important "no old backups to clean up"
    else
      logger.info "keeping #{count} of #{backups.length} backups"

      begin
        archives = (backups - backups.last(count)).map { |backup|
          File.join(backups_path, backup) }.join(" ")

        # fix permissions on the the files and directories before removing them
        archives.split(" ").each do |backup|
          set_perms_dirs("#{backup}", 755)
          set_perms_files("#{backup}", 644)
        end

        try_sudo "rm -rf #{archives}"
      rescue Exception => e
        logger.important e.message
      end
    end
  end
end