Running Rails applications: Choosing a server

Once you develop a web application in Rails, and works great in the embedded web server rails comes with, or mongrel, you may ask yourself how to run the application for production.
It may seem it's easy to decide, and in fact, all the solutions will be around Apache2 or lighttpd + FastCGI.

Actually, as you may have noticed, the performance difference between Apache2 and lighttpd is not the problem. They both work fine (and if you don't need something specific only available for one of the web servers, you can choose the one you prefer). The biggest problem is the FastCGI module.

The FastCGI module for Apache (libapache2-mod-fastcgi in Debian systems) does not perform good, even changing the default configuration (/etc/apache2/mods-available/fastcgi.conf)

By default, the module runs in dynamic mode, which is, you give a minimum and maximum of FastCGI processes running, and these are started or killed automatically when it's needed.

<IfModule mod_fastcgi.c>
  AddHandler fastcgi-script .fcgi
  ...
  FastCgiConfig -minProcesses 2 -maxProcesses 6
  ...
</IfModule>

It can also be configured in static mode, where the number of FastCGI processes specified are started when Apache starts, and remain running. You can adjust the idle timeout parameter to the needs of your application. In the example, it gives a 60 second limit to process the query.

<IfModule mod_fastcgi.c>
  AddHandler fastcgi-script .fcgi
  ...
  FastCgiServer -idle-timeout 60 -processes 4
  ...
</IfModule>

I experienced better performance using FastCGI in static mode for Rails, but it is not good enough. The dispatch.fcgi processes freeze from time to time and the application is either slow or crashes.

The solution I am currently using is Apache2 + libapache2-mod-fcgid. mod-fcgid is a module for Apache2, compatible with FastCGI that I found to perform much better than the other solutions above. Even with the default configuration is much better than the FastCGI module for Rails.

There are some small things you have to change to use fcgid, though. First of all, you will have to change the handler in the .htaccess file in the public/ directory of your Rails application.
You will have to search for the line:
    AddHandler fastcgi-script .fcgi
replacing it with:
    AddHandler fcgid-script .fcgi

If you use HTTP Authentication, you will notice that the header is not passed through the cgi to the rails application. You will have to use RewriteRules to pass it. Again, in .htaccess, search for the line:
    RewriteRule ^(.*)$ dispatch.fcgi [QSA,L]
and replace it with:
    RewriteRule ^(.*)$ dispatch.fcgi [E=X-HTTP_AUTHORIZATION:%{HTTP:Authorization},QSA,L]

Now you can access the Authorization header the usual way:

if request.env.has_key? 'REDIRECT_X_HTTP_AUTHORIZATION'
    authdata =
request.env['REDIRECT_X_HTTP_AUTHORIZATION'].to_s.split
end





 

Using FastCGI with Apache2 on Debian AMD64

I have been using Apache2 with FastCGI to run in.solit.us. Some time ago, I moved to a new AMD64 server, and apparently, there is no Debian support for FastCGI on Apache2 for the amd64 platform. There is, however, a package for Apache 1.3.

For some time, I have been using libapache2-mod-fcgid, which is a replacement for libapache2-mod-fastcgi, but there are some things that are not working with fcgid, such as the upload progress status stuff in rails, and, for example, HTTP Authentication using the browser headers. And fastcgi seems to perform better, too.

Fortunately, the Ubuntu distribution has a deb package for libapache2-mod-fastcgi for the amd64 platform, and I was able to use it on my Debian installation. You only need to have apache2 (it will fail with apache2.2) installed, and it will install flawlessly.

If you are using testing, and therefore you had apache2.2 installed, you can downgrade it changing sources.list, removing apache2 and reinstalling it again.




 

Working at CERN (VI): Trip to Milan

It was not at all correct when in the last post I stated the longest trip we made by train was the one to Saint Gallen. The longest one was in fact to Milan. The Cisalpino took us in 4 and a half hours from the Cornavin station to Milan, where Leonardo da Vinci was to greet us:



Near the Leonardo da Vinci statue there is one of the most famous opera houses: La Scala



And also from the da Vinci statue and the Teatro della Scala we can get to the entrance of the Galleria Vittorio Emanuele, which leads to the Piazza del Duomo, where Il Duomo, Milan's cathedral is located.



The glass-covered street is still the home to several haute couture shops, restaurants and bars, and following the gallery, we arrive to Il Duomo (the entrance of the Galleria Vittorio Emanuele is the arch in the center of the photo, and the cathedral is at the right):



With the cathedral at the right, that was partially covered due to maintenance, to continue with our great luck after Bern's Bundeshaus ongoing repairs.



With some nice paintings at the inside:







 

Working at CERN (V): Trip to Zurich and St. Gallen

The trip to Saint Gallen and Zurich was one of the longest ones we made by train. The journey from Geneva to St. Gallen took about 4 hours, and is actually the farthest city from Geneva, almost in the Austrian border, near Liechtenstein.

Saint Gallen is the home to a quite impressive abbey, with a more impressive library. The abbey was founded in 613, being one of the most important Benedictine abbeys for many centuries. Even if the abbey is almost completely rebuilt, it has a quite nice baroque church. The wikipedia entry for Abbey of St. Gall offers a picture of the library.




After spending the morning in Saint Gallen, we took the train again to end up in Zurich in about half an hour. We found Zurich to be a big city, but still with small houses at both sides of the Limmat river, ending at the lake, and also modern buildings corresponding to what is the economic capital of Switzerland.



The Großmunster in the river, too, near the lake.



As it usually happens in Switzerland, the perfect weather from the first photographs turned to be rainy after a couple of hours. At the end of the river, in Lake Zürich.







 

Working at CERN (IV): Stephen Hawking - The Origin of the Universe

The last 28th of September, I had the opportunity to see Stephen Hawking at the Main Auditorium at CERN. He was there to make a conference about the origin of the Universe. It was a great opportunity to be there and be able to see him, specially when he doesn't make a lot of conferences lately due to his health condition.



The conference was starting at 4:30pm and one hour before almost all seats were already occupied. It was also broadcasted to several auditoriums in other CERN buildings. Anyway, the conference was very interesting, so I recommend you all seeing it if you haven't done it yet.

You don't really have to know anything about physics at all, so if you want to download it, CERN has it hosted in the following link:
Stephen Hawking: The Origin of the Universe (Real Media, 360Mb)



 

Instalar Debian en un sistema remoto

Éste tutorial es especialmente útil para aquellos que dispongan de un servidor al que no se puede tener acceso físico o es demasiado costoso desplazarse al lugar donde está alojado. A partir de una instalación cualquiera de Linux, instalaremos un nuevo sistema basado en Debian.

Necesitamos una partición que podamos usar para copiar los archivos del sistema base. Yo disponía de una partición swap de 2GB que es más que suficiente para instalar el sistema base (con alrededor de 200mb es suficiente). Así que prácticamente todo el mundo podrá hacer su instalación con la partición swap.

Lo primero que deberemos hacer es desmontar la partición de swap:
[root@lxb0751 root]# swapoff -a

Para empezar el proceso, debemos cambiar el tipo de la partición de Linux swap a Linux. Suponiendo que el disco es hda:

[root@lxb0751 root]# fdisk /dev/hda

Mostramos las particiones con 'p'.

Command (m for help): p

Disk /dev/hda: 20.0 GB, 20020396032 bytes
255 heads, 63 sectors/track, 2434 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes

Device Boot Start End Blocks Id System
/dev/hda1 * 1 653 5245191 83 Linux

...
/dev/hda5 1912 2172 2096451 82 Linux swap


Una vez comprobada cual es nuestra partición swap (en este caso la 5), procedemos del siguiente modo (t, cambio de tipo de partición - partición 5 - tipo 83 (Linux)) :

Command (m for help): t
Partition number (1-7): 5
Hex code (type L to list codes): 83
Changed system type of partition 5 to 83 (Linux)

Por último, guardamos los cambios (w). A pesar de lo que diga, NO hay que reiniciar.

Command (m for help): w
The partition table has been altered!

Calling ioctl() to re-read partition table.

WARNING: Re-reading the partition table failed with error 16: Device or resource busy.
The kernel still uses the old table.
The new table will be used at the next reboot.
Syncing disks.


Creamos el sistema de archivos (ext3) en la nueva partición:

[root@lxb0751 root]# mkfs.ext3 /dev/hda5
mke2fs 1.32 (09-Nov-2002)
Filesystem label=
OS type: Linux
Block size=4096 (log=2)
Fragment size=4096 (log=2)
262144 inodes, 524112 blocks
26205 blocks (5.00%) reserved for the super user
First data block=0
16 block groups
32768 blocks per group, 32768 fragments per group
16384 inodes per group
Superblock backups stored on blocks:
32768, 98304, 163840, 229376, 294912

Writing inode tables: done
Creating journal (8192 blocks): done
Writing superblocks and filesystem accounting information: done

This filesystem will be automatically checked every 35 mounts or
180 days, whichever comes first. Use tune2fs -c or -i to override.


Montamos la nueva partición en /deb, por ejemplo:
[root@lxb0751 root]# mkdir /deb
[root@lxb0751 root]# mount /dev/hda5 /deb

Si no se dispone de debootstrap en la instalación de Linux que queremos sustituir, debe instalarse para poder descargar el sistema base de Debian. He preparado con alien un par de paquetes de debootstrap, un rpm y un tgz. Lo más sencillo es bajar el rpm en http://www.gra2.com/shared/linux/, descomprimirlo, e instalarlo con rpm --install

[root@lxb0751 root]# wget http://www.gra2.com/shared/linux/debootstrap-0.2.45-0.2.i386.rpm
[root@lxb0751 root]# rpm --install debootstrap-0.2.45-0.2.i386.rpm

Una vez instalado debootstrap, instalamos el sistema base en /deb (usando el mirror de Debian de Switch para Woody). Woody no es la versión más nueva de Debian, lo sé, pero me daba problemas con Sarge. Actualizaremos más tarde.

[root@lxb0751 /]# debootstrap --arch i386 woody /deb http://mirror.switch.ch/ftp/mirror/debian/

En un par de minutos, estará instalado. Si aparece algún warning, ignóralo.

Antes de continuar, debemos copiar los archivos importantes de red en la nueva instalación.

[root@lxb0751 /]# cp /etc/resolv.conf /deb/etc/resolv.conf
[root@lxb0751 /]# cp /etc/hosts /deb/etc/hosts

Debemos copiar también la información de la interfaz de red, usando ifconfig (las dos primeras líneas) y route (la entrada default):

[root@lxb0751 /]# ifconfig
eth0 Link encap:Ethernet HWaddr 00:D0:B7:B8:6A:AB
inet addr:128.142.65.59 Bcast:128.142.255.255 Mask:255.255.0.0


[root@lxb0751 /]# route
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
default 128.142.1.1 0.0.0.0 UG 0 0 0 eth0


Editamos /deb/etc/network/interfaces
[root@lxb0751 /]# pico /deb/etc/network/interfaces

Con la información obtenida, el archivo quedará así:
auto lo
iface lo inet loopback

auto eth0
iface eth0 inet static
address 128.142.65.59
netmask 255.255.0.0
broadcast 128.142.255.255
gateway 128.142.1.1


Ahora ya podemos hacer chroot a la nueva instalación:

[root@lxb0751 /]# chroot /deb /bin/bash

Completamos la información sobre la tabla de particiones:
lxb0751:/# nano /etc/fstab

Suponiendo que la partición que usamos era hda5, quedará así:

/dev/hda5 / auto defaults 0 1
proc /proc proc defaults 0 0


Montamos /proc
lxb0751:/# mount /proc

Configuramos el host:
lxb0751:~# hostname lxb0751.cern.ch

Iniciamos la configuración del sistema base (entre otras cosas, asignamos el password de root):
lxb0751:~# /usr/sbin/base-config
Configuring the base system...

En la configuración de apt, seleccionamos http. No usamos dselect, no usamos tasksel. Finalmente, aparecerá algo así:

Reading Package Lists... Done
Building Dependency Tree... Done
The following packages will be REMOVED:
console-tools-libs
The following NEW packages will be installed:
aptitude coreutils debconf-i18n dselect e2fslibs gcc-3.3-base initscripts libacl1 libattr1 libblkid1
libcomerr2 libconsole libdb1-compat libdb4.2 libdevmapper1.01 libgcc1 libgcrypt11 libgdbm3 libgnutls11
libgpg-error0 liblocale-gettext-perl liblzo1 libnewt0.51 libopencdk8 libpcap0.7 libsasl2
libsigc++-1.2-5c102 libss2 libstdc++5 libtasn1-2 libtext-charwidth-perl libtext-iconv-perl
libtext-wrapi18n-perl libuuid1 slang1a-utf8 sysv-rc zlib1g
94 packages upgraded, 37 newly installed, 1 to remove and 0 not upgraded.
Need to get 34.2MB of archives. After unpacking 39.6MB will be used.
Do you want to continue? [Y/n]
...
Fetched 34.2MB in 5s (6382kB/s)
Preconfiguring packages ...


Es seguro contestar por defecto a todas las preguntas de la instalación.

Do you want to erase any previously downloaded .deb files? [Y/n] y
Press enter to continue.

Select a number from 1 to 5, from the list above.
Enter value (default=`1', `x' to restart): 5

==============================================================================
Mail configuration skipped.


Una vez finalizada, debemos instalar ssh, haciendo especial hincapié en el servidor ssh (Do you want to run the sshd server? -> YES). De lo contrario no podremos acceder a la máquina.

lxb0751:~# apt-get install ssh locales

Igualmente importante es instalar detector, que detectará dispositivos, entre ellos, nuestra tarjeta de red.

lxb0751:~# apt-get install discover
...
Setting up discover (2.0.7-2.1) ...
Discovering hardware: e100


Instalamos uno de los kernel de Debian ya compilados. Más adelante podremos compilar uno.
lxb0751:~# apt-get install kernel-image-2.6-686

If you have already done so, and you wish to get rid of this message,
please put
"do_initrd = Yes"
in /etc/kernel-img.conf. Note that this is optional, but if you do not,
you will continue to see this message whenever you install a kernel
image using initrd.
Do you want to stop now? [Y/n]n
Install a partition boot block on partition /dev/hda5? [Yes] No


Comprobamos que el kernel y el initrd están en /boot:
lxb0751:/boot# ls
System.map-2.6.8-3-686 boot.b config-2.6.8-3-686 initrd.img-2.6.8-3-686 vmlinuz-2.6.8-3-686

Pasamos a configurar GRUB:
lxb0751:/boot# apt-get install grub

En este punto, debemos salir del chroot para poder instalar el nuevo sector de arranque:
lxb0751:/boot# exit
exit


Debemos copiar el kernel e initrd que instalamos previamente a /boot:

[root@lxb0751 /]# cp /deb/boot/initrd.img-2.6.8-3-686 /boot/
[root@lxb0751 /]# cp /deb/boot/vmlinuz-2.6.8-3-686 /boot

[root@lxb0751 grub]# pico /boot/grub/grub.conf

Deberá contener como mínimo lo siguiente (debe estar al principio del archivo) -comprobad que la versión del kernel sea el que indico, puede variar-:

default=0
timeout=10
title Debian 2.6
root (hd0,4)
kernel /boot/vmlinuz-2.6.8-3-686 root=/dev/hda5
initrd /boot/initrd.img-2.6.8-3-686


Con ésta configuración indicamos que inicie Debian 2.6, que está en /dev/hda5 (hd0,4), con la partición / en /dev/hda5, y con el kernel e initrd en el path que indicamos.

Instalamos grub con la nueva configuración:

[root@lxb0751 boot]# grub-install /dev/hda
Installation finished. No error reported.
This is the contents of the device map /boot/grub/device.map.
Check if this is correct or not. If any of the lines is incorrect,
fix it and re-run the script `grub-install'.


Desmontamos las particions (usando -l):

[root@lxb0751 root]# umount -l /deb/proc
[root@lxb0751 root]# umount -l /deb

[root@lxb0751 root]# reboot

De nuevo conectados al sistema remoto, ya en el nuevo Debian, movemos la instalación a la partición original (suponiendo que la teníamos en /dev/hda1):

lxb0751:~# mkfs.ext3 /dev/hda1

Copiamos a la nueva partición:
lxb0751:~# dd if=/dev/hda5 of=/dev/hda1 bs=1024

Comprobamos que no haya ningún error en la partición:
lxb0751:~# e2fsck -f -y /dev/hda1

La partición destino tendrá el tamaño de la particíón origen, aunque la primera sea mucho más grande. Lo solucionamos con resize2fs:

lxb0751:~# resize2fs -p /dev/hda1

Ahora deberemos modificar de nuevo /etc/lilo.conf para adaptarlo a la nueva situación. Para ello debemos montar la nueva partición y modificar su lilo.conf:

lxb0751:~# mount /dev/hda1 /mnt
lxb0751:~# pico /mnt/etc/lilo.conf

/dev/hda1 / auto defaults 0 1
proc /proc proc defaults 0 0


lxb0751:~# umount /mnt

Debemos modificar también grub:
lxb0751:~# pico /boot/grub/grub.conf

default=0
timeout=10
title Debian 2.6
root (hd0,0)
kernel /boot/vmlinuz-2.6.8-3-686 root=/dev/hda1
initrd /boot/initrd.img-2.6.8-3-686


lxb0751:~# grub-install /dev/hda
Installation finished. No error reported.
This is the contents of the device map /boot/grub/device.map.
Check if this is correct or not. If any of the lines is incorrect,
fix it and re-run the script `grub-install'.


Reiniciamos de nuevo:
lxb0751:~# reboot

Una vez conectados de nuevo, borramos la antigua partición de swap y la volvemos a activar como swap:

lxb0751:~# fdisk /dev/hda
Command (m for help): t
Partition number (1-7): 5
Hex code (type L to list codes): 82
Changed system type of partition 5 to 82 (Linux swap)


lxb0751:~# mkswap /dev/hda5
lxb0751:~# swapon -a

En este punto, el sistema ya es completamente funcional y se puede proceder como se desee.



 

Trabajando en el CERN (III): Computer Centre

Hace unos días estuve en el Computer Centre, en el edificio 513, donde se encuentran los servidores, clusters y demás elementos de red del CERN. La seguridad para entrar a las salas es bastante alta, se necesita autorización mediante tarjeta magnética. Además, hay cámaras por todo el edificio.

En el primer nivel, un pequeño cluster nada más entrar:



En la primera planta aún hay mucho espacio disponible, actualmente se están instalando más nodos. Al fondo pueden verse los armarios de racks medio vacíos:


En esta planta están los servidores web, de correo, de nombres, y el CERN Internet Exchange Point. En la siguiente foto pueden verse algunos armarios de red:



Con más detalle, puede observarse uno de los switches 10 Gigabit Ethernet (Force 10 Networks), concretamente el modelo E600.



El espacio para Sun. Servidores web, de correo y AFS:



El cluster grande (en la foto tan solo se ve una pequeña parte), ocupa aproximadamente 4 veces más de lo que se ve en la foto:



Por último, sistemas de almacenamiento de datos en cintas, con capacidad de grabar a cada cinta a 30MB/s, consiguiendo tasas de aproximadamente 1GB/s. Diferentes soluciones, una de IBM y otra de StorageTek.



En ambos sistemas, un robot viaja por el interior, cambiando cintas.





 

Excursión a Berna

Esta semana, Zé Pedro, Marco, Takeshi, Omar y yo decidimos visitar Berna, la capital de Suiza, y la ciudad donde Albert Einstein estuvo trabajando para la oficina de patentes.

El trayecto desde Ginebra a Berna, en tren, nos llevó aproximadamente 1 hora y 40 minutos, rodeando el lago Léman, lo que nos permitió observar paisajes como éste. Todo ello por el módico precio de 45CHF ida y vuelta.



Llegamos a Berna, cuyo casco antiguo es patrimonio de la UNESCO, así que no se ven edificios altos ni que desentonen. Los tranvías circulan por toda la ciudad.


Al fondo, la famosa torre del reloj, construida en 1530, con una serie de figuras mecánicas que se mueven a las horas en punto. Siempre hay gente alrededor de la torre cuando falta poco para en punto.




La casa donde vivió Einstein cuando estuvo trabajando en Berna en la oficina de patentes, Kramgasse 49, y dónde vivía cuando publicó la Teoría Especial de la Relatividad.



Vista de Berna después de subir unos 200 peldaños de la escalera de la catedral. Al fondo se ve un edificio en construcción: es el Bundeshaus, el parlamento suizo.


A la izquierda, el río Aare:




Home sweet home. Ginebra de noche:







 

Tributo a Ronald Reagan

Haciendo el repaso a Bloglines, me he encontrado con un tributo a Ronald Reagan en forma de vídeo, a mi parecer, el mejor presidente que ha tenido Estados Unidos, pero también en comparación con los presidentes de otros países en mucho tiempo, con el permiso de Margaret Thatcher, claro está.



Vía Expose the Left



 

Trabajando en el CERN (II): Visita a ATLAS

La semana pasada estuve en una visita guiada a uno de los cinco experimentos de detección de partículas del LHC, ATLAS (A Toroidal LHC Apparatus), que pretende encontrar fenómenos más allá del Standard Model (el mayor modelo de interacciones entre partículas que se usa en la actualidad, que describe las fuerzas strong, electroweak y las partículas elementales que forman la materia).

Uno de los objetivos principales del experimento es encontrar (o demostrar que no existe) el Higgs boson. Como curiosidad, al parecer, Peter Higgs, cuyo apellido da nombre al boson, no tiene del todo claro por qué lleva su nombre. Según he oído a varios físicos, entre ellos Frank Close, a mi parecer, el mejor conferenciante de los que hemos tenido hasta el momento, preferirían no encontrar el Higgs boson, o al menos, tal como está teorizado.

Otra curiosidad es que no se hacen experimentos desde Noviembre hasta Marzo porque la energía que se necesita para alimentar los aceleradores y los diferentes experimentos es tal que no es viable trabajar en invierno debido al precio de la energía y al aumento de demanda por las calefacciones.

El panel del estado de los magnets (podría traducirlo como imanes?). Al parecer se tardan días en bajar la temperatura de los "cables" (solenoids) hasta 4ºK (Kelvin).




Vista desde la superficie:






Unos minutos de ascensor más tarde y un casco, desde una plataforma elevada de observación, se puede ver la construcción del detector:








 

Search



About

newton.gra2.com is a blog about technology, opinion and random thoughts written by Daniel Alvarez, a computer engineer currently living in Zurich, Switzerland.

Topics

News (20/0)
Manuals (24/0)
Security (7/0)
Music (3/0)
Weeklog (1/0)
Personal (34/0)
Photos (3/0)
Opinion (14/0)
Windows (5/0)

Blogroll

Pros i contres (Jordi)
Entrepa de fusta (Oriol)
Spaghetti Code (Isaac)
Made in net (Eric)
Nogare (Juan)
Blog de Isaac Jimenez
Web d'en Jaume Benet
Montcada Wireless (Fran)
Blog d'en Ricard Forniol
Angela Fabregues
in.solit.us

Libertad Digital
FOX News
The Wall Street Journal
The Washington Times
The Jerusalem Post

Michelle Malkin
Eurabian News
Nihil Obstat
Barcepundit
Expose the left
Davids Medienkritik
Johan Norberg
Ayaan Hirsi Ali

User Functions

:

:


Lost your password?

Latest posts

Stories

No new stories

Comments last 2 days

No new comments

Trackbacks last 2 days

No new trackback comments

Links last 2 weeks

No recent new links