domingo, 7 de diciembre de 2014

Instalar y actualizar ack-grep en ubuntu (dpkg-divert)

Hace poco actualicé Ubuntu a la versión 14.10 en mi laptop y traté de actualizar ack-grep pero este proceso siempre fallaba con el siguiente error:

package ack-grep 2.12-1 failed to install/upgrade: trying to overwrite 
`/usr/bin/ack', which is the diverted version of `/usr/bin/ack-grep'


Después de investigar un poco recordé la guía oficial de instalación de ack-grep recomienda renombrar el paquete posterior a su instalación para que sea posible llamar dicho programa simplemente escribiendo ack en lugar de ack-grep, lo que la guía no dice es que esto causará problemas al tratar de actualizar el paquete, al menos es lo que me pasó después de actualizar Ubuntu.

Instalar ack (guía oficial)

Esta es la forma recomendada de instalar ack-grep en Ubuntu (http://beyondgrep.com/install/):

Primero necesitamos instalar el paquete:

sudo apt-get install ack-grep 


Y luego, por conveniencia, renombramos el paquete instalado:

sudo dpkg-divert --local --divert /usr/bin/ack --rename --add /usr/bin/ack-grep 


Este comando causa que el paquete sea renombrado localmente y si se ejecuta sin problemas están listos para usar ack

Acerca de dkpg-divert


dpkg-divert crea una "desviación", en este caso local, que cambia el nombre de ack-grep por ack, si ejecutan el siguiente comando:

dpkg-divert --list |grep ack


verán algo como lo siguiente:

desviación local de /usr/bin/ack-grep a /usr/bin/ack


si quieren eliminar dicha desviación puede usar:

sudo dpkg-divert --remove /usr/bin/ack-grep


y deberían ver el siguiente resultado si todo sale bien:

Eliminando `desviación local de /usr/bin/ack-grep a /usr/bin/ack'


Instalar ack (mi recomendación)

El principal problema con la guía oficial es que no dice nada sobre remover la desviación y los posibles problemas que puedes encontrar, y lo cierto es que prefiero usar "ack" antes que "ack-grep" así que usaré un alias.

La instalación ack-grep es igual:

sudo apt-get install ack-grep 


Ahora vamos a crear un alias y para esto editamos el archivo de configuración de nuestra consola de comandos, por defecto en Ubuntu sería ~/.bashrc

nano ~/.bashrc


y añadimos un línea como la siguiente al final:

alias ack='ack-grep'


Para que el cambio sea visible hay que recargar la terminal, lo cual vuelve a leer el archivo ~/.bashrc, por lo general lo más simple sería cerrar la ventana del emulador de terminal o podemos ejecutar:

exec $SHELL


Y luego debemos poder ejecutar ack de forma normal.


Conclusión

Aunque la guía oficial ofrece una forma simple de hacer que el comando ack esté disponible para todos, crear una desviación local puede causar problemas y a menos que sepamos la forma de usar dpkg-divert podríamos terminar con un paquete roto en nuestro sistema.
Mi solución tiene la ventaja de que no afecta futuras actualizaciones y aunque el ejemplo solo afecta la cuenta de un usuario, solo haría falta actualizar el archivo /etc/bash.bashrc (o el equivalente para el shell que esten usando) para hacer este alias accesible a todos los usuarios; cabe resaltar que para mi solución ack está disponible para todos los usuarios si invocan al comando ack-grep sin necesidad de crear un alias.

lunes, 15 de septiembre de 2014

evironment specific wordpress configuration

Everyone who has ever setup Wordpress knows the wp - config.php file and all settings that you can define there, this works fine to configure your wordpress instalation on any given environment but there are times when we have to work on different environments or stages as your applications is developed, tested and installed on production.

I have worked on companies that have one local environment per developer, then one for QA(quality assurance), another for staging and finally other one for production, in some cases there is a development environment where all development code is merged so developers can test their changes with what others have done, there is not a right answer here but one thing is for sure you don 't have the same settings on each of those environments and you don' t want to, here are some reason why that is the case :

  1. your local working copy: you want to be able to do just anything and you don 't care about database access rights so is usual to setup for example mysql root account without password.
  2. staging environment: you want to configure your database and the settings of your application to be as close as production as possible but this environment is accessible to a lot of people like: QA, software architects,  system administrators and perhaps even developers so you want to keep things simple and share easy to remember passwords with those who need them.
  3. production: this is the place that you want to keep protected, very specific user access rights, security policies, strong passwords, and so on. Maybe only certain sys admins whose are trust worthy can access here and see the application event log and change/install/update any required software.

With all of that being said here a simple example of a possible configuration of database users and privileges using MySQL 5.5.x, see here for a complete list of all supported Privileges and how to grant them.





environment user name permissions
local root ALL
staging root ALL
staging qa CREATE, DROP, SELECT, INSERT, UPDATE, DELETE
production root ALL
production app_user SELECT, INSERT, UPDATE, DELETE


Now let's say that you want to use root on your local without password, on staging you want to configure qa and use app_user for production.

Here is an example of your wp-config.php file for production, is very likely that you will just provide an example with place holders, then a sys admin will replace with actual values and deploy the final file to production environment.


Now the questions is: how do we allow different settings on staging and local environments? some people will just edit the config file to adjust it for every environment however this is very dangerous because you could end up overwriting one or more of those files and if you do override production your site will not work.

My suggestion/solution
inspired on this wordpress plugin I got the idea of defining an stage constant and then use that constant to load an environment specific configs file, another way could be just checking if an environment specific file existed but I think using a constant is better.

So we need to update our wp-config.php file making sure that it contains the WP_STAGE constant and that this is used to load the right configs file, here is how it looks like:


And this is how the wp-config-local.php looks like:

As you can see if you define some value for WP_STAGE constant and you create a file named like: wp-config-{WP_STAGE}.php the original (production settings in this case) will be ignored and your stage specific settings are loaded instead.

You may use local settings as default and create an specific version for production and staging. In my example I am loading and external file OR what is defined on wp-config.php so If something is required in many environments I will have to redefine it as many times as it is required, you could "move" this common setting to wp-config.php outside of the if block. In the worst case scenario if by accident you upload any of your environment/stage specific configs to production it will not be used unless your WP_STAGE constant is also changed and your production files are not going to get overwritten.

martes, 15 de abril de 2014

My first ubuntu indicator

I was reading about Unity indicators and how to create one here and here and decided that I will give it a try, but and indicator of what? it must be something useful but not too complicated to implement because I want to keep things simple so I ended up create a touch pad indicator that will allow me to turn on and off the mouse pad of my laptop.

If you need to disable your touch pad of any reason take a look at this post

Requirements

Make sure that you have the package python-appindicator installed, you can install it using this command:
sudo aptitude install python-appindicator

We will also use pygtk and pynotify libraries.

The source code

My source is divided in two main sections the indicator menu items and the event handlers all defined inside one single class called TouchPadIndicator. You can find this indicator source code here: https://bitbucket.org/emont01/py-touchpad-indicator
The touch pad indicator constructor (__init__) is responsible for creating an appindicator.Indicator instance and setup the menu. This constructor also setup the indicator icon, I was not able to find a list of all possible icons but in some forums I found references to the Gtk Stock and to the folder /usr/share/icons/CURRENT_THEME where CURRENT_THEME is the name of theme actually in use, listing files on some folders under /usr/share/icons allows me to find this file name gpm-mouse-060.svg so figured that using "gpm-mouse-060" should work and it did at least in my computer, so if you can't see the indicator logo you can check that.
Setup the indicator menu is quite simple, you need to:
  • Create a gtk.MenuItem instance
  • Bind your instance to the correct event handler
  • Show the menu (make it visible), and
  • Add the menu item to the main menu
My indicator have two options, namely: "Quit" and  "Toogle touch pad".
Quit just call to sys.exit to terminate the execution
Toogle touch pad is the interesting part it uses a class called TouchPadDevice to detect the current touch pad status and also calls the notify function to show a nice information message.
The part that deals with the device status is inspired by this ask ubuntu answer

martes, 25 de marzo de 2014

Instalando ubuntu en una HP Envy 15-j003la

Recientemente tuve la oportunidad de instalar Ubuntu en una HP Envy 15-j003la (especificaciones) en lo personal me gustaron mucho esos 12GB de memoria DDR3, el procesador Intel Core i7-4700MQ y la tarjeta de vídeo NVIDIA GeForce GT 740M... :-D

La verdad lo único malo que le pude ver es el SO que trae pre-instalado, el sistema operativo MS Win8 no me gusta pero para nada, así que me di a la tarea de instalar Ubuntu 14.10 ¡con el permiso del propietario claro!.

Todo este asunto me trajo recuerdos por que me tocó bajar la iso más reciente de Ubuntu, lo cual no hacía desde hace rato porque acostumbro actualizar el SO directamente; bueno suficiente charla empecemos con esto.

Primero lo primero
Hay que descargar la versión más reciente de Ubuntu al momento de redactar este post es la 13.10 Saucy Salamander
Ya que el procesador mencionado (i7-4700MQ) es de 64bits descargué: 64-bit PC (AMD64) desktop image

Mientras esperaba vi algunos capítulos de una serie...

Una vez terminó la descarga usé UNetBootin para crear un USB booteable, la mayoría de las portátiles modernas soportan arrancar desde un USB pero en este caso en particular es la única opción ya que la laptop no trae lector de CD/DVD/Blueray.

Use una utilidad llamada Disk2vhd  para hacer una imagen de la instalación actual, solo en caso de haga falta y esperando que funcione en una maquina virtual, pero eso es material para otro post.

La instalación
Todo parecía ir bien luego de que encontré la forma de seleccionar desde cual dispositivo deseaba arrancar la laptop, pero cualquier opción que seleccionaba me daba una pantalla negra sin texto, imágenes o errores así que supuse que alguna cosa no estaba cargando correctamente y leyendo algunas preguntas sobre modelos similares me dió la idea de que podría ser el acpi así que usé esta guía para apagar el acpi y pude iniciar ubuntu desde la USB y empezar a probar, el tema del acpi lo revisaré luego con calma.

En las configuraciones de sonido verifiqué que el microfono y las bocinas funcionaban bien, habilité los repositorios "universe" para installar cheese y probar la webcam... ¡todo bien!

Inicié la instalación y seleccioné que se instalaran los paquetes de terceros, ya saben para poder reproducir formatos como mp3.

Como ya se había intentado antes instalar ubuntu en la mencionada laptop las opciones del instalador fueron algo así como "reinstalar ubuntu", "borrar ubuntu" e "instalar al lado de la instalación anterior", me parecía que había una de usar todo el disco pero no salió entre las opciones así que opté por borrar manualmente, no puedo negar que sentí cierta satisfacción al eliminar todo rastro del anterior SO para hacer espacio para Ubuntu aunque luego el instalador esperaba que configurar manualmente el swap, la carpeta home y todo lo demás así que cancelé la instalación abrí gparted y borré todo el disco :D

Reinicié la instalación y esta vez si estaba la opción de usar todo el disco :D.

El resto es la usual selección de la zona horario, el teclado, el primer usuario y su contraseña.

Primer inicio de sesión
Después de esperar a que la instalación terminara reinicié la computadora y todo funcionó a la perfección.

Acerca del audio:
Varias peronas han comentado sobre los parlantes/bocinas y que solo funcionan parcialmente, lo cual he podido comprobar, y además encontré esto en linux.org.
En esencia el artículo dice que:
  • la compañía "Beats Electronics LLC" fabricante de los parlantes no ha provisto de los drivers necesarios para que dicho hardware funcione en GNU/Linux
  • existe una herramienta llamada HDA-jack-retask, que podemos usar para reasignar los pines de audio en la tarjeta madre y así lograr que ALSA los reconozca.
Esto es interesante y estoy seguro que es tema para un artículo relacionado, no puedo prometer nada pero intentaré escribir sobre el asunto en los próximos días.

Referencias:
[1] Especifications de la HP Envy 15-j003la

Actualizaciones:
5-Dic-2014: El número de la versión de ubuntu estaba mal escrito, decía 14.10 Saucy Salamander y debía decir 13.10 Saucy Salamander ¡ups!
2-Feb-2015: Nota acerca de Beats Audio y HDA-jack-retask 22-Ago-2015: Tomé una captura de pantalla de las especificaciones ya que la URL cambió.