Archive for the 'Linuxadas' Category

Imágenes en “negativo” tras escalar con ImageMagick

Un apunte rápido de una cosa que solucioné en el trabajo hace unas semanas y desde entonces he visto en otro par de sitios.

Al escalar imágenes con el convert de ImageMagick (o con alguna de sus API) algunas fotos se quedan como en negativo: tonos negros, verdes oscuro, etc. aunque por supuesto la imagen original se ve bien. Después de darle vueltas el “problema” con estas imágenes es que el color iba codificado en CMYK en lugar de RGB, y por lo visto ImageMagick en el escalado por defecto usa RGB como salida y no realiza la conversión necesaria.

Solución rápida: antes de escalar las imágenes, pasarlas a RGB con:


convert -colorspace rgb original.jpg rgb.jpg

En medios exclusivamente digitales es difícil que esto pase, ya que para imágenes en pantalla se usa RGB. Sin embargo en medios que trabajen también con papel (prensa, editoriales, publicidad) es más fácil porque CMYK es el modelo que se usa para imprimir, y es posible que alguna foto en este formato pase inadvertidamente a la versión digital del medio.

  • Twitter
  • Facebook
  • Meneame
  • email
  • Print
  • PDF
  • RSS

Per-domain tinydns configuration

  • english
  • spanish

It’s no secret that I really like DJB’s software. I think that qmail and djbdns are rock-solid pieces of software, something you can really rely on. But some people just don’t get them and bash them for whatever reasons.

Case in point, djbdns. Many a time I’ve heard the argument that having all tinydns’ domains in a single data file is a PITA. Well, that proves those people don’t get the point in DJB configuration files: you can edit them by hand, but their real power is that they’re easily scriptable! You don’t want having all the domains in a single file? Ok, split them and join them before compiling!

You can do this with the following makefile: split the domains, one per file on the “domains” directory, and work with those files, don’t ever touch the original “data” file again. And if you have a backup server put it’s IP address or FQDN on an env/BACKUP file. Then when you run “make” it will join all the files, compile them and sync the results with the backup server. Easy as pie, don’t you think?


all: data.cdb

data: domains/*[^bB][^aA][^kK~]
        cat $+ > data

data.cdb: data
        /usr/bin/tinydns-data
        [ -f ../env/BACKUP ] && rsync -azv * root@`cat ../env/BACKUP`:`pwd`

clean:
        -rm -f *~ domains/*~
  • Twitter
  • Facebook
  • Meneame
  • email
  • Print
  • PDF
  • RSS

Debuggin nginx issues

  • english
  • spanish

Last week I’ve been debugging a problem I had with this site’s nginx server: from time to time it hanged and I had to restart the process. Some time ago I wrote a little script that checked if it was running OK and restarted it otherwise, but anyway that wasn’t a real solution.

So I spent some days really looking into it and asking for support and reporting my findings to the nginx mailing list. One useful tip I got there was enabling the “debug” mode on the error log, which shows full traces of the processes (including their PID) as they’re processing the request, the rewrites, upstreams, etc.

error_log /var/log/nginx/$host-error.log debug;

With this extended log and the PID of the process malfunctioning, it’s quite easy finding out what that process was doing right before hanging. In order to find out the PID of the hanged processes, I extended my check-reboot script to log some generic system metrics right before restarting nginx: netstat -nap (which shows the PID), ps, vmstat, etc.

#!/bin/sh

TIMEOUT=20
CHECK=http://localhost/wp-admin/
LOG=/var/log/checkWeb/checkWeb-$(date +%Y%m%d).log
LOGR=/var/log/checkWeb/restart-$(date +%Y%m%d).log
TMP=/tmp/checkWeb-$RANDOM

if ! wget -t 1 -o /dev/null -O /dev/nul -T $TIMEOUT $CHECK
then
echo "ERROR, restarting nginx"
echo "** RESTARTING **" >> $TMP
date >> $TMP
echo "- CLOSE_WAIT:" >> $TMP
netstat -nap | grep -c CLOSE_WAIT >> $TMP
echo "- vmstat" >> $TMP
vmstat 1 5 >> $TMP
echo "- free" >> $TMP
free >> $TMP
echo "- ps" >> $TMP
ps aux >> $TMP
echo "- netstat" >> $TMP
netstat -nap >> $TMP
echo "" >> $TMP
echo "" >> $TMP

#       pkill -9 -f php-cgi
pkill -9 -f nginx
sleep 1s
/etc/init.d/nginx start

cat $TMP
cat $TMP >> $LOG
date >> $LOGR
fi

rm -rf $TMP

This way, each time localhost/wp-admin was unresponsive (I was debugging a WP site), besides restarting nginx I was getting a lot of system info. With time I got to realize that nginx processes were not actually hanging, but some of their sockets got on the CLOSE_WAIT state forever until the process was restarted. Looking for the PID of those processes according to netstat on the error log, the last request they were processing before getting to the CLOSE_WAIT state was always the same: on my blog I have some examples of how running servers with daemontools; daemontools uses named pipes (FIFOs), which can become kind of black holes if there’s no process feeding them; when nginx hit one of these FIFOs, it hanged.

Funny thing is that I never had this problem with either Apache nor lighttpd. But anyway the problem is not nginx but those FIFOs which shouldn’t really be there. I removed them and have had no hanged processes in five days, while before this nginx was restarting 3-4 times a day.

  • Twitter
  • Facebook
  • Meneame
  • email
  • Print
  • PDF
  • RSS

find -empty,deleting empty dirs

  • english
  • spanish

The find command has an -empty option which detects empty directories of files (0bytes). This is useful if you need to locate or remove empty directories or files from a directory structure:

find /path/ -type d -empty -exec rmdir {} \;
find /path/ -type f -empty

  • Twitter
  • Facebook
  • Meneame
  • email
  • Print
  • PDF
  • RSS

Rewriting URL to lowercase with nginx

  • english
  • spanish

With nginx and its embedded Perl module it is possible to automatically rewrite/redirect every incoming request to a lowercase URL with something like this:

http {
	...
	perl_modules  perl/lib;

 	perl_set $uri_lowercase 'sub {
   		my $r = shift;
   		my $uri = $r->uri;
   		$uri = lc($uri);
   		return $uri;
 	}';
	...
}

server {
	...

	location / {
               if ( $uri != $uri_lowercase ) {
                       rewrite . http://$host$uri_lowercase;
               }
# or just:
#		rewrite . $uri_lowercase;
	}
	...
}

The first option (with the if and http://$host) sends an HTTP redirect to the lowercase URL if the requested URL is not completely in lowercase. I like this approach better as it kind of normalizes all URL to a canonical form. The second option (without if nor http://) just accepts any URL and internally rewrites them to lowercase: if you rename all your directories and files to lowercase, this will imitate Windows’ case-insensitive behaviour.

Kudos to the following post on the nginx users list were I draw the “inspiration” :D from to get this done. The embedded perl doc and examples are indeed scarce. :-(

http://forum.nginx.org/read.php?2,39425,39944

Anyway I see two problems in this approach:

  • you need the embedded perl module which according to the docs is experimental and can lead to memory leaks.
  • the actual redirection is done with the rewrite, which you can put on the location you need. But the URL lowercase calculation, being on the “http” section of the config, is done for each and every request arriving to your server. Say you have a virtual server with 10 domains and you only need this on one particular location of one of them. The lowercase URL is going to be calculated for every request of every domain.

I guess that by defining a perl function the URL calculation could be restricted to a particular location, have to look into it further. Another option is writing a C module.

And why would anybody want to rewrite every URL to lowercase? We’re migrating a legacy Tomcat-based application from Windows to Linux, and it seems the original developers were not “case-aware” at all, they mixed upper and lowercase in the filenames without regarding how the actual files were named. On Windows this is not a problem but when moving the app to Linux it is. So we have renamed every file and directory to lowercase and used the previous configuration on the nginx servers that load-balance our Tomcat farm. Some corner-cases remain (includes in JSP files, which don’t route back to the nginx server and are dealt internally by Tomcat) and have been dealt with one by one, but the bulk of wrongly addressed images, videos, links to HTML files, etc. now works.

  • Twitter
  • Facebook
  • Meneame
  • email
  • Print
  • PDF
  • RSS

Setting the date on Amazon EC2 servers

  • english
  • spanish

Amazon EC2 virtual servers’ internal clock is synchronized with that of their host server. But some host servers seems to be off-date: I’m working on a four-server cluster (will grow to eight when we go into production) and while three of them were perfectly synchronized, the fourth one lagged behind a couple of minutes.

By default you can’t adjust the date with either date nor ntp, the commands execute but do nothing. In order to decouple the VM’s clock from the host’s one and being able to set the time on your system you need to run the following command:

echo 1 > /proc/sys/xen/independent_wallclock

Bear in mind that, as pointed out here, after decoupling your clock from the host’s you can’t go back, you’ll be on your own forever.

  • Twitter
  • Facebook
  • Meneame
  • email
  • Print
  • PDF
  • RSS

Keeping SSH sessions open

  • english
  • spanish

Sometimes SSH sessions die. At work I usually have several ssh sessions with a number of servers, and depending on the configuration of some intermediate router/firewall some TCP sessions get closed after a little while, the SSH sessions die and you have to log back in again.

To prevent this you can instruct sshd to implement some kind of keepalive mechanism preventing the TCP sessions from dying, by including these options on the sshd_config file:

KeepAlive yes
ClientAliveInterval 60

  • Twitter
  • Facebook
  • Meneame
  • email
  • Print
  • PDF
  • RSS

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

  • Twitter
  • Facebook
  • Meneame
  • email
  • Print
  • PDF
  • RSS

Real-time HTTP headers capture

  • english
  • spanish

Some people call me a freak because of doing things like this, analyzing a tcpdump capture with strings and grep:


tcpdump -i any -p -s 0 -w - "port 80" | strings | grep -E "^(GET|POST|HEAD|[a-zA-Z-]+:) "

:-D

  • Twitter
  • Facebook
  • Meneame
  • email
  • Print
  • PDF
  • RSS

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.

  • Twitter
  • Facebook
  • Meneame
  • email
  • Print
  • PDF
  • RSS



Bear
Creative Commons Attribution-NonCommercial 2.5 Spain
This work is licensed under a Creative Commons Attribution-NonCommercial 2.5 Spain.