Since a couple of hal versions (0.5.12~git20090406.46dc48-1) in Debian Sid, it stopped using system groups as the method to grant privileges to users, and started using something called PolicyKit instead. Just to remember what are we talking about here, a user in the powerdevil group used to suspend or hibernate his machine sucessfully. But now Mr. PL is a not-understood monster and the package does not give a smooth transition. That's what I'll try to do here.

To make sure this is the problem, let's try to suspend the machine simply by calling hal through d-bus. I use qdbus here, found in the libqt4-dbus package, because it lets me introspect the dbus interface, but you could use dbus-send instead:

qdbus --system org.freedesktop.Hal /org/freedesktop/Hal/devices/computer org.freedesktop.Hal.Device.SystemPowerManagement.Suspend 0
Error: org.freedesktop.Hal.Device.PermissionDeniedByPolicy
org.freedesktop.hal.power-management.suspend no <-- (action, result)

If we edit the file /etc/PolicyKit/PolicyKit.conf we'll see the empty default config that comes with the package. According to its documentation, we just need to add a couple of nested <match> tags with a <return> inside. The outher match will filter the hal action, the inner one the group, and the return will grant access.

... we wish! There's no way to match to a group, only to a user. Ok, the first shot will use the user, then we'll see if we really can do it.

How do we discover which action we must use? We can use polkit-action to see what are the available actions. In the first case, org.freedesktop.hal.power-management.* will do.

<match action="org.freedesktop.hal.power-management.*">
    <!--match group="powerdev"-->
    <match user="mdione">
        <return result="yes"/>
    </match>
</match>

Now the previous command suspends the machine allright! Next, removable devices:

<match action="org.freedesktop.hal.storage.mount-removable">
    <!--match group="plugdev"-->
    <match user="mdione">
        <return result="yes"/>
    </match>
</match>
<match action="org.freedesktop.hal.storage.eject">
    <!--match group="plugdev"-->
    <match user="mdione">
        <return result="yes"/>
    </match>
</match>

I added the eject action just in case. All this works fine for my user, but I really liked the group interface. The complaining about it was that it was too coarse, and now this way one can grant specific actions in amore fine grained way, but I think is too fine grained. Unluckly we cannot (ab)use the define_admin_auth tag to give a similar functionality, it doesn't work that way (I don't know what way it works either).

As a final note, see that I used a per-action approach, where the outer match points to an action. we could use a per-user approach, where the outer match points to a user:

<match user="mdione">
    <match action="...">
    <match action="...">
    <match action="...">
</match>

debian sysadmin

Posted Wed 27 May 2009 05:25:03 PM CEST Tags: debian

Just a note: from now on some posts will be in English. I just want to make sure some of them are worlwide readable.

During DebConf8 I met John Wright, who works in HP. He packages a couple of python things, like trac-mercurial (currently in sid only), and he offered to teach me how to package python things.

I've been trying to do that for a couple of years, but Debian's Python Policy is just too much for me. Call me lazy, $DEITY knows I know I am, but I just can't cope with so much and dense info.

So, I tried to look for automatical tools to do it. Two years ago the only thing I could find was (WARNING: ugly colors ahead) packer, but its vitality is rather low: according to FreshMeat, it was added on Dec 2005 and last updated on Feb 2006. I started using it, but its interface is not very good, so realeasing further versions was not an easy task. Also, I think now it's very out-of-date to Debian Policy.

This week I tried again, now trying to find something that could use either python-support or python-central to manage the python package, and also that it used the info from setuptool's setup.py, but I only could find some incomplete tutorials.

So John explained it to me. It really comes down to using dh_make, the starting point of debhelper. Before you run it you have to make sure everything's in place for it. That means to put the code in a directory which name is the name of the program, followed by a dash, followed by the version, like psync-0.4.1.

Now you just run dh_make --createorig, who asks what kind of package you're about to build. Normaly a 'single binary' is enough. It will show you some info it has gathered from your environment, about who you are and what package you're building. This will also create a .orig directory in the parent directory (making if a sibling of the current one) from the current directory, so make sure no cruft goes in. Here is the point were if there is no setup.py file, you just add it with the proper info.

This creates the debian directory with a lot of files on it. Those who already read about Debian packaging will find familiar files. If you're not, the best way to figuring out what goes where is the proper Debian Policy.

The first file you have to edit is control; just make sure that you add python and python-support as BuildDeps and ${python:Depends} as Deps.

The rules file is a little more complicated. It's a Makefile with several targets. configure must have the commands needed to configure the project prior to building it. Most python programs don't need this or the next one, which is the build target. This one obviously should have the commands needed to build the program. The third one is clean, where you usualy just neet to replace the boilerplate $(MAKE) clean with python setup.py clean. The install target will need a python setup.py install --prefix=$(CURDIR)/debian/psync/usr. Just check out the $(MAKE) invocation and you'll figure it out.

The last one is the binary-arch target. This one has lots of calls to debhelper functions. If you read it carefully, you'll see a dh_python call, commented out. Don't use it, use dh_pysupport. This is the hook for python-support support. This is the part that does all the magic to make sure that you don't break the Debian Python Policy. And that's mostly it. You can comment out a couple of dh_ functions, like dh_strip or dh_shlibdeps (shared libs deps).

Another file to edit, and this might be the last one, is changelog. This one has a particular format, so I suggest to use dch from the devscripts package. The one you'll find is a template the dh_make left for you to fill. You just need to put the bug number of the ITP bug. What, you haven't send an ITP but yet? Well, do it! Then you can use dch -a to add new entries to the current version's entries, dch -i to increment the Debian version and maybe dch -r to update the date at the bottom of the current version. See its manpage for further options.

Last, there is some junk in the debian directory, most of them the *.ex files, which are just examples. You can safely get rid of them, or read them to see if they suit you.

The next step is to build it. This is as easy-peasy as running dpkg-buildpackage. This will build a .deb file, a .dsc file, a .orig.tar.gz file, a .diff.gz and a .changes file in the parent directory. This is the outcome of all the work you've done so far, but is not finished yet. You better run lintian on the .dsc file and the .deb file. If you add the -i option you'll get some explanation on why you failed to give a proper, no-lint package.

So, that's it. It's a longish post, but should get you up packaging python apps in a few minutes. The are still a few problems: you end up dup'ing info: in the setup.py file and in various files in the debian directory. Maybe I'll hack something to workaround this.

debian python

Posted Sat 23 Aug 2008 10:31:01 PM CEST Tags: debian

En la oficina tenemos un server que entrega nfs; también tenemos mucha gente que compila cosas. Estos dos parámetros hacen que tener sincronizadas las horas de las máquinas sea una necesidad. Pra esto se pueden usar los paquetes ntpdate (para on-time-sync) y ntp (para keep-in-sync). Hoy estuve revisando bien como interactúan ambos, sobre todo al momento del booteo. antes una descripción de qué hace cada uno.

ntp se encarga de mantener la hora de la máquina mas-o-menos sincronizada con la de una fuente externa. Si llega a haber cierta diferencia, se encarga de ir acomodando la hora de a poco, para que el sistema no sufra por cambios bruscos. Un problema que tiene es que si la diferencia con la referencia externa es muy grande, ntp no es capaz de salvar las diferencias y entonces ''no hace nada''. ntpdate se encarga simplemente de setear incondicionalmente la hora local según la hora que consiga de esta referencia externa. El escenario ideal sólo haría uso de ntp, pero en general se podría usar también ntpdate para máquinas con el reloj para-el-carajo, como parece ser el caso de al menos una de nuestra máquinas.

El tema es que, por defecto, ntpdate utiliza un archivo de configuración de ntp, pero a su vez corre despúes de éste, en cuya condición falla pues el puerto UDP que usa ya está en uso por ntp. Desinstalando ntp nos deja sin el archivo de configuración, y en realidad tiene sentido quedarnos con él.

La solución que encontré es simplemente hacer un symlink al script de ntpdate en /etc/network/if-up.d a un nombre anterior al de ntp (por ejemplo, mntpdate). Voy a ver si en debian/ubuntu me dan pelota con lo de ponerles mejor orden que simplemente el nombre.

sysadmin ubuntu debian

Posted Thu 10 Jul 2008 10:34:23 PM CEST Tags: debian

Después de la debacle de la semana pasada (de la que aún quedan algunas secuelas que ya comentaré) y teniendo ya planeada una upgradeada del desrver de Sarge a Etch (cosa que venía haciendo en un Xen hasta que me fui de vacaciones), decidimos hacerlo de una.

Empezamos en otra máquina instalando un Etch prístino. Esto implicó (re)instalar todo el soft que ya estaba corriendo en el servidor (que aún seguía corriendo). Lo único que no instalamos de nuevo aún es el zope/plone; tal vez lo hagamos directamente con lo que llaman un buildout.

Una desición personal, sobre todo basada en que en este entorno casi todos somos root, fue instalar algo que mantuviera en un rcs el contenido de /etc. Hace un par de años me senté a intentar un wrapper para svn que guardara la metadata como properties de los archivos llamado sylvan. El sistema era mas o menos usable, pero por suerte el genio de Joey Hess le ocurrió el mismo problema y salió con etckeeper. ectkeeper no está en Etch, por lo que instalé ese paquete y metastore bajándolos del repo de Sid y mercurial del repo de backports. Como no estoy seguro que el nnotito de aptitude sepa manejar este tipo de repos [para el caso creo que dselect tampoco] no puse backports entre los deblines.

El siguiente paso fue mergear la configuración actual del server con lo que me dejó esta instalación. Claramente no era cuestión de tirar el /etc viejo encima del otro y que se hagan agua los helados. Para ello usé xxdiff (o también podría haber usado meld o diff3 para emacs), pudiendo seleccionar qué pedazos quería específicamente. Un poco de edición y estábamos casi listos.

El penúltimo paso fue popular el nuevo LDAP. pare ello alcanzó un slapcat -l en el server; borrar los registros que ya están en el server nuevo (el root del directorio y el admin); luego un slapadd -l en el nuevo; y luego probar con un par de ldapsearchs. Tambien copiar los certificados y cambiarles el owner a openldap.

Luego tocó hacer andar PAM y nss contra dicho LDAP. La configuración estaba "as is", incluyendo los certificados. Luego de algo así como una hora encontré que la parte de TLS no estaba andando, así que hube de desactivarla, para lo cual śolo hubo que comentar el ssl start_tls y ya. Mas adelante veré cómo reactivarla.

Ya listos (cerca de las 12 de la noche) apagué el server, instalé el disco y a bootear. Y acá es cuando comienza el verdadero baile.

Por suerte el mail no me trajo verdaderos problemas. Sólo tuve que ser muy cuidadoso, pues nosotros bajamos losmails de nuestra verdadero servidor por fetchmail. Por algún motivo se me escapó en el merge de la configuración del postfix la parte que dice que use MailDir en el home del usuario, por lo que estuve renegando otro tanto. ssh también fallaba, pero era porque se me había escapado un PasswordAuthentication no.

El último paso de la noche era (re)configurar el Apache para que anduvieran los repos svn vía DAV que autenticaban contra el LDAP. Al día siguiente vendría la parte de reactivar otros servicios del Apache. No hubo que renegar mucho, sólo cambiaron la forma en que le decía que autentique contra LDAP y agregarle una z a AuthzLDAPAuthoritative:

# AuthLDAPEnabled On
AuthBasicProvider ldap
AuthzLDAPAuthoritative on

13 horas después de iniciar mi día laboral (3 de la matina) me retiré tambaleando a mi casa.

sysadmin ldap debian sarge etch pam apache svn

Posted Sat 05 Jul 2008 01:29:16 AM CEST Tags: debian

¡Sí señores, voy a DebConf8! MDQ, del 9 al 17.

debian

Posted Sat 05 Jul 2008 01:29:16 AM CEST Tags: debian

El segundo día me amaneció a las 13. Hoy tocaba terminar con el Apache, que incuía apenas los tracs y el dotproject. Ambos implicaban upgrades.

Los trac no me hicieron renegar mucho, pues está muy bien documentado y hasta fue scripteable. Básicamente era un salto de sqlite2 a sqlite3, un trac-admin ... upgrade seguido de un trac-admin ... resync.

Con lo único con lo que renegué fue que a pesar del upgrade fue exitoso no podía entrar. En los logs encontraba esto:

(9)Bad file descriptor: Could not open password file: (null)

Google al rescate me dijo que había que apagar esa directiva que había tenido que modificar el día anterior:

AuthzLDAPAuthoritative off

También me salió esto:

Failed to load the AuthzSVNAccessFile: The character 'o' in rule '@except' is not allowed in authz rules

Eso era porque en un archivo de configuración del repo (conf.svnaccess) tenía los permisos de sólo lectura como ro en vez de r.

El dotproject me enfrentó a un viejo archienemigo: mysql. La verdad que no se a queinacarajos se le ocurre que es una excelente idea poner la configuración de acceso y permisos de una base de datos dentro de la base misma. Por un lado eso termina siendo un archivo binario no versionable y por otro obliga al sysadmin a aprender SQL (cosa que sé, pero no manejo fluidamente ni me interesa saberlo; otro de los motivos por los que amo los ORM's). Y además esta configuración termina en /var y no en etc. postgresql, en cambio, es mucho más inteligente. Y viva el SQL independiente del motor. Lástima nadie lo usa...

Bien, sólo tuve que hacer un dump del mysql anterior (chroot mediante), crear la base en el nuevo y hacer un load. Fantástico. Luego una lucha trabado con el sistema de permisos antesmencionado. Luego apuntar un browser a https://server/dotproject/install. En ese minisitio tuve primero que configurarlo (como DP no es un paquete en Debian, lo instalé de fuentes; la configuración queda en un archivo en include/config.php; ojo que las otras opciones es nukear las bases), luego volver a entrar a dicha URL, momento en el cual detecta las bases viejas y da la opción de upgradearlas. Anduvo sin problemas y ahora disfrutamos de un DP más nuevo. Yeepee!

sysadmin debian sarge etch apache trac svn mysql dotproject

Posted Sat 05 Jul 2008 01:29:16 AM CEST Tags: debian

ayer le ofrecí hosting para sus proyectos a humitos. el iluso cayó rápido, sobre todo después de que probó cómo anda svn desde su casa bajando las fuentes de kreissy.

para ofrecerle este servicio le creé una cuenta en mi máquina y lo dejé hacer lo que le parezca, como ya he hecho con otra gente (por ejemplo, mi máquina es un ssh gateway paara alguna gente que se queda detrás del firewaal de la facu, pues tiene corriendo el ssh en el 443, que si está abierto).

como mi máquina es un debian sid, y éste suele sacudir los paquetes de vez en cuando (ya con el desarrollo de kreissy me mordió el cambio de SQLAlchemy, saltando de la 0.3.x a la 0.4.x, que tienen APIs sutilmente incompatibles), se me ocurrió levantar una instancia xen que ya tenía tirada por ahí. les cuento.

hace poco más de un mes nueces trajo su desktop que estaba juntando en un rincón de su pieza y, poniendo uno de los dos discos que tengo, pusimos un debian unstable, al cual convertimos en el dom0 de un xen que corrió dos instancias xen, una para él y otra para mí. la mía corría un debian etch directamente de mi disco, por las dudas en algún momento él se tuviera que llevar la máquina.

y ese momento llegó hace una semana: la vendió. me devolvió mi disco, que terminó de nuevo en mi máquina. lo monté como lo ten;ia antes y todos contentos.

entonces, hoy instalé un kernel xen. como esto es un debian sis, y no hay kernels con xen más arriba del 2.6.18, y sid ya corre 2.6.22 (para cuándo el .23?!?), tuve que bajar los paquetes linux-image-2.6.18-5-xen-6862.6.18.dfsg.1-13i386.deb y linux-modules-2.6.18-5-xen-6862.6.18.dfsg.1-13i386.deb a mano e instalarlos a mano. para instalarlos usé dpkg a lo macho, pero bien podría haber usado gdebi. configuré grub un poco a mano y reinicié.

hace mucho que uso debian, y desde hace mucho que uso kelmers compilados específicamente para mi hw (he notado que en máquinas chicas eso aumenta bastante la velocidad, así porqué no aplicar un poco la filosofía gentoo en este caso?). el tema es que estuve un rato reconfigurando algunas cosas para que anden con cómo levantó el kernel genérico algunas cosas (red y soporte de IDE en vez de PATA). sé que esas cosas se pueden arreglar con udev, pero la verdad es que siempre me llevé medio mal con él y ahora no tenía tiempo de revisarlo.

cuestión que después de un par de toqueteos levantó sin más problemas. me restregué las manos, creé el archivo de configuración de la instancia xen, y disparé un xm create. para asegurarme que estaba todo bien, con xm console luxury me ataché a la consola del domU. ésta felizmente me mostró cómo arrancó todo el sistema hasta que llegó el momento de correr /sbin/init. entonces es cuando no hizo más que imprimir:

request_module: runaway loop modprobe binfmt-464c

y nada más. buscando encontré referencias que no entendía, hasta que me cayó la ficha: la máquina de nueces era una amd64, y la instancia xen estaba en esa arquitectura. acá tengo un athlon xp 2600+, que es i386. el loco se negaba a correr soft compilado para 64 bits.

en fin. humitos empezó a subir sus cosas a su home en el dom0. ya después veré si migro eso a una máquina aparte o no. también estuvimos jugando con svk y svnadmin.

xen debian sysadmin

Posted Sat 05 Jul 2008 01:29:16 AM CEST Tags: debian

Yo sabía que tener un serven en Debian Sid es una lotería, pero como no me anduvo volver a poner a andar mi instancia Xen con Debian Etch, bueno, acá estamos.

Cuestión que hoy hice una actualización de los paquetes, cosas que hago una vez por semana, y resulta que ahora mis tracs no andan. Revisando los logs de Apache veo backtraces que terminan en:

ValueError: database parameter must be string or APSW Connection object

Buscando encontré que es un bug en Debian. Ahora, resulta que estoy usando apt-listbugs, que te muestra los bugs reportados de los paquetes que van a ser instalados/actualizados antes de que lo sean, de forma que puedas decidir si lo querés hacer o no. Recuerdo haber visto el bug en la lista e ignorarlo, cosa que fue mi perdición.

Según la lista trac-users, una forma de soplucionarlo es volver a la versión anterior de python-pysqlite2. ¿Y cuál era la versión anterior? Bueno, eso lo puede responder el log de la actualización, /var/log/apt/term.log:

Preparing to replace python-pysqlite2 2.3.5-1 (using .../python-pysqlite2\_2.4.0-1\_i386.deb) ...

Fantástico. Por suerte justo esa versión fué migrada a Lenny hace poco; sino, habría que haber buscado un mirror que no actualizara muy seguido. Además, parece que el bug ya está reparado por la nueva versión del paquete. Así que simplemente me bajé la 2.4.0-2 y la instalé con dpkg -i. ¡Listo!

¿Listo? I wish. El trac que estaba revisando quedó sin css y otras cosas. De los logs de Apache:

GET /~mdione/projects/kreissy/chrome/common/css/trac.css HTTP/1.1" 500

Internal Server Error. Now what? ¡Seguimos en la misma!:

ValueError: database parameter must be string or APSW Connection object, referer: http://grulicueva.homelinux.net/~mdione/projects/kreissy/

Ok, tons vamos patrás. Instalo 2.3.5-1 y... ¡tampoco! Same shit... ¿No me olvido de algo? ¡Sí, de reiniciar Apache! Reinicio, y allí está mi querido trac, vivito y coleando.


PD: Ustedes tal vez se preguntarán "¿Este pibe piensa globear todo lo que le pase en Sid?". La respuesta es: espero que no. Only time will tell. Supongo que será hasta que descubra qué está bueno y qué no.

sysadmin debian

Posted Sat 05 Jul 2008 01:29:16 AM CEST Tags: debian

Como dijo Marga hace más de un mes, hubo que hacer una nueva versión del paquete tzdata para que tome el cambio de horario de Argentina por el supuesto ahorro de energía. Una cosa que no aclaró Marga es que ese paquete sirve para sarge también, aunque sea una versión para etch.

Como no me animo a poner en un sarge el volatile de un etch, decidí instalar el paquete a mano. Lo bajé de volatile y lo instalé con dpkg -i:

# dpkg -i tzdata_2007j-1etch2_all.deb
Selecting previously deselected package tzdata.
(Reading database ... 51812 files and directories currently installed.)
Unpacking tzdata (from tzdata_2007j-1etch2_all.deb) ...
Replacing files in old package libc6 ...
Setting up tzdata (2007j-1etch2) ...
Current default timezone: 'America/Cordoba'.
Local time is now:      Tue Jan 29 14:55:02 ARST 2008.
Universal Time is now:  Tue Jan 29 16:55:02 UTC 2008.
Run 'tzconfig' if you wish to change it.

Como diría Anibal, "me encanta cuando un plan funciona".

sysadmin debian

Posted Sat 05 Jul 2008 01:29:16 AM CEST Tags: debian