Parche para autenticar nginx con Amazon S3

Vuelvo tras el paréntesis del CCNA (4 módulos aprobados, sólo me falta el examen final de certificación) con algo que he estado haciendo esta semana en el curro: un parche poder usar la autenticación de S3 al hacer de proxy con nginx.

En el curro estamos montando una arquitectura de servidores con EC2, S3 y ELB: los EC2 están distribuidos por capas, con servidores nginx (web y proxy) delante de los servidores de aplicaciones Tomcat, y aparte en S3 tenemos todo el material “pesado” (fotos, vídeos, descargas, etc.) Como nginx puede hacer de proxy, en lugar de mandar a los usuarios directamente a S3 hacemos de proxy y mapeamos el contenido en nuestro propio dominio, con lo que además nos ahorramos unas pelillas (S3 aparte de por ancho de banda y espacio ocupado, cobra por número de conexiones).

El problema viene porque tenemos una gran mayoría de archivos que son públicos (imágenes, iconos y otros elementos del diseño y archivos multimedia) y otros que sólo queremos que los puedan descargar los usuarios registrados en la página. Un paso hacia la solución es usar el parche Secure Download, que genera URL que expiran tras unos minutos con lo que los elementos privados estarían asegurados, pero sólo a través de nuestra página. Si alguien descubre el nombre de nuestro bucket y el esquema de URL (y no es muy complicado….) podría descargar cualquier cosa directamente de S3.

Con este parche se puede acabar de securizar las descargas: se hacen privadas en el bucket de S3, de forma que sólo autenticándose puedan descargarse (el usuario final ya no podría descargarlas aunque averigüe la URL), y nginx si que puede acceder autenticándose a la vez que protege en local las URL con el Secure Download.

El parche está disponible aquí: nginx proxy – Amazon S3 autentication

csshX

  • english
  • spanish

Some time ago I wrote an article about Cluster SSH.

Now that I’m using a Mac at work too and am working with clusters again, I’ve googled for a MacOS X-based program similar to cssh. And of course, there’s a guy who has done it! csshX is a different implementation of the same idea, this time written on perl instead of TCL/TK and using OS X’s Terminal.app.

Works like a charm.

nginx, memcached y HTTP 304

  • english
  • spanish

I’m working on the server architecture for a new web portal. It’s going to be Amazon-EC2based and will have a nginx front end to several tomcat back end servers. The nginx servers will proxy-cache some dynamic pages (search results, internal web-services queries) and will also have a static page cache based on memcached.

While starting to roll memcached into the solution I noticed that I stoped receiving HTTP 304 responses, everything served off memcached where 200. After digging a little bit on Google I found out it was the expected behavior as memcached doesn’t store the timestamp (last-modified) of the files. So I’ve given it a try and developed a quick patch. You can find it here.

I’m quite puzzled at the simplicity of the patch, as I didn’t need to code the logic to check if the cached page is more recent than the client’s one and return 302 or 200. After successfully returning the last-modified header from memcached, nginx seems to do the rest of the job somewhere on its own!

I have tested the patch today at work and everything seems to work OK. Will do more extensive testings tomorrow and update the path if needed. In the meantime, if someone gives it a try and works for them (or doesn’t), I’m waiting for your feedback.

Probando nginx

Estoy cacharreando con nginx. El nuevo servidor virtual donde tengo el dominio está un poco justo, con la migración lo dejé con Apache en vez de volver a lighttpd y ahora estoy probando alternativas.

Como aparte de configurar el servidor y el PHP con fast-cgi hay que convertir todos los rewrites del Apache (wpmu y super-cache) al formato de nginx, es posible que el blog haga cosas raras, no se actualice debidamente, algunas páginas no vayan bien, pete, no acepte comentarios, o cobre consciencia de sí mismo y decida matar a todos los humanos. YMMV.

Android rooteado

Creo que por aquí no he llegado a comentarlo, pero hace unos meses me pillé un HTC Magic de Vodafone, si, un móvil con Android. Al final he picado, yo que nunca me he llevado bien con los móviles y de hecho hasta entonces tenía el más sencillo que había encontrado en la tienda. :-)

El bicho es una pasada, todo lo que siempre prometieron las PDA pero en mi opinión nunca llegaron a cumplir. Hace un tiempo ya publiqué un artículo sobre mi opinión de todos estos dispositivos, que creo que están más cerca de los ordenadores (prácticamente en la liga de los netbooks) que de las PDA de antaño. Echando la vista atrás al final el iPod Touch se me quedaba pequeño para todo lo que quería hacer, sin Internet un chisme de estos no deja de ser una PDA muy avanzada; con Internet … ¿un pocket-netbook? Y con una gran ventaja si usáis todos los productos de Google (GMail con sus contactos, Calendar, etc.): sincronización automática, :-) uno de los mayores quebraderos de cabeza con cualquier teléfono o PDA resuelto de un plumazo.

El caso es que ayer me decidí a “rootearlo”. En el caso de los Android no lo veo tan necesario como con los iPhones/iPods Touch, el Market de Android es mucho más abierto que la AppStore de Apple pero aún así hay aplicaciones (aceptadas en Market) que necesitan root, la única limitación que tienes con el firmware original. Además de que quería probar algunas de las características de Hero y Donut que llevan las ROMs “cocinadas”, como p.ej. el multitouch. :-)

El proceso en estos momentos es lo más sencillo del mundo: la semana pasada se descubrió un bug en todos los kernels 2.4 y 2.6 de Linux que permite un escalado de privilegios local, y pronto un tipo desarrolló una aplicación para, con un solo click, ejecutarla y conseguir acceso total al sistema operativo del teléfono. Ya no hace falta instalar la SDK, ni andar con cables y consolas de desarrollo. Eso si, es de suponer que en breve las operadoras actualizarán el software de los teléfonos con el parche que corrige este agujero de seguridad, con lo que me dije “ahora o nunca”. Es el momento antes de que con la próxima actualización ya no se pueda rootear tan fácil y haya que volver al método tradicional.

No voy a explicar el proceso porque en El Androide Libre se han currado un tutorial la mar de sencillo para rootear e instalar la ROM de Cyanogen, que por supuesto ya lleva parcheado el bug. Sólo algunos detalles:

  • momento de pánico: al primer intento el móvil se me quedó frito en el arranque después de la actualización. Solución: en el menú del “Recovery Mode” (arrancar con encendido y casita, es una especie de “lilo” que en el 1er paso del rooteo se sustituye por otro más avanzado que permite hacer backups e instalar las ROMs) hacer un wipe antes de instalar. Acojona. :-)
  • se puede volver al firmware original de Vodafone y el móvil queda como si no hubiéramos hecho nada, para eso el paso del  ”Nandroid backup”. De hecho después de la petada hice esto para recuperar un par de puntos de cordura antes de volver a intentar el proceso (previo wipe).
  • tras la instalación el nuevo sistema no está completamente traducido al español, lo típico de cualquier aplicación de Linux, que con la nueva versión no se ha actualizado el .po de gettext y alguna que otra frase sale en inglés.
  • también se pierde la configuración de los APN de Vodafone, con lo que nada más arrancar no hay acceso a Internet (p.ej. el registro de la cuenta de Google falla). La configuración hay que hacerla a mano, datos aquí (si, si, pone Airtel).
  • y parece que se pierde también la configuración de todas las aplicaciones, a pesar de que guardé y luego restauré aplicaciones y datos con el MyBackup. :-/ La configuración del sistema si que la restaura, pero la de las aplicaciones no. :-(

Aparte de eso … como la seda. Aún no le he metido caña con lo que p.ej. lo de que la batería aguanta más no lo he podido comprobar. Pero si que funciona el multitouch (en el navegador se puede hacer zoom “pinchando” como en el iPhone), y si que da la impresión de que todo va más rápido, más fluido. No en vano la Cyanogen se originó en el Dream, con menos memoria que el Magic, así que si está optimizada para funcionar con un dispositivo menos cañero con éste va de lujo.

Ahora a meterle caña al juguete. :-)

Consejos para pruebas de carga de servidores y proxies web

  • english
  • spanish

At work, one of the technologies I work with are web proxies. On my previous work, web servers and web applications. On both cases before going into production (or before rolling an update) it’s wise doing some stress-testing, trying to assess the limits of the technology or the need for more servers. There are commercial solutions available, like e.g. Spirent‘s Avalanche, but with some work you can roll out your own stress-testing infrastructure using free software.

On the first place, before beginning with the test, you need a measuring tool. Just throwing some load to Apache and then taking a look at the logs, free, ps, and server-status by hand is plain crazy, too much raw information to deal with. One tool I’ve found extremely useful, both for analyzing stress-tests results and for everyday operations monitoring is Cacti.

Cacti is a LAMP-based software which runs a series of (programmable) probes on your systems and makes graphs out of them, graphs of different time periods: the last hours, last days, months, etc. so that you have an historic view of the evolution of the service. Having this historic information is critical, when doing these kind of tests you not only want to know how well the latest release works but how does it compare to the previous one. Or in operations, you want to know the difference between the web traffic spike on a Monday morning compared to the calm of the Sunday afternoon. Just running a test and taking a measure in that moment is not enough, you need to put it in perspective with your previous tests and what you have in your production environment. And you can develop your own probes in whatever programming language you want, so there’s nothing that can be measured (CPU or memory usage, latency, I/O load, concurrent connections, etc.) that you can’t get on the graphs. You’ll add more and more probes and graphs as you go testing and discovering new variables that can affect system performance. Detecting regressions, memory leaks, etc. is very easy (well… visual) when using Cacti.

After having some measuring tool in place, we can start stress testing the systems. If you’re dealing with a web server, you only need a client-simulation program; if a proxy, both that and a server. The server part is easy, just use Apache or (even better) lighttpd or nginx. You want to stress test your proxy application, not the web server behind it, so you want a web server as fast as possible. Even think of putting your cloud (the set of web pages you’re going to test with) in a ramdisk and disabling the server’s access.log. Make sure that the web server doesn’t become a bottleneck or you won’t be really stressing the proxy!

As for the client-simulation software, you have several options: develop your own from the ground up, develop a series of scripts with wget or curl, or use some of the existent solutions available out there, like curl-loader, Apache’s JMeter. or may others. Just Google them.

No matter which software you use for the test, one consideration: These programs usually generate a very high load but under ideal conditions. I mean: you’re running them on a local network, likely with Gbps speeds, without packet loss or rearrangements … That’s not what you’ll find “out there”. Depending on what you want to test, either the theoretical top performance or how a new development would cope with real traffic, you need to adapt the traffic of your test to that.

Things you’ll find useful for tweaking your traffic:

  • If your client-simulation software allows you, don’t run it at full network speed! trickle may come in handy here. At least run two tests: one without speed limit, and another with e.g. a 3mbps limit simulating a DSL line. Bear in mind that this is just a speed limit, the server will still have a high load because at a lesser speed it’ll likely have to cope with more concurrent (blocking?) connections. I’ve seen some software do great on a high speed laboratory test and choke in seconds with slow, real-world traffic.
  • Lose packets. Rearrange them. Insert a router/bridge linux server between your client and your test object and use Linux’s tc system. Take a look here, here, here and here.
  • Simulate multiple origin IPs. Take a whole B or C class network, make sure the routes in all your systems are coherent, and run something like this to randomize the clients’ IP addresses (a bit hacky, but it works):
    while :
    do
      I=$((1+RANDOM%254))
      J=$((1+RANDOM%254))
      /sbin/iptables -t nat -F
      /sbin/iptables -t nat -A POSTROUTING -d 1.1.1.1 -o eth1 -j SNAT --to-source 10.10.$I.$J
      sleep 0.1s
    done

With all this in place, you should have a pretty decent testing framework going.

Segundo monitor en el Lenovo T400 con Jaunty

  • english
  • spanish

A couple of weeks ago I upgraded the laptop I use at work to Jaunty, and since then I couldn’t get the external monitor to work properly.

This laptop has two graphic cards: an Intel one integrated on the mainboard, which uses few battery power; and an ATI one with all the bells and whistles, which of course takes more battery. On Windows the graphic driver can change from one to the other on the fly, but on Linux you can’t. You need to go to the BIOS and select one, disabling the other one.

So since I upgraded to Ubuntu 9.04, I the Intel card (which is the one I always use, I use this laptop for work only so I’d rather have half an hour of extra battery than ultra-fast OpenGL… heck, I even have compiz disabled) wouldn’t even boot, X hanged while booting when using that card. And with the ATI card and the fglrx driver, getting the external monitor to work is a PITA. And I need it, as from time to time I give presentations and training sessions and need to hook the laptop to a projector.

I finally found the solution on a Ubuntu forum somewhere (lost the link, sorry): uninstall the fglrx driver! Even if I didn’t use it, even if the ATI card was disabled on the BIOS (wouldn’t even show on lspci) and on the xorg.conf file was using the Intel driver and not the fglrx one, if this driver was installed X would crash when using the Intel card. Uninstall it and voila! The Intel card works again and so does the external monitor configuration applet. Weird.

Ubuntu 9.04 en un Lenovo T400

Un par de URLs útiles para acabar de configurar y optimizar el sistema en un Lenovo T400:

Destacar en el 1er enlace por el final, la guía para configurar el aparcado automático de los cabezales del disco duro en función de si el acelerómetro detecta movimiento (APS), al estilo de lo que llevan los MacBook Pro. ¡Funciona!

Grande Debian, y grande screen

Este finde pasado he actualizado la Debian del Slug de Etch a Lenny. En remoto desde Alicante, a ratos y a lo largo de los tres días (viernes-domingo). XDDD

Cómo molan dos cosas:

  • dist-upgrade de una plataforma no sé si minoritaria, pero desde luego menos extendida y probada que i386, sin problemas. Todo a la primera. Yay!
  • screen. En remoto con una hardware tan justito y lento como el slug hubiera sido imposible. Con screen: abre sesión, “aptitude full-upgrade”. Apaga el ordenador, cena con amigos, vuelves a casa, ssh, screen … mira, pregunta algo. Respondes. Apagas y a dormir. Al día siguiente otra vez … luego desde casa de un colega …

Son pequeños detalles que al final te acostumbras a ellos y creo que no los valoras en su medida, si no te paras a pensar lo coñazo que hubiera sido tener que reinstalar, que la actualización no fuera bien y al reiniciar no arrancara, o no haber podido ir entrando y saliendo de la sesión durante tres días sin tener que mantener el ordenador encendido y la conexión ssh abierta (y sin cortes con un 3G de Yoigo!).

Bravo!