Showing posts with label rails. Show all posts
Showing posts with label rails. Show all posts

Wednesday, May 13, 2009

Journey with Thinking Sphinx and Crond

This is my journey through time :)

Environment:
Ruby => 1.8.7-72
Rails => 2.3.2
Thinking-sphinx => 1.1.3


I had a server running thinking-sphinx through crontab but noticed that this was not working so I started doing some debugging to see what was causing the non running thinking-sphinx:index task...

First I Changed crontab to have full path like so: (crontab -e)

*/10 * * * * cd /rails/current && RAILS_ENV=production /usr/local/bin/rake thinking_sphinx:index >> /dev/null 2>&1
This did nothing... Then I changed the output to go to a file to see if this would give me something

*/10 * * * * cd /rails/current && RAILS_ENV=production /usr/local/bin/rake thinking_sphinx:index >> /tmp/sphinx.output 2>&1
This gave me a timestamp ??? Running that exact command from the shell gives me a full reindex without any issues

Then I figured maybe I needed a trace so I moved the cron task to /etc/cron.d/thinking-sphinx.ct and put this in the file

*/10 * * * * cd /rails/current && RAILS_ENV=production /usr/local/bin/rake thinking_sphinx:index --trace >> /tmp/sphinx.output 2>&1
AND THERE IT WAS !!

!!! The bundled mysql.rb driver has been removed from Rails 2.2. Please install the mysql gem and try again: gem install mysql.
Damn I should have know. So its a PATH issue when running rake under cron... Here is the latest /etc/cron.d/thinking-sphinx.ct I have that is now WORKING!!

# ------------- minute (0 - 59)
# | ----------- hour (0 - 23)
# | | --------- day of month (1 - 31)
# | | | ------- month (1 - 12)
# | | | | ----- day of week (0 - 6) (Sunday=0)
# | | | | |
# * * * * * command to be executed

PATH=/usr/local/mysql/bin:/usr/kerberos/sbin:/usr/kerberos/bin:/sbin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin
SHELL=/bin/bash
RAILS_ENV="production"
LD_LIBRARY_PATH=/usr/local/mysql/lib:${LD_LIBRARY_PATH}


# re-index production sphinx every 15 minutes
*/10 * * * * root cd /rails/current && /usr/local/bin/rake thinking_sphinx:index >> /dev/null 2>&1

There are two important settings there setting the PATH with ruby/rakes install path and MySQLs install path. But also the LD_LIBRARY_PATH so that rails can find the MySQL library. I have that set in /etc/profile.d/mysql.sh but cron does not load the profile.

Friday, April 3, 2009

uninitialized constant CGI::Session (NameError)

After upgrading one project to Rails 2.3.2 I got an error on startup uninitialized constant CGI::Session (NameError)
Looking into the source I found that I was loading this class CGI::Session::ActiveRecordStore::Session

After a little hunting on Google I was directed to the Rails release notes and found this section:


script/server has been switched to use Rack, which means it supports any Rack compatible server. script/server will also pick up a rackup configuration file if one exists. By default, it will look for a config.ru file, but you can override this with the -c switch.

CGI::Session::ActiveRecordStore has been replaced by ActiveRecord::SessionStore.

Done!

Monday, November 17, 2008

Mac(OSX) Jruby and Rails 2.2 -- Part 2

Running webrick isn't doing what we want... How about Tomcat? Or maybe Glassfish? Well I have heard that glassfish is VERY EASY, lets checkit out...

Step 1:
~$ sudo jruby -S gem install glassfish
Successfully installed glassfish-0.9.0-universal-java
1 gem installed
Installing ri documentation for glassfish-0.9.0-universal-java...
Installing RDoc documentation for glassfish-0.9.0-universal-java...

DONE... no I'm serious... THAT WAS IT!!!

Lets start the server:

~$ jruby -S glassfish_rails myapp
Nov 17, 2008 7:21:23 PM com.sun.enterprise.glassfish.bootstrap.ASMain main
INFO: Launching GlassFish on Apache Felix OSGi platform
Nov 17, 2008 7:21:23 PM com.sun.enterprise.glassfish.bootstrap.ASMainOSGi findDerbyClient
INFO: Cannot find javadb client jar file, jdbc driver not available
...

Now I can access the rails app at http://localhost:3000/

NICE!!

Here is some more information about the glassfish gem:

-c, --contextroot PATH: change the context root (default: '/')
-p, --port PORT: change server port (default: 3000)
-e, --environment ENV: change rails environment (default: development)
-n --runtimes NUMBER: Number of JRuby runtimes to crete initially
--runtimes-min NUMBER: Minimum JRuby runtimes to crete
--runtimes-max NUMBER: Maximum number of JRuby runtimes to crete
APPLICATION_PATH (optional): Path to the application to be run (default:
current).


This is almost too easy for a development environment...

THIS IS NOT A BENCHMARK BUT even so here is the info...

My laptop with a test app I have and seed data installed thin 1.0 and Glassfish...

With threading:
============
Requests per second: Thin 10 [#/sec]
Requests per second: Glassfish 14 [#/sec]

Without threading:
==============
Requests per second: Thin 3 [#/sec]
Requests per second: Glassfish 2.6 [#/sec]

:) Not what I was hoping for ...

Mac(OSX) Jruby and Rails 2.2

Not Sure why but I wanted to try JRuby and Rails(2.2) new threads...

These are the steps I used to get a application on my mac running with Rails 2.2 and JRuby 1.1.3(I used ports to install JRuby thats why 1.1.3).

Here are the steps:

- First Install JRuby .. # sudo port install jruby

- Fix an annoying warning .. # sudo jruby -S gem install jruby-openssl

- Install rails .. # sudo jruby -S gem install rails

- Install the database connector .. # sudo jruby -S gem install activerecord-jdbc-adapter
  • We Also need to download the mysql java (JDBC) driver
  • Copy mysql-connector-java-x.x.x-bin.jar to $JRUBY_HOME/lib. (/opt/local/share/java/jruby)
  • http://dev.mysql.com/downloads/connector/j/5.1.html

- Upgrade the gem environment .. # sudo jruby -S gem update

- Install latest RubyGems (Rails 2.2 Needs 1.3.1 or higher.. ) .. # sudo jruby -S gem install rubygems-update

- Now you have to force install the update .. # sudo jruby -S update_rubygems

- Install Rails 2.2.1 .. # jruby -S gem install rails -s http://gems.rubyonrails.org

# jruby -S rails myapp
# cd myapp
# vi config/database.yml
  development:
adapter: jdbc
driver: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost/testapp_development
username: root
password:
# vi config/environment.rb
Add this code:

# Bootstrap the Rails environment, frameworks, and default configuration
require File.join(File.dirname(__FILE__), 'boot')
if RUBY_PLATFORM =~ /java/
require 'rubygems'
RAILS_CONNECTION_ADAPTERS = %w(jdbc)
end
# jruby script/server
=> Booting WEBrick...
=> Rails 2.2.1 application started on http://0.0.0.0:4000
=> Ctrl-C to shutdown server; call with --help for options
[2008-11-17 16:40:34] INFO WEBrick 1.3.1
[2008-11-17 16:40:34] INFO ruby 1.8.6 (2008-11-17) [java]
[2008-11-17 16:40:34] INFO WEBrick::HTTPServer#start: pid=13484 port=4000


DONE!

Sunday, September 28, 2008

http and https with different urls in rails

I wanted to do the following on my site:

http://www.cadechristian.com and https://secure.cadechristian.com

I ran in to the problem that the cookie was not valid on BOTH domains and I search for the longest time before I found this solution.

What I found was to put this in the environmnet.rb file: (I'm on rails 2.1)

config.action_controller.session = {
:session_domain => '.cadechristian.com',
:session_key => 'xxxxxxxxxxxxxxxxxxx',
:secret => 'xxxxxxxxxxxxxxxxxxx'
}

I had some issues testing this on my local development environment since I was using just cadechristian as the hostname. The cookie host NEEDS to have the . and then a domainname.com. (minimum two levels)

.something.local is valid but .something is not.. The first DOT is very important for it to work.

Now I installed the ssl_requirement plugin and hardcoded the code where it does the redirect to SSL_HOSTNAME and NONE_SSL_HOSTNAME which I set in my development.rb/production.rb...

Works great....

Friday, August 15, 2008

mysql gem and mysql NOT from RPM

Have you ever seen this:

>> require 'mysql'
LoadError: libmysqlclient.so.15: cannot open shared object file: No such file or directory - /usr/local/lib/ruby/gems/1.8/gems/mysql-2.7/lib/mysql.so
from /usr/local/lib/ruby/gems/1.8/gems/mysql-2.7/lib/mysql.so
from /usr/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:32:in `require'
from /usr/local/lib/ruby/gems/1.8/gems/activesupport-2.1.0/lib/active_support/dependencies.rb:509:in `require'
from /usr/local/lib/ruby/gems/1.8/gems/activesupport-2.1.0/lib/active_support/dependencies.rb:354:in `new_constants_in'
from /usr/local/lib/ruby/gems/1.8/gems/activesupport-2.1.0/lib/active_support/dependencies.rb:509:in `require'
from (irb):2


I found this happens when your environment for mysql is not setup correctly. The fix is easy. All you need is to add a file in the /etc/profile.d directory called mysql.sh with the correct exports and re-login...

[root@heimdull log]# cat /etc/profile.d/mysql.sh
export LD_LIBRARY_PATH=/usr/local/mysql/lib:$LD_LIBRARY_PATH
export PATH=/usr/local/mysql/bin:${PATH}


That fixes the binary and library paths... MAKE SURE THERE ARE NO MYSQL RPMS INSTALLED...

rpm -qa | grep mysql should give no mysql-[version] or mysql-server-[version] or mysql-devel-[version]


log-in and out...

install the gem
[root@heimdull ~]# gem install mysql -- --with-mysql-config=`which mysql_config`
Building native extensions. This could take a while...
Successfully installed mysql-2.7
1 gem installed



test the new gem:
[root@heimdull current]# RAILS_ENV=production ruby script/console
Loading production environment (Rails 2.1.0)
>> require 'mysql.so'
=> []
>> puts Mysql::VERSION
20700
=> nil
>> exit

Monday, August 11, 2008

Using thin with rails (apache frontend)

prerequisites (running on redhat/centos 5)

ruby 1.8.6+ (download, untar, configure, make, make install [reboot])
rubygems (download, untar, ruby rubygems/setup.rb)
rails (gem install rails)
thin (gem install thin)
apache 2.2 (installs apache to /usr/local/apache2 with mod_proxy/_balancer)
  • download
  • untar
  • ./configure --enable-proxy --enable-proxy-balancer --enable-rewrite --enable-deflate --enable-headers
  • make && make install
Install the thin run script
# thin install

Installing the thin configuration file
# vi /etc/thin/thin_conf.yml
---
user: daemon
group: daemon
chdir: /var/www/rails_app/current
log: log/mongrel.log
pid: tmp/pids/mongrel.pid
environment: production
port: 8000
address: 127.0.0.1
servers: 3

# /etc/init.d/thin start

Now lets add the proxy configs to apache...

in httpd.conf:

Include conf/extra/*.conf

now add your vhost config in conf/extra/httpd-rails_app.conf ...

# vi conf/extra/httpd-rails_app.conf

# Always keep the host header
ProxyPreserveHost On


BalancerMember http://127.0.0.1:8000
BalancerMember http://127.0.0.1:8001
BalancerMember http://127.0.0.1:8002



ServerName www.rails_app.com
ServerAlias rails_app.com
DocumentRoot /var/www/rails_app/current/public


Options FollowSymLinks
AllowOverride None
Order allow,deny
Allow from all


ProxyPass /images !
ProxyPass /javascripts !
ProxyPass /stylesheets !
ProxyPass /uploads !
ProxyPass /photos !

ProxyPass / balancer://rails_cluster/
ProxyPassReverse / balancer://rails_cluster/

# =============================================
# Configure Deflate Module (gzip)
# =============================================

AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE image/svg+xml
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/atom_xml
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/x-javascript
AddOutputFilterByType DEFLATE application/x-httpd-php
AddOutputFilterByType DEFLATE application/x-httpd-fastphp
AddOutputFilterByType DEFLATE application/x-httpd-eruby
AddOutputFilterByType DEFLATE text/html
BrowserMatch ^Mozilla/4 gzip-only-text/html
BrowserMatch ^Mozilla/4\.0[678] no-gzip

# =============================================
# Virtualhost logs
# =============================================
# Mark requests for the robots.txt file
SetEnvIf Request_URI "^/robots\.txt$" dontlog

ErrorLog logs/www/error_log
CustomLog logs/www/access_log combined env=!dontlog



# /usr/local/apache2/bin/apachectl start

rails thin apache all working together.... :)

Wednesday, March 12, 2008

MySQL on Leopard for rails


SQLite is a great little tool and very easy to use and setup… gem install sqlite3-ruby and you are done!! But now I’m creating a rails application that needs foreign keys and that’s something that SQLite does not do. So MySQL it is…(I’m a MySQL guy if you haven’t figured)

My choice to install MySQL on the macbook was using macports… I’ll assume that macports is installed correctly for the next exercises…  (port version should give you the version number)
Installing MySQL 5.0 with port:

sudo port install mysql5 +server

When the installation is done you have to create the run directory

sudo mkdir /opt/local/var/run
sudo mkdir /opt/local/var/run/mysql5
cd /opt/local/var/run
sudo chown _mysql mysql5
ls -al
total 0
drwxr-xr-x  4 _mysql  admin   136B Mar 12 10:37 mysql5/


setup the config file for MySql. (use the template so you can see where Mysql puts stuff)

sudo /opt/local/share/mysql5/mysql/my-small.cnf /opt/local/etc/mysql5/my.cnf

Testing if MySQL Starts…

sudo /opt/local/lib/mysql5/bin/mysqld_safe5

(you will need crtl-Z and then type bg. This will put the MySQL process in the background. type jobs to see the process)

now connect to mysql with the client

mysql5 -uroot

If you want to stop MySQL you have to kill the process. ps -ax | grep mysqld… there should be one mysqld and one mysqld_sfae5 process get BOTH pids and run kill pid pid.

ps -ax | grep mysqld 70170   ??  S      0:00.01 /bin/sh /opt/local/lib/mysql5/bin/mysqld_safe --datadir=/opt/local/var/db/mysql5 --pid-file=/opt/local/var/db/mysql5/new-host-2.home.pid
70195   ??  S      0:01.22 /opt/local/libexec/mysqld --basedir=/opt/local --datadir=/opt/local/var/db/mysql5 --user=mysql --pid-file=/opt/local/var/db/mysql5/new-host-2.home.pid --port=3306 --socket=/opt/local/var/run/mysql5/mysqld.sock kill  70170 70195

If you only kill one the server will auto restart!!
Running MySQL using MySQL launchctl

This is where I need more help BUT this is what I did and it works:

sudo launchctl load -w /Library/LaunchDaemons/org.macports.mysql5.plist  
PS(make sure you kill mysqld_safe5 before doing this...)

Now the part I don’t udnerstand… the server just started but I don’t know how to CONTROL the server like stop, start and restart???

sudo launchctl stop org.macports.mysql5

This did "restart" MySQL but using start/restart did nothing. Looks like when you stop MySQL it aut restart from lunched. 

Password for MySQL root user?

mysqladmin5 -u password 'secret-password'

connecting with password

mysql5 -uroot -p

Monday, January 21, 2008

Mysql driver for rails



When installing the mysql gem you might get this:

Building native extensions.  This could take a while... ERROR:  Error installing mysql: ERROR: Failed to build gem native extension.

the fix is easy but you are going to need the mysql-devel package if you are on redhat then do this:

yum install mysql-devel

Now you can install the mysql driver like this:

gem install mysql -- --with-mysql-config=`which mysql_config`

To test the driver us the rails console:

# ruby script/console
>> require ‘mysql’
>> puts Mysql::VERSION

This should give you the 20700 version. (As of Jan 2007 thats the latest version.)Now enjoy the speed.

Saturday, December 29, 2007

Create a subversion repository for rails



First you need a directory to house your repository. Since I work on multiple projects at home and in the office I need a master directory first. And just to make it simple I use /repos. This could be a link or a real directory.
(To clean-out a old svn directory use the following find . -name .svn -exec ‘rm -rf {}\;‘)
Step 1:

# create /repos

Step 2 (Create a repository):

# svnadmin create /repos/rails_project

Step 3 (Create rails specific directories):

# export REPOS=file:///repos/rails_project
# svn mkdir --message="Initial project layout" $REPOS/trunk $REPOS/tags $REPOS/branches

Step 4 (Initial Import of project):

# cd /rails_project
# svn import . file:///repos/rails_project/trunk -m "Initial Import..." */ This command import everything from the current directory to the svn server running locally using the file:/// structure */

Step 5 (check-out):

# svn co file:///repos/rails_project/trunk rails_project
# svn co svn://subversion_server/rails_project/trunk rails_project

Both of the above command will checkout the trunk of rails_project into a directory called rails_project.

Step 6 (Rails clean-up):

Go into the newly checked-out rails project

*/ Remove and Ignore the log files */  

# svn remove log/* 
# svn commit -m 'removing all log files from subversion' 
# svn propset svn:ignore "*.log" log/ 
# svn update log/ 
# svn commit -m 'Ignoring all files in /log/ ending in .log */ Remove and Ignore tmp directory */   
# svn remove tmp/* 
# svn commit -m 'removing all tmp artifacts from subversion' 
# svn propset svn:ignore "*" tmp/ 
# svn update tmp/ 
# svn commit -m "ignore tmp/ content from now on" */ Move the database config file to an example file and ignore */   
# svn move config/database.yml config/database.example 
# svn commit -m "Moving database.yml to database.example to provide a template for anyone who checks out the code" 
# svn propset svn:ignore "database.yml" config/ 
# svn update config/ 
# svn commit -m "Ignoring database.yml"

 

Thursday, November 8, 2007

hobo 0.64 with rails



ok I know I’m newbo and this is lame BUT here are the steps to get hobo installed and running.There are NO documentation except blogs and new groups for the latests version so here goes…Install latest rails and hobo gems

$ gem install rails –source http://gems.rubyonrails.org$ gem install hobo 

Now get the rails version (its going to be rails 1.99.seomthing) and set the env variable:

$ gem list rails$ export RAILS_GEM_VERSION=1.99.0.8178 
$ hobo myapp
$ cd myapp
$ script/plugin install svn://errtheblog.com/svn/plugins/will_paginate

update the myapp/config/database.yml with the correct database info and your are good-to-go.This is mine:

    development:  adapter: mysql  encoding: utf8  database: myapp_development  username: hobo  password: hobo_password  host: 10.0.0.200 

we also need to create the users table and admin user.

$ ./script/generate hobo_migration create_initial_tables$ g (for [g]enerate migration, don’t migrate yet.)

Now open the migration file db/migrate/001_creat_initial_tables and add the following after the create table end:

def self.up    
create_table :users do |t|      
t.string   :crypted_password, :limit => 40      
t.string   :salt, :limit => 40      
t.string   :remember_token      
t.datetime :remember_token_expires_at      
t.string   :username      
t.datetime :created_at      
t.datetime :updated_at    
end   

# create the admin user now because we can’t do it    
# through the web UI as it would fail validation    
admin = User.new    
admin.crypted_password = ‘ea87f9851d923a9a287631dd082799b83c0fa473′    
admin.salt = ‘7d8b386a7dfdcd0f268794038104791112cd4acd’    
admin.username = ‘admin’    
admin.save_without_validation  
end 

This will create a user ‘admin’ with password => password.
Now start the server

$ ./script/server

go to http://localhost:3000DONE!

Thursday, October 25, 2007

Deploying with Subversion tags in Capistrano



This is a 0.1 deploy method :) I have tested this and we are using this version in production BUT its is not stupid proof…

In the ./config/deploy.rb

# Setup the repository with the TAG variable ()
tag = (ENV[”TAG”] || “”)
set :repository, “http://svn.mypostit.local/#{application}/tags/#{tag}”
set :repository, “http://svn.mypostit.local/#{application}/trunk” if tag.empty?

Now you can deploy with:
[deployer@heimdull ]# cap deploy TAG=’my_tag’

Wow is that easy.. If the TAG environment variable is empty then it will use the trunk for the repository or else it will use whatever you put in TAG.

I guess I should check if the tag exists before continuing … maybe 0.2 :)

Thursday, September 27, 2007

Deploying with capistrano to servers behind a firewall



First lets install the rsync_with_remote_cache gem:

Check-out from source
svn co http://svn.extendviget.com/lab/trunk/gems/capistrano_rsync_with_remote_cache

Add patch so we will deploy to all roles not just the :app role(this will ensure that migration will work)
vi lib/capistrano/recipes/deploy/strategy/rsync_with_remote_cache.rb

change this:

# Step 2: Update the remote cache.
logger.trace “copying local cache to remote”
find_servers(:roles => :app, :except => { :no_release => true }).each do |server|
system(”rsync -az –delete #{local_cache}/ #{user}@#{server.host}:#{repository_cache}/”)
# TODO: an alternate version that excludes SVN, if we wanted to use an export-like strategy,
# from Andrew Kreiling - however, if we do an svn export locally and then sync it up, it wouldn’t
# include .svn anyway so this may be moot
# system(”rsync -az –delete –exclude=.svn –delete-excluded #{local_cache}/ #{user}@#{server.host}:#{repository_cache}/”)
end

to this:

# Step 2: Update the remote cache.
logger.trace “copying local cache to remote”
find_servers(:except => { :no_release => true }).each do |server|
system(”rsync -az –delete #{local_cache}/ #{user}@#{server.host}:#{repository_cache}/”)
# TODO: an alternate version that excludes SVN, if we wanted to use an export-like strategy,
# from Andrew Kreiling - however, if we do an svn export locally and then sync it up, it wouldn’t
# include .svn anyway so this may be moot
# system(”rsync -az –delete –exclude=.svn –delete-excluded #{local_cache}/ #{user}@#{server.host}:#{repository_cache}/”)
end

Create the gem
rake package

Install the gem
gem install pkg/capistrano_rsync_with_remote_cache-2.1.gem

Verify
gem list capistrano_rsync_with_remote_cache

Now inside of the capistranos deploy.rb file add this
set :deploy_via, :rsync_with_remote_cache

This strategy maintains two cache directories:

    * The local cache directory is a checkout from the Subversion repository. The local cache directory is specified with the local_cache variable in the configuration. If not specified, it will default to “.rsync_cache” in the same directory as the Capfile.

    * The remote cache directory is an rsync copy of the local cache directory. The remote cache directory is specified with the repository_cache variable in the configuration (this name comes from the remote_cache strategy that ships with Capistrano, and has been maintained for compatibility.) If not specified, it will default to “shared/cached-copy” (again, for compatibility with remote_cache.)

Deployment happens in three major steps. First, the local cache directory is processed. If it does not exist, it is created with a checkout of the revision to be deployed. If it exists, but is not a checkout from the repository specified in the configuration, the cache directory is removed, then recreated as if it did not exist. If it exists, and is a checkout from the repository specified, it is updated to the revision to be deployed.

Second, rsync runs on the local side to sync the remote cache to the local cache. When the rsync is complete, the remote cache should be an exact replica of the local cache.

Finally, a copy of the remote cache is made in the appropriate release directory. The end result is the same as if the code had been checked out directly on the remote server, as in the default strategy.

Sunday, July 1, 2007

Capistrano with multiple environments



A few months ago I started poking around with Capistrano and now cap is all I use everywhere… This thing rocks. The first problem I had was multiple environments, we have Production, Staging, performance, integration, qa1,qa2,stability1 and stability2 ?!?! dude can you say excessive.. anyways heres how I managed around this:

This goes in your deploy.rb file:

desc "Set the target stage to production"
task :production do
before “deploy”, “mysql:backup”
set :deploy_via, :rsync_with_remote_cache
set :stage, “#{current_task.name.to_s}”
role :web, “192.168.1.1″, :ssl => true
role :app, “192.168.1.2″
role :db, “192.168.1.3″, :primary => true
role :db, “192.168.1.4″, :no_release => true, :replica => true
role :db, “192.168.1.5″, :no_release => true, :replica => true
end
desc “Set the target stage to staging”
task :staging do
before “deploy”, “mysql:backup”
set :deploy_via, :rsync_with_remote_cache
set :stage, “#{current_task.name.to_s}”
role :web, “192.168.2.1″, :ssl => true
role :app, “192.168.2.2″
role :db, “192.168.2.3″, :primary => true
end

desc "Set the target stage to perf"
task :perf do
set :stage, “#{current_task.name.to_s}”
role :web, “192.168.3.1″, :ssl => true
role :app, “192.168.3.2″
role :db, “192.168.3.3″, :primary => true
end

I think this worked better than the multi-stage extension the was added to Capistrano. (It’s very similar except you put all the stages in their own files.)

Now when you call a task add the environment

cap production deploy:cold

I also have two different ways of deploying since the production servers are behind a firewall I added the :deploy_via in the task which overrides the deploy method and uses rsync for these hosts. (Btw there is a bug in the rsync code which I blogged about here)