Report inadequate content

non-RDBM distributed databases, map/reduce, key/value and cloud computing

I've been playing recently with several distributed databases with the aim of choosing the best solution for my needs. Since there isn't much documentation on the web with a general overview on the subject, I write here some comments, thoughts and my humble experience. Hope it's usefull for you, this document is not a comparison of performance, or a "mine is bigger than yours",  just some ideas ;)

My background
Being my experience based on relational databases (like MySQL or Postgres) and Object oriented databases (like ZODB) it was very easy for me to get hooked on this new challenge, anything but the relational databases (no offense). Last year, in Mainz, Germany, and after having heard a lot of buzz on the subject, Jan Lehnardt gave an interesting lecture on CouchDB. (BTW, thanks Jan for all the questions you answered to me). That event was the firestarter and since that I've been trying things... So I am a newbie in this expert area.

Now, I am working on a project that performs WRITES on very large set of data. All this data doesn't need to be in a relational database since it's a simple collector of activity, flat and with a variant structure that writes some gigabytes every day that must be processed at night, under different criteria.

To store this, I started doing some research on what I could use to store that data, and here are some of the things I tried. The principles were:

  1. Horizontally scalable
  2. Able to handle and process a lot of non-trivial data
  3. Able to write at least 1000 reqs/s, non-bulk
  4. Open source

(I still have a decision to make)

Tokyo Cabinet + Tokyo Tyrant (key/value)

Tokyo Cabinet is library of routines for managaing a database that in conjunction with Tokyo Tyrant, the network interface, create an excellent network database. Tokyo supports up to 8 Exabytes of data and it's really fast both in write and in read. Currently is used in the Japan's Mixi Social Network (more than 14 billion page views monthly). It's a key/value database.

From the sysadmin point of view was a lovely product, easy to install, start, manage, backup or replicate. It's everything as easy as they state in the website, and it works. If you, like me, are a Memcached lover, Tokyo is completely compatible with the memcached protocol, allowing you to do delights as "persistent but volatile data" . You can run the database in memory-only or with persistence (If you want in-memory, I think memcached is slightly faster for that purpose, but it's just my impression on few tests, do yours or Google it).

To start a master-slave system is as easy as (you might want only a master, or several slaves):

Start the Master: ttserver -port 1978 -sid 1 casket-1.tch

Start the Slave: ttserver -port 1979 -sid 2 -mhost localhost -mport 1978 -rts 2.rts casket-2.tch

Where casket are the databases and the extensions define what algorythm you want to use. Easy as hell. Just be aware to set a different and unique identifier (sid) for every server and say the slaves who is the master host (mhost). That would run a master and a slave on the same machine on ports 1978 and 1979.

Ok, that was really exciting for me but I found that despite Tokyo is wonderful and everything, as in memcached, you need to know the KEY of the element you want to retrieve (yeah, that's what a key/value is supposed to do). In my case, I need to map/reduce the vast amount of data, so Tokyo is not an option for me, but might be what you've been looking for. I'll use it for any other project, sure.

The weak points I found where that when used through the HTTP wrapper the performance goes down significantly. For instance, I had much better results using curl POSTs with CouchDB on a single node. Oh, and I hope you speak Japanese, you won't find much documentation in English ;)

Basic example on how to write data in Tokyo using the HTTP wrapper:

curl -s -X PUT -d "my_value" "http://127.0.0.1:1978/my_key"

But the fastest way is using the C binaries:

tcrmgr put -port 1978 127.0.0.1 "my_key" "my_value"

You can list the contents using:

tcrmgr list -port 1978 localhost

Here I link a presentation so you can see the whole pictureTokyo Cabinet and Tokyo Tyrant Presentation

CouchDB (document oriented database)

CouchDB is a schema-free document oriented database. A wonderful project of Apache with more community than the others behind it. CouchDB works using a RESTful HTTP/JSON API meaning that with simple HTML and JS you can create a dynamic website. Of course you can use other wrappers like PHPillow if you want to use PHP.

The default query language of the database is Javascript. You write map/reduce functions that are stored as views to get only the content of your interest, your docs are fully indexable, and although you might be pretty used to SQL do give CouchDB a chance.

Amongst all the systems is the one I like more as a product, although is not having a daemon for managing the service (tried the 0.9 from checkout) it is very easy to install and run.

Some things I really like:

  1. No language scripting needed
  2. The replication is bi-directional, peer-based
  3. Leave your nodes offline for a while, reconnect them and nothing happened.
  4. The Futon interface. Some sort of, let's say, phpMyAdmin where you can play and test your views

A basic sample of insertion using curl:

curl -s -X POST 'http://localhost:5984/mynewdb/' -H "Content-Type: application/json" -d '{ "my_key": "my_value" }'

If you want to insert a lot of documents you should insert documents in bulk mode. It's faster and your database will be more compact. Do not perform this test over a million iterations or your space disk will grow a lot.

What is CouchDB

MongoDB (document-oriented)

MongoDB is like CouchDB, another document-oriented database. This project was born this year 2009, so it's very young. With a colleague we tried to install the server and run it with the PHP libraries under CentOS, but it was completelly impossible.

Despite all, I'll keep an eye on it, very interesting as well, because:

  1. You can filter data by fields without knowing the keys (as couchDb)
  2. You can create indexes to accelerate the data filtering
  3. Sexy functionalities to operate with the database
  4. Internal drivers ready for C, Ruby or Python. A PHP module available.
  5. Without much learning curve
  6. Replication, failover and auto-sharding coming soon.

Project Voldemort (key/value)

Behind this curious name from Harry Potter there is an interesting Java distributed key-value system database. Project Voldemort handles replication and partitioning automatically, every server contains only a subset of the data and if a node fails your data integrity is not compromised, nor there is a central point for coordination. The balancer read from any node but writes in all them at the time, that can reduce your writing experience. This system is used in some parts of the well-known LinkedIn with 12TB of data. But I am not a big fan of Java, so I played a little bit, and after going nuts running the examples and installing the Ecplise stuff,  i tried something else, not for me :$  (Not a lover of Tomcat either)

Again, another key/value. Doesn't fit me at this moment.

Hbase (column-oriented)

Hbase is a Key/value Hadoop project. I am using it right now with the HTTP interface and it's very fast on writing (the quicker for my tests). If you want to serve your website content from this database, you better skip this one, the latency is high. I jumped from here to cloudera.

Some basics:

Create a table in Hbase:

 

curl -H "Content-Type: text/xml" -H "Accept: text/xml" -v -X POST -T - http://ip.to.hbase:60050/api/

Then paste something like this and press Ctrl+D twice after:

 

<?xml version="1.0" encoding="UTF-8"?>
<table>
<name>table1</name>
<columnfamilies>
<columnfamily>
<name>col1</name>
<max-versions>2</max-versions>
<compression>NONE</compression>
<in-memory>false</in-memory>
<block-cache>true</block-cache>
</columnfamily>
<columnfamily>
<name>col2</name>
<max-versions>2</max-versions>
<compression>NONE</compression>
<in-memory>false</in-memory>
<block-cache>true</block-cache>
</columnfamily>
</columnfamilies>
</table>

After version 0.19 the JSON notation will be supported, so you will be able to do things like:

curl -H "Content-Type: application/json" -H "Accept: application/json" -v -X POST -T - http://ip.to.hbase:60050/api/

{"name":"test5", "column_families":[{ "name":"columnfam1", "bloomfilter":true, "time_to_live":10, "in_memory":false, "max_versions":2, "compression":"", "max_value_length":50, "block_cache_enabled":true } ]}

 

 

Show tables in Hbase:
Any of these:

curl -v http://ip.to.hbase:60050/api/
curl -v -H "Accept: text/xml" -X GET http://ip.to.hbase:60050/api/

And to see the metadata of a table:

curl http://ip.to.hbase:60050/api/table1

 

Insert a row

 

curl -v -T row_contents.xml http://172.20.4.42:60050/api/table1/row/

 

... where row_contents.xml has something similar to the XML code pasted above.

Other commands...

Disable/enable a table:

curl -v -X POST http://ip.to.hbase:60050/api/restest/disable
curl -v -X POST http://ip.to.hbase:60050/api/restest/enable

PUT:

curl -v -T y.row http://ip.to.hbase:60050/api/table1/row/y?column=a

GET:

curl -v  http://ip.to.hbase:60050/api/table1/row/y    

SCAN

curl -v -T ./y.row http://ip.to.hbase:60050/api/table1/scanner?column=a:
curl -v -T ./y.row http://ip.to.hbase:60050/api/table1/scanner?column=a:
# That returns an ID, like b959591, retrieve it:
curl -v -T ./y.row http://ip.to.hbase:60050/api/table1/scanner/b959591

Cloudera (hadoop cluster)

Cloudera is a company that offers an Apache-licensed packed solution based on the Hadoop family. If you are interested in cloud computing and you have been after projects like the Yahoo!'s Pig or the Facebook's Hive,  then you'll like to know that Cloudera brings to the 'mere mortals' all that power in an easy RPM.

Cloudera combines the Hadoop cluster and filesystem HDFS with Hive and all the pain that is configure a Hadoop cluster. You will be able to summarie, analyze and query an ingent amount of data. Have a look at the latest video of training sessions to get an idea on how the Hive query language similar to SQL looks like. You can even download an VMWare virtual machine with the solution running.

I am recently looking at this, it's a lot more complex than any of the other solutions, but since I'll need to store and process several Gigabytes every day, this seems the way to go...  :_/ sniff...

If you are interested in this, you can also have a running Hadoop via Amazon Elastic MapReduce, billing is hourly and by machine.

More interesting projects:

The folling project aren't less interesting, nor I hadn't time to fully test, but for my current needs aren't suitable,  they are worth a mention anyway:

  • Disco Project: Another map/reduce framework started at Nokia. Uses python and quite simple.
  • LightCloud: Distributed key-value database using the Tokyo Tyrant network interface (Plurk open source)
  • Cassandra: Another Facebook project based on Google's BigTable
  • Hypertable: Also based on BigTable, a distributed storage system using a query language. It's not supporting load balancing as far as I am concerned.
  • Scalaris: An interesting key-value store allowing range queries, but it doesn't support persistence yet.
  • Redis: Not just another key/value. Has a lot of libraries for PHP, Python, Ruby, Lua, Perl... If the numbers are true it's fast as hell! A complete protocol to interact.
  • MemcacheDB: Memcache made persistent (key/value of course)

These are only a few ideas that may help to you. Hope it helped :)

{
}

Cómo reproducir ficheros .RMVB en Ubuntu

Los ficheros .rmvb no se pueden reproducir por defecto en Ubuntu, esta extensión es para los de tipo RealMedia Variable Bitrate, pero instalando los códecs de Mplayer los podrás abrir sin problemas.

Lo primero que debes instalar, aunque no sea intuitivo es la librería libstdc++5, para hacerlo o bien abre Synaptic ( Sistema -> Administración -> Gestor de Paquetes )  y haz doble click sobre libstdc++5 o ejecuta en la terminal:

sudo apt-get install libstdc++5

Si ya tienes Mplayer instalado con los códecs prueba ya a ver si se pueden reproducir los ficheros. Si no, lo siguiente será instalar Mplayer,  a través otra vez de Synaptic o de la terminal

sudo apt-get install mplayer

Luego para instalar los códecs, bájatelos de la página Mplayer Binary Codec Packages (si no sabes cuál elegir lo más probable es que necesites el que se llama Linux x86). Descomprime la carpeta que te has bajado en el escritorio y abre la Terminal, ejecuta los siguientes comandos:

cd Escritorio  ( en función del idioma de tu Ubuntu puede cambiar)
cd essential-20071007
sudo mkdir -p /usr/lib/codecs
sudo cp * /usr/lib/codecs

A partir de este punto ya sólo te queda configurar Mplayer, para ello entra en las Preferencias y en la pestaña Codecs & Demuxer selecciona de los deplegables:

  • Video codec: RealVideo decoder
  • Audio codec: FFmpeg

y ya deberías poder reproducir los ficheros .rmvb en Ubuntu. Si te suceden cosas extrañas, como ver la imagen pequeña, no oír el Audio, o ver la imagen que da saltos, tendrás que hacer modificaciones en la configuración de Mplayer, como por ejemplo desactivar opciones tipo "Enable double buffering", "direct rendering", etc...

Mplayer CodecsMplayer prefs video

SVN merge for Mac OS X

If you want to merge branches in your projects using a Mac OS X, you'll probably miss how straightforward is to do that with the TortoiseSVN client.

Mac has many SVN-fashioned clients where you can fall in love when you see the GUI, but when it comes to do a merge it seems that all they have forgotten to include support for it. I haven't seen any free or comercial application for Mac that integrates all the subversion commands in the same tool without pain. You need always a couple of tools and sometimes use the terminal commands (I do this the most in Mac).

Returning to the specific svn command merge, here are the only tools that you can use to accomplish that task:

Subcommander:

Graphical subversion client with diff and merge tool. http://subcommander.tigris.org/

DiffMerge

Multiplatform utility for merging and comparing: http://www.sourcegear.com/diffmerge/ (not SVN specific)

Guiffy:

Guiffy is a normal diff/merge application, you don't need to use Subversion, but it comes with support for CVS/SVN. http://www.guiffy.com/

And that's all. I've spent many hours looking for more apps, but I haven't found any helping me with the merge integrated with SVN. If you find anything let me know and I'll add it to the list.

UPDATE (Added SmartSVN)

SmartSVN (commercial)

SmartSVN is the most complete solution for Mac I've seen. It runs on Windows and Linux as well. Although it is not a Cocoa application and doesn't accept things like drag and drop it does everything you might need, and speaking about merge:

  • Merge
  • Merge from 2 sources
  • Reintegrate branches

The application allows to create several projects, browse them (very clean and neat), see the logs inside the context, see diffs, resolve conflicts, tags, branches, logs, filters... everything!!!

I don't understand how this application isn't more popular, since is the missing app for advanced mac developers and works on any platform.

If you find anything interesting please let me know and I'll add it in the list.

"ipconfig /flushdns" para Mac OS X

Desde el lanzamiento de Mac OS X Leopard (de esto ya hace unos cuantos días) que ya no funciona el comando lookupd -flushcache que utilizábamos para invalidar la caché de DNS de Mac.

Este comando, que era el equivalente mac de ipconfig /flushdns de Windows ahora se ejecuta usando:

dscacheutil -flushcache

Lo dejo aquí anotado porqué soy flojo de memoria para este tipo de cosas :)

{
}

Spotify, escuchar música online. Competencia de Last.fm

SpotifyLlevo unos días probando Spotify, gracias a una cuenta beta gratuita que me dió mi compañero de trabajo Rufino . Para quienes no hayan oído hablar de Spotify es un reproductor de música en streaming (es decir, la música no está en tu ordenador, sino en sus servidores). Hay que bajarse el programa, que de momento está disponible sólo para Mac y Windows (Linux a través de Wine).

La aplicación promete mucho (no he probado la de pago), pero lo que se se puede hacer con la versión gratuita incita a usar el programa en su forma completa.

Qué puedes hacer con Spotify (versión gratuita)?

  • Buscar por cualquier criterio de texto que se te ocurra. Algunos ejemplos de música que busqué (hay una gran oferta y muy variada) son: Amy McDonald, De-Phazz, Rage against the machine, Mates of State, Mr. Bungle o The Mars Volta e incluso encontre muchos resultados para Estopa, Camela o El Fary... así que música hay  ;-)
  • Poner en la cola música mientras vas navegando por la interfaz web que tiene.
  • Escuchar lo que llaman radio, donde puedes elegir los estilos de música que te gustan y las décads que te interesen y se crea una lista de reproducción con tu elección.
  • Crear listas de reproducción, que luego estarán disponibles desde cualquier ordenador que uses con tu cuenta.
  • Rebobinar una pista! Algo que desde luego nunca se pudo hacer con Last.fm, así como volver a una canción anterior, o saltar a la siguiente.
  • Escuchar en modo aleatorio o repetición
  • Navegar por las biografía de los artistas.
  • Escuchar la "Artist radio", como en Last.fm
  • Arrastrar a las playlists los elementos que van apareciendo en pantalla
  • Ver las portadas de los discos que escuchas.

Para los que sean muy exigentes con la calidad del audio, pues simplemente les digo que sigan escuchando su música desde el disco duro. Aunque he leído en un thread de GetSatisfaction que uno de sus empleados decía que el streaming se hacía en formato OGG de bitrate 160kbps yo no me lo creo. Almenos en la versión gratis.

Utiliza tu cuenta en varios lugares...

En cuanto utilizas tu cuenta en diferentes lugares, las playlist que vas creando, están disponibles en todos los ordenadores, y solamente cambian las búsquedas que has hecho, que solo se guardan de forma local. Lo que no se puede hacer es acceder con una misma cuenta simultáneamente desde dos lugares (esto será una fiesta):

193785-119422.jpg

Limitaciones:

En la versión gratuita cuando has escuchado muchas canciones aparece un hombre con voz de ultratumba, que te invita a pasarte a la versión de pago, y luego continua la música. Personalmente lo encuentro muy molesto, ya que en la propia aplicación ya aparecen banners y mensajes para que te pases a la de pago...

También he visto que alguna canción está baneada y no se puede escuchar en España. No sé a que se debe, pero estoy seguro que los señores de la SGAE ya se están frotando las manos... vamos, si se las frotan cuando hay música en un boda...

Competencia de Last.fm?

Fijo. Pero yo pienso que este está mucho mejor por lo que a mescuchar la música se refiere. En last.fm si buscas algo en concreto sólo puedes escuchar un "preview" y te quedas con las ganas. Eso si, Spotify no tiene nada de comunidad de usuarios, ni información de conciertos, ni grupos, etc...

En cuanto al precio, 10€ al mes me parece una cantidad excesiva :(

Borra 10 amigos de Facebook y llévate una Whopper gratis

Sí, sí, como los has leído. Sacrifica 10 de tus amigos en Facebook por una hamburguesa. Así de absurdo.

Hoy me encuentro en un artículo de CNET que los señores de Burger King han lanzado una campaña de márketing viral que consiste en instalarse una aplicación de Facebook y borrar 10 de tus amigos. La han bautizado Whopper Sacrifice, y según parece, al acabar el sacrificio te dan un cupón válido para una Whopper gratis (un cupón por cuenta Facebook).

Al sacrificar uno de tus amigos, en las actualizaciones de tu perfil aparece una frase al estilo de:

Antonio ha sacrificado a Josefa por un whopper gratis.

Al borrar 10 amigos estos reciben la notificación y se adhieren a la campaña, con lo cual se convierte en un fenómeno exponencial.

Hasta aquí uno puede pensar, bueno, no cuesta nada instalar una aplicación y uno se lleva una hamburguesa al cuerpo, pero hay que tener presente qué sucede realmente cuando instalamos una aplicación en Facebook:

Si permites el acceso a Whopper Sacrifice, esta aplicación podrá obtener información de tu perfil, fotos, información de tus amigos y otros contenidos que necesite para funcionar.

Pues ala, ya está, dándo consentimiento para que Burger King tenga acceso total a lo que haga falta. Sin duda una buena manera de obtener datos confidenciales de los usuarios por la cara. Un aplauso señores.

¿Qué se hizo de esas campañas que te regalaban un viaje a Andorra por asistir a una charla informativa?

El fin de las fotos movidas en el iPhone, con Darkroom

Logo steadySe acabó que las fotos del iphone salgan movidas!

Si tienes un pulso tan bueno como el mío te habrás encontrado más de una vez que haces varias tomas de fotografías y siempre te sale la foto desenfocada o movida. Pero tu tienes paciencia y tiras la misma foto 40 veces hasta que sale bien. El simple hecho de pulsar el botón de fotografiar hace que esa mínima presión nos mueva el objetivo y adiós foto.

Pues los señores de Stepcase Limited han creado una aplicación gratuita llamada Darkroom (esta semana pasada se llamaba SteadyCam) que se espera a tirar la foto hasta que tu pulso está estabilizado. Pulsas el botón de tirar foto y la aplicación a través de un sensor de movimiento cuando detecta un momento de paz en tu mano saca la foto.

Una vez ha sacado la foto pregunta que quieres hacer con ella, si la quieres conservar o desechar y a continuación deja la cámara preparada para otro disparo. En las preferencias puedes marcar que guarde automáticamente cada disparo.

Es un poco lenta la guardar la foto, pero se puede perdonar. Almenos hace que las fotos de iPhone se puedan ver y dejen de ser tan indecentes!

Por la barbaridad de 0,79€ existe una versión premium con funcionalidades añadidas, pero a mi con esta me vale :)

SteadyCam, tomando fotografías Guardar o eliminar fotografía? Navegar por las fotos desde SteadyCam Preferencias SteadyCam

Enlace para descargar Darkroom (SteadyCam) en iTunes

El todo o nada para Palm: presentación de Nova en el CES de 2009

De todos es conocido que Palm, la inventora del concepto pda que por tanto tiempo dominó el nuevo mercado que tan bien supo crear, atraviesa por una situación muy, muy difícil después de varios años de ir a la deriva.

Tras un sistema operativo excelente pero inestable y vetusto (PalmOS) que no ha sabido renovar en 5 años, una línea de smartphones Treo legendaria pero que ya no puede con la competencia y fiascos como el Foleo, Palm lleva dos temporadas sobreviviendo a base de sacar el enésimo smartphone Treo con Windows Mobile, inferior a los demás en diseño, tamaño y prestaciones.

Aquella compañía que maravillaba por la simplicidad, elegancia y eficiencia del software que integraba en sus dispositivos, tiene una última oportunidad para demostrar que puede competir con monstruos como RIM, Google/HTC (Android), Microsoft, Nokia o Apple. Este jueves 8 de Enero Ed Colligan, CEO de Palm, presentará Nova, el nuevo y tan esperado sistema operativo en la feria CES (Computer Entertainment Show) de Las Vegas. Seguramente mostrará algún nuevo modelo de móvil que lo integre --se especula con que incorporará un teclado extraíble, como el que se ve en el diseño adjunto--, y es muy posible que también muestre aplicaciones de terceros que ya funcionen en la nueva plataforma.

Nuevo concepto de Palm 2009



Ojalá que Palm haya sabido analizar de manera realista el mercado y se posicione fuertemente de nuevo en el único nicho que puede ocupar hoy en día: el de proporcionar la excelencia en las aplicaciones PIM (contacto, agenda, notas). Aquel segmento de mercado en el que nunca ha dejado de ser el rey, por méritos propios pero también porque el resto de competidores nunca se han propuesto entrar en él.

RIM es el rey indiscutible de la mensajería con sus Blackberrys, Apple es insuperable en ocio y multimedia, Google Android se posicionará seguramente como la mejor plataforma para web, Windows Mobile es la navaja suiza en el mundo móvil (lo hace todo, pero no es bueno en nada) y Nokia inunda cada año el mercado con sus modelos basados en Symbian, otro S.O. generalista que encanta a los que prefieren el form factor de móvil tradicional.

Palm ya no tiene ninguna posibilidad de competir con cualquiera de estos monstruos en sus segmentos, así que si mañana Ed Colligan nos sale con el enésimo competidor del iphone, se acabó, finito, adiós a la marca del logo naranja. Ojalá que no sea así, y veamos un sistema operativo valiente, que se centre en las aplicaciones PIM y la excelencia en la introducción de datos en los nuevos modelos de smartphone; ojalá veamos un buen teléfono, con unas aplicaciones multimedia decentes, pero que tenga un manejo potente de agenda, tareas, notas, e-mail, wiki. Ojalá dejen de hacer diseños y carcasas cutres, con forma de ladrillo, ya muy pasados de moda.Y todo ello con la elegancia que Palm ha mostrado siempre en sus interfaces de usuario.

Ciertamente este mercado es minoritario y no va a dar el beneficio de los otros, pero es un mercado que Palm dominaba y todavía puede recuperar, donde a poco que haga seguirá siendo el rey por muchos años. Hay muchos ex-usuarios que volverían al zen de Palm si se vuelven a presentar dispositivos con prestaciones modernas pero que conserven la excelencia en la gestión de información que Palm traía inherente a la marca.

Muchos echamos de menos aquellas pdas, las tungsten, las zire (aún conservo una z22 y me es muy útil)... Mi mujer todavía usa extensamente una Palm Zire 71 que le regalé hace 4 años, ¡¡4 años!! No ha tenido una agenda tan útil como esa, y ciertamente, cuando la Zire 71 se muera no se me ocurre ningún móvil que la pueda suplir para ella en la gestión PIM... Lo más parecido es una Blackberry Curve, pero algo de la magia de la Zire se perderá.

Así pues, ¿con qué nos sorprenderá Palm mañana?