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!

Can't access my VPS via ssh ??

This was the errors message:

PTY allocation request failed on channel 0

Searching around on the internet I found that there is a device ptmx that might be missing with this error message. SO I did the following:

[root]# ls -l /dev/ptmx
ls: /dev/ptmx: No such file or directory


So is that the problem? hmm, I recreated the device:

[root]# /sbin/MAKEDEV -d /dev ptmx


and restarted sshd and Now everything works again!!

Thursday, November 13, 2008

Mysql5 in OSX

Install mac ports

Install Mysql:
freddy@new-host-2:~$ port list | grep mysql5
mysql5 @5.0.67 databases/mysql5
mysql5-devel @5.1.28-rc databases/mysql5-devel
freddy@new-host-2:~$ port install mysql5


  • First run this command in your terminal to install the MySQL 5 package:

    sudo port install mysql5 +server
  • Second load the MySQL server by running the following command: (Note: Mac OS X Tiger and above use launchd for starting programs, and this command is worth getting familiar with. In this case the startup configuration file was created for us when we installed MySQL 5.)

    sudo launchctl load -w /Library/LaunchDaemons/org.macports.mysql5.plist
  • Third figure out the path for your server socket. It should be /opt/local/var/run/mysql5/mysqld.sock but verify this by running this command:

    mysql_config5 --socket
    /opt/local/var/run/mysql5/mysqld.sock
  • Fourth you want to create a shortcut to the MySQL socket so that PHP, Ruby on Rails, Python, and your other languages can access it. These commands should make MySQL work for PHP and Ruby on Rails:

    sudo ln -s /opt/local/var/run/mysql5/mysqld.sock /tmp/mysql.sock
    sudo mkdir /var/mysql
    sudo ln -s /opt/local/var/run/mysql5/mysqld.sock /var/mysql/mysql.sock
  • Fifth you will need to shut down the MySQL server for now. Run this command:

    sudo launchctl unload -w /Library/LaunchDaemons/org.macports.mysql5.plist
  • Sixth you need to setup the root user and the default MySQL database. Sometimes called the grant tables. To do this run this command:

    sudo /opt/local/lib/mysql5/bin/mysql_install_db --user=mysql
  • And last you’ll need to start up the MySQL server and then login and change the root password.

    sudo launchctl load -w /Library/LaunchDaemons/org.macports.mysql5.plist
    mysql5 -u root
    UPDATE mysql.user SET Password = PASSWORD('password') WHERE User = 'root';
    FLUSH PRIVILEGES;
    quit
  • Now you should be able to login using your new password.

    mysql5 -u root -p

That’s it you’re all setup with MySQL on Mac OS X.

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, September 26, 2008

Building a site map in Ruby on Rails...

I needed an automated sitemap process for the www.cadechristian.com website and here is what I managed to create...
route.rb:
map.sitemap 'sitemap.xml', :controller => 'sitemap', :action => 'sitemap'
robots.txt:
Sitemap: http://www.cadechristian.com/sitemap.xml

sitemap controller:
def sitemap
@model1 = Page.find(:all)
@model2 = Page.find(:all)
render :layout => false
end

/app/view/sitemap/sitemap.builder:
@home_url = 'http://www.cadechristian.com'

xml.instruct!
xml.urlset :xmlns => 'http://www.sitemaps.org/schemas/sitemap/0.9' do

# Add static Urls
%w( / /url1 /url2 /url3 ).each do |url|
xml.url do
xml.loc @home_url + url
xml.lastmod Time.today.xmlschema
xml.priority 1
end
end

@model1.each do |model|
xml.url do
xml.loc @home_url + model_path(model)
xml.lastmod product.updated_at.xmlschema
xml.priority 0.9
end
end

@model2.each do |model|
xml.url do
xml.loc @home_url + model_path(model)
xml.lastmod product.updated_at.xmlschema
xml.priority 0.9
end
end
end



That removes the need to update my sitemap.xml file when we add products and other static resources :)

You could also create a ruby script or some hook that runs this code:

require 'net/http'
require 'uri'
include ActionController::UrlWriter

sitemap_uri = 'www.cadechristian.com/sitemap.xml'
escaped_sitemap_uri = URI.escape(sitemap_uri)

%w( submissions.ask.com www.google.com ).each do |engine|
Net::HTTP.get(engine, '/ping?sitemap=' + escaped_sitemap_uri)
end
Net::HTTP.get('webmaster.live.com', '/ping.aspx?siteMap=' + escaped_sitemap_uri)

This would ping the search engines and you are done...

Monday, September 22, 2008

mod_mem_cache.c:591: undefined reference to `ap_cache_cacheable_hdrs_out’

If you are getting this error, it’s because you’ve included the ‘--enable-mem-cache‘ flag, but not the ‘--enable-cache‘ one. You need both.

enable-disk-cache also needs the same enable-cache switch to work.

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.... :)

Monday, April 7, 2008

Ferret is not ready for production!!!

Hi,

There will be more to this article later but for now... Ferret sucks...

If I was to recommend a small-footprint search engine that is fast and EASY to use for Rails I would say install sphinx and use the ultrasphinx plugin. (paginates with will_paginate_on_steroids )

Using Ferret could not handle the initial load when starting 10 Mongrels after a new deployment. Starting 1 mongrel with 2-3 sec wait-time between worked fine!! Maybe I'm doing something wrong?!?

Friday, March 14, 2008

Using awk to sum all entries in one column

Had to search this one for a while... here is the source file:

360109368 15004557 java.lang.String
310090432 7692644 char[]
179389488 7474562 java.util.HashMap$Entry
71350968 70689 java.util.HashMap$Entry[]
14298360 109019 * ConstMethodKlass
7853616 109019 * MethodKlass
7409816 119136 java.lang.Object[]
7302080 17556 int[]
7094864 11288 byte[]

I wanted the sum of all the numbers in the first column and heres the awk line I used:

cat sourcefile | awk '{print $1}' | awk 'BEGIN{sum=0}{sum+=$1}END{print "Total: " sum}'

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.