XFS and LVM snapshots

Marzo 31, 2007

This is another article I’ve written some years ago (2003-09-29, original URL). It used to be quite popular, so I’ve decided to recover it and publish it again here:

I want to do a consistent snapshot of my /home, which is an XFS filesystem created on an LVM logical volume:

# grep home /etc/mtab
/dev/vg01/lvhome /home xfs rw,noatime 0 0

# lvdisplay /dev/vg01/lvhome
--- Logical volume ---
LV Name                /dev/vg01/lvhome
VG Name                vg01
LV Write Access        read/write
LV Status              available
LV #                   2
# open                 1
LV Size                800 MB
Current LE             200
Allocated LE           200
Allocation             next
Read ahead sectors     1024
Block device           58:1

In order to get a consistent image of the filesystem in the snapshot, we need to freeze it, so the log jornal is flushed and no more accesses are done to it.

So the idea is : freeze, take snapshot and then unfreeze (see xfs_freeze(8))

# xfs_freeze -f /home
# lvcreate -l 30 -n lvsnap_home -s /dev/vg01/lvhome
# xfs_freeze -u /home

I’ve created the snapshot with 30 extents which is ~15% of the original LV.

Now we can mount the snapshot, and for example make a backup of the filesystem while users can continue to work.

# mount /dev/vg01/lvsnap_home /mnt/tmp/
mount: block device /dev/vg01/lvsnap_home is write-protected, mounting read-only
mount: wrong fs type, bad option, bad superblock on /dev/vg01/lvsnap_home,
or too many mounted file systems

The mount error message is a little confusing, but looking at console messages or syslog, we can see the explaination:

kernel: XFS: Filesystem lvm(58,2) has duplicate UUID - can't mount

Uff… actually we are in trouble: as expected, the snapshot is an image of the orginal filesystem, so it also has it UUID.

The solution could be:

# xfs_admin -U generate /dev/vg01/lvsnap_home

But it can’t be done because the snapshot is read-only.

NOTE: i’ve read that there is a LVM kernel patch and userland tools patch for mounting a LVM snapshot r/w, but i’ve not seen it.

Actually i’ve found the solution in Documentation/filesystems/xfs.txt: using the nouuid option of mount:

# mount -o ro,nouuid /dev/vg01/lvsnap_home /mnt/tmp/

That’s it:

alegrome:~# df /home /mnt/tmp/
Filesystem           1K-blocks      Used Available Use% Mounted on
/dev/vg01/lvhome        814400    201508    612892  25% /home
/dev/vg01/lvsnap_home   814400    201504    612896  25% /mnt/tmp

UPDATED (Sat, 31 Mar 2007 14:40:59 +0200):
This article works for LVM10. It may be obsolete when you use LVM2, as it seems that LVM2 snapshots are R/W by default now.


Las teclas Magic SysRq de Linux

Marzo 17, 2007

Este es otro articulo que escribi tambien hace bastante tiempo (2003-11-12). Ahora lo vuelvo a publicar aqui:

Introduccion

Las teclas Magic SysRq pueden resultar muy utiles cuando estamos administrando un sistema linux (sobre todo de forma remota, si accedemos por consola serie desde otro equipo). En ciertos momentos incluso pueden resultar ser la unica forma de actuar con el sistema (sin no queremos desplazarnos para rebotarlo por ejemplo).

Nos permitiran realizar acciones como:
* observacion del estado de la maquina: memoria, procesos, registros,
* reboot de emergencia,
* apagar el sistema (apagado electrico),
* provocar un panic y vocado de un dump (con un parche de kernel).

Lo mejor es que todo occure a nivel de kernel, con lo cual no hace falta que este ningun servicio arrancado, y suele responder bien incluso si la maquina esta “colgada”.

Habilitar las teclas Magic SysRq en el kernel

Para poder usar las teclas magicas, tenemos que hacer dos cosas:

* habilitar el soporte en el kernel para las teclas Magic SysRq
* activarlas (ver apartado siguiente)

Para habilitar el soporte en el kernel, poner la opcion siguiente en nuestro .config:

CONFIG_MAGIC_SYSRQ=y

En el make menuconfig de un kernel 2.4 la opcion esta en :

   ...
   [*] Kernel debugging
      ...
      [*]   Magic SysRq key
      ...

Activar las teclas Magic SysRq en el kernel

Para activarlas, primero debemos correr un kernel con soporte para las teclas Magic SysRq. (ver apartado anterior).

En los kernel derivados del stock kernel, deberia estar activado por defecto. De no ser asi (por ejemplo en los kernel de RH) hay que activarlo en el arranque, con:

echo "1" > /proc/sys/kernel/sysrq

Tambien se puede usar sysctl(8).

El no tenerlas activadas por defecto, impide poder usar las teclas magicas durante el arranque del kernel (hasta que se activen). Esto puede ser problematico. Con lo que, en mi opinion, es mejor que este activado por defecto.

Para comprobar y/o activarlo por defecto, basta mirar en las fuentes de nuestro kernel, en /usr/src/linux/drivers/char/sysrq.c y buscar sysrq_enabled:

...
/* Whether we react on sysrq keys or just ignore them */
int sysrq_enabled = 1;
...

Resumen de teclas Magic SysRq

'h' '.' - Will display help ( actually any other key than those listed
          above will display help. but 'h' is easy to remember :-) 

* Estado de la maquina:

'0'-'9' - Sets the console log level, controlling which kernel messages
          will be printed to your console. ('0', for example would make
          it so that only emergency messages like PANICs or OOPSes would
          make it to your console.)

'm'     - Will dump current memory info to your console.

't'     - Will dump a list of current tasks and their information to your
          console.

'p'     - Will dump the current registers and flags to your console.

* Accion sobre los procesos en maquina:

'e'     - Send a SIGTERM to all processes, except for init.

'i'     - Send a SIGKILL to all processes, except for init.

'l'     - Send a SIGKILL to all processes, INCLUDING init. (Your system
          will be non-functional after this.)

* Forzar reboot:

Pulsar esta secuencia de teclas Magic SysRq para forzar un reboot limpio del sistema: primero intenta hacer un sync de los filesystems, despues los intenta cambiar a modo r/o, y por fin se manda reiniciar el sistema (no pasa por los rc).

's'     - Will attempt to sync all mounted filesystems.

'u'     - Will attempt to remount all mounted filesystems read-only.

'b'     - Will immediately reboot the system without syncing or unmounting
          your disks.

* Apagar:

'o'     - Will shut your system off (if configured and supported).

Como usamos estas teclas?

* Desde la consola “fisica” (monitor & teclado pinchado al equipo), tenemos que teclear Alt-SysRq-Tecla. En un teclado normal, la tecla “SysRq” es tambien la tecla “Print Screen”.

* Desde la consola serie, tendremos que mandar un break. Una vez mandado el break, tendremos un tiempo de 2-3 segundos para teclear la tecla en cuestion.

Por ejemplo: Break+’.’ -> Ayuda.

Ejemplo: servidor “colgado”

Para el ejemplo, imaginemos que tenemos un servidor A que se ha quedado colgado (por ejemplo ha hecho un oops! y no se recupera solo). Ya no nos deja ya entrar ni por telnet, ni por ssh… nada! Nosotros estamos en otro edificio, pero, por suerte, podemos entrar en B que hace de consola remota de A (por conexion serie – ver articulo sobre como configurar consola serie).

Nos conectamos a B (por telnet, ssh, lo que sea…), y desde B nos conectamos a A por serie (con cu o minicom por ejemplo. Yo prefiero cu, por su tecla de escape).

Una vez que tenemos la consola, le damos a intro, a ver si sale el login de A. Si sale el login, bien, podremos intentar entrar y hacer reboot ordenado del servidor.

Si no sale el login, que hacemos ?? Vamos a usar las teclas Magiq-SysRq !

Primero, lo que suelo hacer para asegurarme que responde bien el kernel, es comprobar que funcione la tecla ‘.’ . Debe aparecerme la ayuda.

servidorB$ cu -l /dev/ttyS0 -s 9600 dir
Connected.

~# '.'
SysRq : HELP : loglevel0-8 reBoot tErm kIll saK showMem showPc unRaw Sync showTasks Unmount

Ok !!

Ahora, la secuencia de teclas que usaremos para rebotar es SUB: S-U-B,
o sea:

S: Syncronizar los FS
U: desmontar y montar r/o los FS
B: reboot

Asi intentaremos minimizar una eventual corrupcion de los filesystems.

~# 's'
SysRq : Emergency Sync
Syncing device 08:02 ... OK
Syncing device 08:01 ... OK
Syncing device 08:04 ... OK
Done.

Segun la documentacion, el sync se ha hecho bien si aparece el OK. A veces me ha pasado que no aparecia… supongo que no se habra hecho el sync. Tampoco es grave.

~# 'u'
SysRq : Emergency Remount R/O
Remounting device 08:02 ... OK
Remounting device 08:01 ... OK
Remounting device 08:04 ... OK
Done.

~# 'b'
SysRq : Resetting
Disconnected.

En ese momento, la maquina estara rebotando (como si le hubieramos dado al boton de reset).

Mas informacion

La documentacion del sysrq esta en:
/usr/scr/linux/Documentation/sysrq.txt.

Conectarse a la consola serie con cu:

cu -l /dev/ttyS0 -s 9600 dir

Mandar un break con cu: ~#


Consola serie de un Linux

Marzo 17, 2007

Este es un articulo que escribi hace tiempo ya (2003-03-14). Lo tenia publicado en mi web y era bastante popular (segun las estadisticas del apache). Ahora lo vuelvo a publicar aqui:

Introduccion

Una vez configurada la consola serie, podremos conectarnos a la consola de nuestro equipo desde otro por puerto serie.

Esto implica dos equipos:

Basicamente, nuestro “servidor” SERV, y un cliente CLI.

Configuramos lo que detallo a continuacion en SERV, conectamos SERV y CLI por un cable null-modem, y desde CLI accederemos a la consola de SERV.

Para que sirve esto ?? Si es mucho mejor conectarse por red por ssh o incluso telnet!

Ya, pero desde la consola de un equipo, podemos hacermas cosas:

* entrar como root (cuando en general esta deshabilitado el acceso a root por telnet/ssh)
* rebotar la maquina SERV ! (por si se hubiera quedado “frito”)
* rebotar+entrar en modo single user !!

Ambas cosas pueden resultar de gran interes por ejemplo si tenemos 2 equipos Linux A y B con conexion a Internet, configuramos esto en ambos de tal forma que desde cualquiera sea “consola del otro”: desde A podremos conectarnos a la consola de B (A sera consola de B), y vice-versa.

Si por ejemplo B se queda frito, entramos en A por ssh o lo que sea (de forma remota), y desde A abrimos la consola de B: a lo mejor podemos ya algun mensaje “raro” en la consola de B que nos indique el problema (como un Oops por ejemplo). Si no consequimos entrar como root, al menos podemos rebotar la maquina y si hace falta entrar en sigle user para hacer algo de mantenimiento !

Pero como se hace esto ?? Pues ahi va…

Configuracion en el kernel

Primero tenemos configurar el soporte para los puertos series y la consola serie en nuestro kernel. Los kernels de RH ya vienen con este soporte.

* En /usr/src/linux/.config:

...
CONFIG_SERIAL=y
CONFIG_SERIAL_CONSOLE=y
...

* O si preferimos usar make menuconfig/xconfig

Character devices  --->
   Standard/generic (8250/16550 and compatible UARTs) serial support
  [*]   Support for console on serial port

Luego hay que compilar el kernel :) .

Habilitar el login de root en la consola serie

Primero tenemos que tocar el inittab para que se levante un getty en el puerto serie.
Nuestra consola en cualquier equipo sera el ttyS0 (el primer puerto serie). (Para conectarnos a otro equipo, usaremos el ttyS1)

* En el /etc/inittab:

#
T0:S123:respawn:/sbin/getty -L ttyS0 9600 vt100
#  ^

*En el /etc/securetty:

Añadir una linea con ttyS0

Configurar Grub

Vamos a configurar dos cosas en Grub:

1- Que grub sea capaz de interactuar con el usuario a traves de la conexion serie: para ver el menu de grub desde la consola serie (CLI) [opciones "serial" y "terminal"]

2- Pasaremos al kernel que cargamos desde grub el parametro console=ttyS0, para que este sepa que debe tratar el ttyS0 como la consola (pero ya no el monitor&teclado).

En este ejemplo, tambien he puesto el parametro de kernel panic=30 que permite que el kernel rebote si hace un panic. [Pienso que es mejor especificar este parametro desde el grub a ponerlo con un echo 30 > /proc/... por si se produce un panic en el arranque, antes que que se carge el script de arranque.]

En /boot/grub/menu.lst:

...
serial --unit=0 --speed=9600
terminal --timeout=10 serial console

default=0

title           Debian, kernel testing - serial console
root            (hd0,0)
kernel          /kernel-testing root=/dev/hda3 ro console=ttyS0 panic=30
boot
...

Pues ya esta. Una cosa mas, desde un linux, para conectarse por serie a otra maquina, podemos usar el minicom por ejemplo.
Desde un windows, el hyperterminal o el secureCRT por ejemplo.


Non-interactive ssh to your La Fonera

Marzo 16, 2007

The Dropbear mini ssh daemon doesn’t recognize $HOME/.ssh/authorized_keys files. However, you can configure authorized public keys in /etc/dropbear/authorized_keys (using the same format).

For example, you can do:

scp .ssh/id_rsa.pub root@fon01:/etc/dropbear/authorized_keys

The next time you access your Fonera box, you won’t need to enter root’s password ;-) .


Tweak your FON Chillispot allowed URL list

Marzo 5, 2007

Following Ivan’s article about how the La Fonera automatically updates it’s chilli.conf file (Chillispot configuracion file), and about the fact that you may like to configure your own set of allowed URLs — URLs users can browse without registering against FON radius –, I propose here a modification of /etc/init.d/N50chillispot.

With that patch applyed to N50chillispot:
* You can now specify your own set of allowed URLs. Put the lines into /etc/chilli.allowed (create the file). Leave the file blank or remove file if you don’t want to allow any URL.
* You’ll receive any update to the file (radius changes,…) but you won’t be affected by "uamallowed" lines (your lines will apply instead).

Here is the patch I propose:

--- N50chillispot.old   2007-03-05 11:43:53.000000000 +0100
+++ N50chillispot       2007-03-05 12:22:13.000000000 +0100
@@ -2,7 +2,9 @@
 . /tmp/network-config

 TMP_C=/tmp/chilli.conf
+TMP_C_T=/tmp/chilli.conf.tmp
 ETC_C=/etc/chilli.conf
+ETC_W=/etc/chilli.allowed
 PID_F=/var/run/chilli.pid
 PID_LOOP_F=/var/run/chilli_loop.pid
 LOG_LOOP_F=/var/log/chilli_loop.log
@@ -69,6 +71,9 @@
                --dhcpif $wifi_ifname \
                > $TMP_C
        [ -n "$(cat $TMP_C)" ] &')
                MD5SUM_ETC=$(md5sum $ETC_C | awk '{ print $1 }')
                if [ ! "$MD5SUM_TMP" = "$MD5SUM_ETC" ]; then

(tested on Fonera Firmware Version 0.7.1 rev 1)


Change your Fonera date and timezone

Marzo 4, 2007

# echo "CET-1CEST-2,M3.5.0/02:00:00,M10.5.0/03:00:00" > /etc/TZ
# ntpclient -c 1 -s -h pool.ntp.org
39143 45854.743  153016.0     25.0  104118.5  43060.3         0
# date
Sun Mar  4 13:44:29 CET 2007

Now the date and timezone is correct.

Reference:
* Timezone at OpenWRT Configuracion wiki


Change your Fonera hostname

Marzo 4, 2007

The Fonera OS doesn’t bring the hostname command, but you can change it’s default “OpenWrt” hostname to any hostname you like:

# sysctl -w kernel.hostname=fon01
kernel.hostname = fon01
# uname -a
Linux fon01 2.4.32 #9 jue nov 23 12:11:45 UTC 2006 mips unknown

(note: the date is wrong!)

You can make it persistent accross reboot:

echo "kernel.hostname=fon01" >> /etc/sysctl.conf


Shell access (ssh) on your Fonera

Marzo 4, 2007

Movimiento FONRight after receiving my free La Fonera social router, I plugged it into my local home network, and registred it, as explained in the provided guide. The problem (I knew it later), is that when the Fonera boots, it connects to Fon and upgrades itself (and reconfigures itself also).

So, as I plugged my Fonera to Internet, it upgraded to the latest firmware revision, for which there is no known hack to get ssh shell access.

Today I searched for a way to succesfully downgrade my Fonera to it’s original firmware.

After trying several ways (found on the Internet) with no success, this is the way that finally worked for me:

* Configure your PC with ip 169.254.255.2/24
* Connect your PC and the Fonera with a direct cable (straight or crossover ethernet, doesn’t matter, the Fonera is smart enough)
* Press the reset button (down the fonera) for 20 seconds
* Release the button
* From the PC, ping 169.254.255.1 (As it cannot get any DHCP IP, the Fonera autoconfigure it’s eth0:1 with this zeroconf IP).
* Wait till it’s reachable (approx 2mn)

When the IP is reacheable (when the Fonera answers the ping requests), you can now apply the following hack:

Create on your PC 2 html files, with the following content:

step1.html:

step2.html

Now, open step1.html with your favorite browser and click the submit button (if your are asked for login/passwd, unless you changed it, try admin/admin). Once done, do the same with step2, and submit.

The dropbear ssh deamon should now be open on your Fonera! You can get a shell inside your Fonera: connect by ssh to 169.254.255.1 (port 22): user root and password admin, unless you changed it (the same passwd as the web UI).

Final steps are:

* Activate ssh permanently :

root@OpenWrt:~# mv /etc/init.d/dropbear /etc/init.d/S50dropbear

* Unlock firewalling rules :

root@OpenWrt:~# vi /etc/firewall.user

* Uncomment the following :

iptables -t nat -A prerouting_rule -i $WAN -p tcp --dport 22 -j ACCEPT
iptables -A input_rule -i $WAN -p tcp --dport 22 -j ACCEPT

* Deactivate automatic Fonera updates :

root@OpenWrt:~# vi /bin/thinclient

* Comment the following line (last one) :

#. /tmp/.thinclient.sh

At this point I had some troubles with the Fonera not catching IP by DHCP. By advice of another fonero-geek and friend (Ivan!), I set up the Fonera to use a static IP (using the MyPlace web UI), and everything worked fine. Eventually this morning I changed back the Fonera to get it’s IP by DHCP and it actually worked too.

Some sources that inspired me a lot (and more):
http://imil.net/docs/fonera-ssh.txt
http://blog.blase16.de/2006/11/28/Hacking-Fonera