14 12 / 2011

Set up Jenkins-CI on Ubuntu for painless Rails3 app CI testing

Jenkings-CI, formerly known as Hudson before Oracle acquired Sun, can be installed on Ubuntu pretty easily with the apt-get package manager, but getting it working with Ruby on Rails app, Github with rollified Users involves some glitches, so I’m writing them down for posterity. A good documentation on this is still missing.

Jenkins-1

Setting up Users with different permissions and hooking into private Github repos is too tricky. So, this is the post on setting up the Jenkins-CI on Ubuntu with a Githubfied private repository.

Our Goals:

  1. Setup the Jenkins CI
  2. Integrating with Git and Github
  3. Run the test build when changes gets pushed to Github
  4. Run the test build when new branch is pushed to Github
  5. Notify back to the committer(or team members) if the build fails

Installing Jenkins

SSH into your box. It can be a Vagrant box, VMWare, … I’ve used VMWare Fusion for this write up. Then install it with the following commands.

wget -q -O - http://pkg.jenkins-ci.org/debian/jenkins-ci.org.key | sudo apt-key add -
sudo sh -c 'echo deb http://pkg.jenkins-ci.org/debian binary/ > /etc/apt/sources.list.d/jenkins.list'
sudo aptitude update
sudo aptitude install jenkins

Going Headless

Now that Jenkins is installed, we want to get a headless display configured for our browser based tests. First go to Manage Jenkins > Manage Plugins > Available and install the Hudson Xvnc plugin (this works with Jenkins despite its name). Schedule Jenkins to restart to pickup the plugin. Once installed this gives us the ability to start a headless display automatically when we configure our jobs, more on that later.

With Jenkins configured we need to ensure the required software is installed on the server:

$ sudo apt-get install vnc4server

vncserver requires a password to be set before it can be used, this needs to be set before Jenkins can make use of the vncserver. For this we need to switch to the jenkins user and set a password.

$ sudo -Hiu jenkins
$ vncserver
Enter a password, and verify it
$ vncserver -kill :1 # or whichever display the vncserver output mentioned

Screenshot Gotcha

You have to install imagemagick with to see the screenshot or running browser via Xvnc. But its optional.

Creating the first Job build

After installing jenkins and going to http://the.ip.address:8080, you’ld see the dashboard of Jenkins. You won’t see any Login, Logout or Signup …. links. This is one of the trickiest part and I’ve addressed it below.

But for now, lets create our first Job build.

  1. First click the New Job link
  2. Give a sensible job name. Your project name can be a good fit but it can be anything
  3. Select Build a free-style software project radio button
  4. And OK

Jenkins-2

Configure the Job

After the above step, you’ll be taken to the job configuration form page. But before adding anything, lets add the Github plugin and some Jenkins configuration.

Install the github plugin

Now go to Jenkins > Manage Jenkins > Manage Plugins and install Github Plugin

Restart Jenkins if the Bundler is not picked up

sudo /etc/init.d/jenkins restart

Setting up users with authentication

To restrict the CI system and give access to your Team members to use or see the build logs, first you’ve to create an account.

  1. Go to Manage Jenkins > Configure System
  2. Check the Enable Security checkbox
  3. Under Security Realm, choose Jenkins's own user database
  4. Check the Allow users to sign up checkbox
  5. Under Authorization, choose Project-based Matrix Authorization Strategy
  6. Add first user with the name admin and another with github (Note: the username for Admin access has to be admin) For github named user, just choose the Overall Read only permission. We’ll use this user later with the Github hook.

jenkins-3

Note: The admin and github user that we’ve added in the above step does not create the User. Then you’ve to create a real user with that same name. Ya, I know, its a bit weird with Jenkins UI.

Go to Manage Jenkins > Manage Users > Create User. Create both admin and github users.

Jenkins-5

Lets finish up the Job configuration

Then finally you have to add the user at Project level at Project > Configure > Enable project-based security

Jenkins-6

Database Gotcha

After installing the gems, when tried to rake db:migrate, it looks for config/database.yml file and in many projects its not tracked in the repo. So a good way is to checkin config/database.yml.example file into the repository and copy/rename it to config/database.yml file before migrating during the build process.

cp config/database.yml.example config/database.yml

or you can create a executable shell script and put such kind of actions in it and do check-in this file into your repo. Then you can add ./configure in the build step before running the specs.

For a boilerplate rails app

#!/bin/bash -e
rvm use ruby-1.9.3@myapp
cp config/database.yml.example config/database.yml
bundle install --without darwin
bundle exec rake db:migrate
bundle exec rake

For private projects on Github

If the app is public, skip this step.

Before starting your first build, we need to generate the ssh key for the jenkins user and the RSA of Github.com has to be in the /var/lib/jenkins/.ssh/known_hosts file.

So, lets generate the ssh keys for the jenkins user:

ssh-keygen -t rsa

Copy the contents of /var/lib/jenkins/.ssh/id_rsa.pub file and put it in the Github repository Admin page under Deploy keys. For the Millistarter, it will be at github.com/millisami/millistarter/admin/keys

Jenkins-10

Adding github RSA fingerprint in jenkins home (/var/lib/jenkins)

sudo su - jenkins
jenkins@jenkins:~$ git clone git@github.com:<github_username>/repo_name.git
Initialized empty Git repository in /var/lib/jenkins/github_username/.git/
The authenticity of host 'github.com (207.97.227.239)' can't be established.
RSA key fingerprint is 16:27:ac:a5:76:28:2d:36:63:1b:56:4d:eb:df:a6:48.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added 'github.com,207.97.227.239' (RSA) to the list of known hosts.
^C (Hit Ctrl + C)
jenkins@jenkins:~$ ls .ssh/
id_rsa  id_rsa.pub  known_hosts
jenkins@jenkins:~$

Create the tmp directory if ignored in .gitignore which is true quite often

mkdir -p tmp/cache tmp/pids tmp/capybara tmp/sass-cache tmp/sessions tmp/sockets

And if your test has to create some directories, just create them too. In my case, I’d to had tmp/media.

mkdir -p tmp/media

Hooking with the Github web-hooks

Now to run the build automagically when new commit or branch gets pushed onto Github, we have to setup the repository.

Got to the hooks page for your repository. e.g. github.com/<username>/<project_name>/admin/hooks

Under AVAILABLE SERVICE HOOKS > Post-Receive URLs, add github:github@your-ci-server.com/github-webhook/.

The githu:github is the user that we’d created earlier.

Jenkins-9

Then we have to verify Jenkins with Github. Go to Manage Jenkins > Configure System and under GitHub Web Hook, add your Github username and password and click the Test Credential button to authorize once with Github.

Jenkins-7

Git Gotcha on your first build

If you see the following error after checking out your repo:

FATAL: Could not apply tag jenkins-project
hudson.plugins.git.GitException: Could not apply tag jenkins-project
....
....
Caused by: hudson.plugins.git.GitException: Error performing command: git tag -a -f -m Jenkins Build #4 jenkins-project
Command "git tag -a -f -m Jenkins Build #4 jenkins-project" returned status code 128: 
*** Please tell me who you are.

You have to add the following in the jenkins user home directory:

# /var/lib/jenkins/.gitconfig
[user]
  name = Jenkins-ci
  email = jenkins@localhost

Setting up the email to notify if the build fails

Go to Manage Jenkins > Configure System and add the SMTP credentials.

Jenkins-8

Final Configuration Assertion

Since the post is TL;DR, here are the 2 screenshots of Jenkins Config and Project Config. Your configuration should resemble this.

Jenkins System Config

Project Config

Bonus(es) and Gotcha(s)

Gotcha with OutBound error

Sometimes we get this error MoveTargetOutOfBoundsError. This is caused if the window size is less than the expected one. At least I think so, not confident. To fix this error, in Manage Jenkins > Configure System > Xvnc Command line put this sh -c "USER=jenkins HOME=/var/lib/jenkins vncserver :10 -geometry 1440x900 -depth 16". I’d to install FluxBox with sudo apt-get install fluxbox. And had to downgrade the Firefox down to 3.x from 8.x.

Adding the code coverage metrics

Install the Ruby metrics plugin plugin, to actually display the graphs of your code coverage.

A project called simplecov, that seems to work really well, but the output format isn’t what jenkins expects. simplecov-rcov, its just a formatter for simplecov, that generate rcov style reports. So lets add this to our spec/spec_helper.rb

require 'simplecov'
require 'simplecov-rcov'
SimpleCov.formatter = SimpleCov::Formatter::RcovFormatter

SimpleCov.start 'rails' if ENV["COVERAGE"]

Bonus: Watch your acceptance test run in real graphical window

Download the VNC Viewer viewer for Mac. If you’re on other OS, you can find it by googling around.

Open up a new connection and provide the address and its port.

You can find the port its running on with the cmd:

sudo netstat -tulpn

...
tcp        0      0 0.0.0.0:5910            0.0.0.0:*               LISTEN      3319/Xvnc4
...

References

09 12 / 2011

Revisited: Rails 3.1.x with compass, sass and twitter-bootstrap using the asset pipeline

This is a revised post for the previously released post Rails3.1 with compass, sass and twitter-bootstrap using the asset pipeline It had problems while compiling the assets via rake assets:compile

Here I’ll show you 2 alternative ways to get Compass, SASS(.sass) and Twitter bootstrap installed and compiled in a Rails 3.1.3(latest on as of writing this).

1. Using anjlab-bootstrap-rails

Add the necessary gems in the Gemfile.

group :assets do
  ...
  gem 'compass', :git => 'https://github.com/chriseppstein/compass.git', :tag => 'v0.12.alpha.2'
  gem 'sass-rails', "  ~> 3.1.0"
  gem 'anjlab-bootstrap-rails', :require => 'bootstrap-rails',
                                  :git => 'git://github.com/anjlab/bootstrap-rails.git', 
                                  :ref => 'eab5c9e3db95'
end

Rename the app/assets/stylesheets/application.css file to app/assets/stylesheets/application.css.scss and replace the commented manifest with below.

@import "bootstrap";
@import "compass/css3";
@import "base";

The above imports all the stylesheets of Bootstrap, Compass’s CSS3 mixins and our own base.sass files.

The following is the sample base.sass file using compass/css3 mixins.

a
  outline: 0
object, embed
  outline: 0
input::-moz-focus-inner
  border: 0

div#main
  +box-shadow(red 2px 2px 10px)

We can use all the compass cross-browser compatible awesome mixins.

2. Using compass_twitter_bootstrap

Add the necessary gems in the Gemfile.

group :assets do
  ...
  gem 'compass', :git => 'https://github.com/chriseppstein/compass.git', :tag => 'v0.12.alpha.2'
  gem 'sass-rails', "  ~> 3.1.0"
  gem 'compass-twitter-bootstrap', :git => 'git://github.com/vwall/compass-twitter-bootstrap.git', 
                                :ref => 'b6f9b467bc'

end

Add a file at config/initializers/sass.rb with the following:

Rails.configuration.sass.tap do |config|
  # twitter bootstrap
  config.load_paths << Compass::Frameworks['compass'].stylesheets_directory
  config.load_paths << Compass::Frameworks['twitter_bootstrap'].stylesheets_directory
end

Rename the app/assets/stylesheets/application.css file to app/assets/stylesheets/application.css.scss and replace the commented manifest with below.

@import "compass_twitter_bootstrap"
@import "compass/css3";
@import "base";

Verifying the assets:compile task

Well, if the bootstrap with compass works in development mode doesn’t mean that it will compile the assets properly. To verify it, the rake assets:compile task should run successfully both in development and production environment.

So, to verify this, just run

RAILS_ENV=development bundle exec rake assets:compile
RAILS_ENV=production bundle exec rake assets:compile

This should create compressed assets at public/assets directory.

Hope you find it useful.

02 12 / 2011

Cache sweeper in Rails3.1, if not using ActiveRecord!

If you’re using Rails 3.1 but without ActiveRecord, then you cannot use the the expire_page, expire_action and expire_fragment in your controller. This might happen if you use ODMs such as Mongoid. The app that I’m working on uses Mongoid.

So, the work-around is to add a Mongoid::Observer and expire those caches by creating an instance of the ActionController::Base and call those methods on that object.

class LineObserver < Mongoid::Observer
 observe :line

 def after_save(line)
   expire_cache(line)
 end

 def after_destroy(line)
   expire_cache(line)
 end

 private
   def expire_cache(line)
     @cont ||= ActionController::Base.new
     @cont.expire_fragment "department_lines" if line.public?
   end
end

Hope this saves someone’s time.

17 10 / 2011

Rails3.1 with compass, sass and twitter-bootstrap using the asset pipeline

I prefer the sass original syntax over the new scss. And I don’t want to loose the awesome CSS3 mixins. When you google, you’ll find many articles and almost all have different hacks to implement. But as of today, those load paths hacks are not necessary when I tried to use the compass and twitter-bootstrap.

Add the necessary gems in the Gemfile.

group :assets do
  ...
  gem 'compass', git: 'https://github.com/chriseppstein/compass.git'
  gem 'sass-rails', "  ~> 3.1.0"
  gem 'anjlab-bootstrap-rails', :require => 'bootstrap-rails',
                                :git => 'git://github.com/anjlab/bootstrap-rails.git'
end

Rename the app/assets/stylesheets/application.css file to app/assets/stylesheets/application.sass and change the commented manifest from:

/*
 * This is a manifest file that'll automatically include all the stylesheets available in this directory
 * and any sub-directories. You're free to add application-wide styles to this file and they'll appear at
 * the top of the compiled file, but it's generally better to create a new file per style scope.
 *= require_self
 *= require_tree . 
*/

to sass comment style

// * This is a manifest file that'll automatically include all the stylesheets available in this directory
// * and any sub-directories. You're free to add application-wide styles to this file and they'll appear at
// * the top of the compiled file, but it's generally better to create a new file per style scope.
// *= require_self
// *= require_tree .
// *= require bootstrap

Now do import of compass css3 mixins the sass way in the same application.sass file or other files.

@import "compass/css3/opacity"

#logo h1
  +opacity(0.5)

Thats it.