How to start a rake task using upstart

bundlerupstart

I'm trying to setup a Resque worker as an Upstart init script to be used by Monit in a Rails app. I'm not a sysop and I've tried to write this using examples from other init script we have on our server, here's what I got:

start on startup
stop on shutdown

pre-start script
   cd /var/www/my-app/current
end script

script
   exec bundle exec rake environment resque:work RAILS_ENV=staging PIDFILE=/var/run/resque.pid QUEUE=sync >> /var/log/resque.log
end script

But it doesn't work, if I try sudo start resque I get:

resque start/running, process XXXX

Nothing is being started as far as I know, there's no Resque process to be found nor there's log file. I'm quite lost as to how to get it working.

Update: I've found the syslog file and it says:

Nov  4 17:20:09 fantasysports init: resque main process (3057) terminated with status 2

Update: I've tried to run it using sudo (yeah that doesn't make sense!) and removed the output redirection to the log file and now I get a different status code:

Nov  4 17:29:44 fantasysports init: resque main process (3276) terminated with status 10

Update: Ended up ditching Upstart for init.d, as start-stop-daemon is much better documented and it give me complete control of what's going on.

Best Answer

Here's how I do it.. this also adds in rvm

start on startup
stop on starting rcS

chdir /data/pusher/current
env RAILS_ENV=production
script
  /usr/local/bin/rvm-shell '1.9.2@app' -c 'JOBS_PER_FORK=25 RAILS_ENV=production QUEUE=app_production bundle exec rake --trace resque:work >> /data/app/current/log/app-worker.production.log 2>&1'
end script

Edit: here is how I do it for running as a different user.. chdir doesn't seem to be honored.. so it's kind of hacky

start on runlevel [2345]
stop on starting rcS

chdir /data/app/current
env RAILS_ENV=production
script
        sudo -u user -s -- "cd /data/app/current; export RAILS_ENV=production; /usr/local/bin/rvm-shell '1.9.2-p180@app' -c 'QUEUE=app_production bundle exec rake resque:work >> /data/app/current/log/app-worker.production.log 2>&1'"
end script

You pretty much need to change into the correct directory and set the RAILS_ENV in the sudo command