Mar 23

Deep inside AMQP

This entry is part 3 of 3 in the series AMQP and RabbitMQ

Reading time: 5 – 8 minutes

In the next lines I’ll describe with more details the properties and features of AMQP elements. It won’t be an exhaustive description but in my opinion more than enough to start playing with AMQP queues.

Channels

When producers and consumers connects to the broker using a TCP socket after authenticating the connection they establish a channel where AMQP commands are sent. The channel is a virtual path inside a TCP connection between this is very useful because there can be multiple channels inside the TCP connection each channels is identified using an unique ID.

An interesting parameter of a channel is confirmation mode if this is set to true when messages delivered to a exchange finally gets their queues the producer receives an acknowledge message with an UID of the message. This kind of messages are asynchronous and permits to a producer send the next message when it is still waiting the ACK message. Of course if the message cannot be stored and it is lost the producer receives a NACK (not acknowledged) message.

Producers

Maybe this is the most simple part of the system. Producers only need to negotiate the authentication across a TCP connection create a channel and then publish all messages that want with its corresponding routing key. Of course, producers can create exchanges, queues and then bind them. But usually this is not a good idea is much more secure do this from consumers. Because when a producers try to send a message to a broker and doesn’t have the needed exchange then message will be lost. Usually consumers are connected all time and subscribed to queues and producers only connect to brokers when they need to send messages.

Consumers

When a consumer connects to a queue usually uses a command called basic.consume to subscribe the channel to a queue, then every time subscribed queue has a new message it is sent to consumer after last message is consumed, or rejected.

If consumer only want to receive one message without a subscription it can use the command basic.get.This is like a poll method. In fact, the consumer only gets a message each time it sends the command.

You can get the best throughput using basic.consume command because is more efficient than poll every time the consumer wants another message.

When more than one consumer was connected to a queue, messages are distributed in a round-robin. After the message is delivered to a consumer this send an acknowledge message and then queue send another message to next consumer. If the consumer sends a reject message the same message is sent to next consumer.

There are two types of acknowledgements:

  • basic.ack: this is the message that sends consumer to queue to acknowledge the reception of a message
  • auto_ack: this is a parameter we can set when consumer subscribes to a queue. The setting assumes ACK message from consumer and then queue sends next message without waiting the ACK message.

The message basic.reject is sent when the consumer wants to reject a received message. This message discards the message and it is lost. If we want to requeue the message we can set the parameter requeue=true when sent a reject message.

When the queue is created there can be a parameter called dead letter set to true, then consumer rejects a message with the parameter requeue=false the message is queued to a new queue called  dead letter. This is very useful because after all we can go tho that queue an inspect the message rejection reason.

Queues

Both consumers and producers can create a queue using queue.declare command. The most natural way is create queues from consumers and then bind it to an exchange. The consumers needs a free channel to create a queue, if a channel is subscribed to a queue, the channel is busy and cannot create new queues. When a queue is created usually we use a name to identify the queue, if the name is not specified it’s randomly generated. This is useful when create temporary and anonymous queues for RPC-over-AMQP.

Parameters we can set when create a new queue:

  • exclusive – this setting makes a queue private and is only accessible from your application. Only one consumer can connect to a queue.
  • auto-delete – when last consumer unsubscribes from queue the queue is removed.
  • passive - when create a queue that exists the server returns successfully or returns fail if parameters don’t match. If passive parameter is set and we create a queue that exists always returns success but if the queue doesn’t exist it is not created.
  • durable – the queue can persist when the services reboots.

Exchange and binding

In the first post of the serie we talked about different exchange types as you can remember these types are: direct, fanout and topic. And the most important parameter to set when producer sends a message is the routing key this is used to route the message to a queue.

Once we have declared an exchange this can be related with a queue using a binding command: queue_bind. The relation between them is made using the routing key or a pattern based in routing key. When exchange has type fanout the routing key or patterns are not needed.

Some pattern examples can be: log.*, message.* and #.

The most important exchange parameters are:

  • type: direct, fanout and topic.
  • durable: makes an exchange persistent to reboots.

Broker and virtual hosts

A broker is a container where exhanges, bindings and queues are created. Usually we can define more than one virtual brokers in the same server. Virtual brokers are also called virtual hosts. The users, permissions and something else related to a Broker cannot be used from another one. This is very useful because we can create multiple brokers in the same physical server like multi-domain web server and when some of this virtual hosts is too big it can be migrated to another physical server and it can be clustered if it is required.

Messages

An AMQP message is a binary without a fixed size and format. Each application can set it’s own messages. The AMQP broker only will add small headers to be routed among different queues as fast as possible.

Messages are not persistent inside a broker unless the producer sets the parameter persistent=true. In the other way the messages needs to be stored in durable exchanges and durable queues to persist in the broker when it is restarted. Of course when the messages are persistent these must be wrote to disk and the throughput will fall down. Then maybe sometimes create persistent messages is not a good idea.

 

 

Mar 15

What is AMQP? and the architecture

This entry is part 2 of 3 in the series AMQP and RabbitMQ

Reading time: 3 – 4 minutes

What is AMQP? (Advanced Message Queuing Protocol)

When two applications need to communicate there are a lot of solutions like IPC, if these applications are remote we can use RPC. When two or more applications communicate with each other we can use ESB. And there are many more solutions. But when more than two applications communicate and the systems need to be scalable the problem is a bit more complicated. In fact, when we need to send a call to a remote process or distribute object processing among different servers we start to think about queues.

Typical examples are rendering farms, massive mail sending, publish/subscriptions solutions like news systems. At that time we start to consider a queue-based solution. In my case the first approach to these types of solutions was Gearman; that is a very simple queue system where workers connect to a central service where producers have to call the methods published by workers; the messages are queued and delivered to workers in a simple queue.

Another interesting solution can be use Redis like a queue service using their features like publish/subscribe. Anyway always you can develop your own queue system. Maybe there a lot of solutions like that but when you are interested in develop in standard way and want a long-run solution with scalability and high availability then you need to think in use AMQP-based solutions.

The most simple definition of AMQP is: “message-oriented middleware”. Behind this simple definition there are a lot of features available. Before AMQP there was some message-oriented middlewares, for example, JMS. But AMQP is the standard protocol to keep when you choice a queue-based solution.

AMQP have features like queuing, routing, reliability and security. And most of the implementations of AMQP have a really scalable architectures and high availability solutions.

The architecture

The basic architecture is simple, there are a client applications called producers that create messages and deliver it to a AMQP server also called broker. Inside the broker the messages are routed and filtered until arrive to queues where another applications called consumers are connected and get the messages to be processed.

When we have understood this maybe is the time to deep inside the broker where there are AMQP magic. The broker has three parts:

  1. Exchange: where the producer applications delivers the messages,  messages have a routing key and exchange uses it to route messages.
  2. Queues: where messages are stored and then consumers get the messages from queues.
  3. Bindings: makes relations between exchanges and queues.

When exchange have a message uses their routing key and three different exchange methods to choose where the message goes:

    1. Direct Exchange:  routing key matches the queue name.
    2. Fanout Exchange: the message is cloned and sent to all queues connected to this exchange.
    3. Topic Exchange: using wildcards the message can be routed to some of connected queues.

This is the internal schema of a broker:

Mar 09

AMQP and RabbitMQ [TOC]

This entry is part 1 of 3 in the series AMQP and RabbitMQ

Reading time: 1 – 2 minutes

After reading the book ‘RabbitMQ in action‘ I’m working on series of posts  that will include the following subjects:

  1. What is AMQP? and the architecure
  2. Deep inside AMQP
  3. RabbitMQ CLI quick reference
  4. Hello World using ‘kombu’ library and python
  5. Parallel programming
  6. Events example
  7. RPC
  8. Clustering fundamentals
  9. Managing RabbitMQ from administration web interface
  10. Managing RabbitMQ from REST API

Please let me know if you are interested in this series of posts. Because in my opinion this is very interesting and it always comes in handy to know if someone has been working on those subjects.

Aug 30

wiki: Notes sobre entorns de programació

Reading time: < 1 minute

En un .txt tenia unes notes que havia pres sobre entorns de programació, escencialment la conferència de la que són les notes parlava sobre PHP i diferents formens de fer el desplegament dels projectes. Aquesta informació l'he passat a una pàgina del wiki amb la idea d'anar-la actualitzant per altres llenguatges especialment amb la idea de afegir-hi notes de python.

Així doncs l'enllaç del wiki és a: Notes about programming environments and deployment. Tal com podeu deduir amb el títol les notes són amb anglès, sento no recordar la conferència per afegir-hi la presentació.

A continuació enganxo el contingut de la wiki de forma dinàmica, així quan actualitzi la wiki s’actualitzarà l’article:

Jun 30

dbus+python: emetent i rebent senyals

Reading time: 2 – 2 minutes

Feia massa temps que no jugava amb DBUS i les he passat una mica negres aquesta tarda intentant recordar com funcionava tot plegat. La qüestió de base és molt senzilla, com que el codi parla per si mateix. Simplement adjuntaré els dos codis.

Receptor de senyals DBUS, rep la senyal amb format ‘string’ i la mostra:

#!/usr/bin/env python
#--encoding: UTF-8--
"""
entra en un loop esperant senyals emeses a:
  dbus_interface = cat.oriolrius.prova
  object_path = "/cat/oriolrius/prova/senyal"
amb nom de senyal: 'estat'
quan es rep la senyal la mostrem
"""
import gobject
import dbus
import dbus.mainloop.glib

def mostra(m):
    print m

dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
bus = dbus.SessionBus()
bus.add_signal_receiver(
                 mostra,
                 path="/cat/oriolrius/prova/senyal",
                 dbus_interface="cat.oriolrius.prova",
                 signal_name = "estat"
                )
loop = gobject.MainLoop()
loop.run()

Emisor de senyals DBUS, envia una senyal de tipus ‘string’ amb el contingut ‘hola’:

#!/usr/bin/env python
#--encoding: UTF-8--
"""
Emet una senyal a dbus, al bus 'session' amb destí:
  dbus_interface = cat.oriolrius.prova
  object_path = "/cat/oriolrius/prova/senyal"
amb nom de senyal: 'estat'
"""
import gobject
import dbus
from dbus.service import signal,Object
import dbus.mainloop.glib

class EmetSenyal(Object):
    def __init__(self, conn, object_path='/'):
        Object.__init__(self, conn, object_path)

    @signal('cat.oriolrius.prova')
    def estat(self,m):
        global loop
        print("senyal emesa: %s" % m)
        gobject.timeout_add(2000, loop.quit)

dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
loop = gobject.MainLoop()
bus = dbus.SessionBus()
o = EmetSenyal(bus,object_path='/cat/oriolrius/prova/senyal')
o.estat('hola')
loop.run()

Usant el ‘dbus-monitor’ es pot veure la traça del missatge:

signal sender=:1.634 -> dest=(null destination) serial=2 path=/cat/oriolrius/prova/senyal; interface=cat.oriolrius.prova; member=estat
   string "hola"

Jun 28

Cheetah – the python powered template engine

Reading time: 2 – 3 minutes

Un article ‘fast-n-dirty’ sobre potser la millor llibreria que he trobat per treballar amb templates i python: Cheetah. Es tracta de poder generar fitxers de texte de forma senzilla: fitxers de configuració, pàgines web, emails, etc. a partir de plantilles. Realment útil en molts entorns.

Les funcionalitats (copy-paste de la web):

  • is supported by every major Python web framework.
  • is fully documented and is supported by an active user community.
  • can output/generate any text-based format.
  • compiles templates into optimized, yet readable, Python code.
  • blends the power and flexibility of Python with a simple template language that non-programmers can understand.
  • gives template authors full access to any Python data structure, module, function, object, or method in their templates. Meanwhile, it provides a way for administrators to selectively restrict access to Python when needed.
  • makes code reuse easy by providing an object-oriented interface to templates that is accessible from Python code or other Cheetah templates. One template can subclass another and selectively reimplement sections of it. Cheetah templates can be subclasses of any Python class and vice-versa.
  • provides a simple, yet powerful, caching mechanism that can dramatically improve the performance of a dynamic website.
  • encourages clean separation of content, graphic design, and program code. This leads to highly modular, flexible, and reusable site architectures, shorter development time, and HTML and program code that is easier to understand and maintain. It is particularly well suited for team efforts.
  • can be used to generate static html via its command-line tool.

a qui va orientat (copy-paste de la web):

  • for programmers to create reusable components and functions that are accessible and understandable to designers.
  • for designers to mark out placeholders for content and dynamic components in their templates.
  • for designers to soft-code aspects of their design that are either repeated in several places or are subject to change.
  • for designers to reuse and extend existing templates and thus minimize duplication of effort and code.
  • and, of course, for content writers to use the templates that designers have created.

Jun 16

Somiant amb una extenció pel Gearman

Reading time: 5 – 8 minutes

Cal dir que no sóc massa ordenat al presentar noves tecnologies ja que primer de tot vaig fer un bechmark sobre Gearman abans de fer-ne una introducció, doncs bé com que en aquest article vull parlar sobre unes possibles extensions sobre les que vull treballar amb Gearman primer de tot faré una petit introducció al projecte.

Introducció

Gearman és el que comunment anomenem un servidor de tasques, o sigui, que quan el nostre codi ha de demanar una tasca, funcionalitat, treball, o quelcom similar és molt interessant de cara a:

  • l’escalavilitat: podem tenir tants servidors i/o processos consumint tasques com ens interessi.
  • paral·lelisme: les tasques es poden consumir paral·lelament.
  • balanceix de càrrega: podem fer map/reduce sobre les tasques i enviar-les als servidors que ens interessis per distribuir la càrrega.
  • independència entre lleguatges: el codi que demana la tasca i el que consumeix la tasca poden ser totalment diferents, les llibreries que té Gearman són: PHP, Pearl, Ruby, C, Python, etc.
  • interficie HTTP: a més disposa d’una interficie client HTTP que ens permetra injectar tasques desde llenguatges no suportats des de les llibreries de Gearman.

usar un servidor d’aquest tipus, ja que a més de permetrens demanar tasques síncrones, també podem demanar-li tasques asíncrones. O sigui, que no només no sabem qui ens esta fent la feina limitant-nos a rebre’n el resultat sinó que també podem demanar que aquesta feina es faci quan es pugui.

Per si tot això no fos poc encara hi ha més avantatges:

  • Open Source
  • Programat en C
  • Petit i molt ràpid
  • Suporta diversos backends: RAM, SQLite, Memcached, Tokyo Cabinet, etc.

gearman stack

La gent que va començar a implementar Gearman, van ser els de Danga Interactive famosos per LiveJournal i SixApart.

Les meves idees

Després d’aquesta introducció, ara ja puc parlar de les coses que voldria que fes Gearman però que no fa. Primer de tot he de parlar de les avantatges que tindria si pogués tenir un backend contra Redis. El que persegueixo al connectar Redis amb Gearman és aconseguir:

  • persistència de tasques malgrat es reiniciï Gearman
  • persistència de tasques en disc malgrat es reinciï Redis, gràcies a:
    • l’escriptura asíncrona a disc
    • bgrewriteaof: evita que per l’escriptura asíncrona d’informació es perdin dades al reinciar bruscament Redis
  • publicar a un canal PubSub de Redis els canvis que es fan sobre una tasca que s’ha enviat a ‘background’

Integració amb Redis

Es tracata de fer el mateix que s’ha per integrar backend de tokyo cabinet: queue_libtokyocabinet.c el problema d’usar tokyo cabinet contra disc és la pèrdua brutal de rendiment respecte a usar-lo contra RAM, ja que les escriptures es fan de forma síncrona.

A nivell de codi les semblances més grans són amb: queue_libmemcached.c, malgrat el problema que té aquesta implementació és que cada cop que reiniciem memcached no tenim persistència de la informació que s’havia guardat en memcached, és com si les claus que s’han intrudit en l’anterior sessió s’haguessin esborrat. A més memcached no suporta persistència en les seves dades tampoc.

Així doncs, el que cal fer és agafar el millor d’amdues integracions i fer el mòdul amb Redis.

Subscripció a les actualitzacions d’una tasca via Redis

Quan s’envia una tasca en segon pla a Gearman aquest ens retorna un ‘Handler’ per poder preguntar sobre l’estat de la tasca, el problema és que si volem saber com evoluciona la tasca o que ens informi quan ha acabat no hi ha manera de saber-ho si no és fent ‘pooling’. Per altre banda, el ‘worker’ va actualitzant la tasca cada quan creu convenien perquè Gearman pugui saber quin és l’estat de la mateixa.

La meva idea és que al usar el backend de Redis, al mateix moment que s’actualitzi l’estat de la tasca també es publiqui (publish) a un canal PubSub de Redis de forma que el codi que ha enviat la tasca pugui subscriures (subscribe) a aquest canal i en temps real i amb un cost de recursos baixíssim es pugui seguir l’estat de la tasca. Això ens evitaria la necessitat de que Gearman hagués de poder cridar un mètode de callback per informar-nos de l’estat de la mateixa, ja que hi ha alguns llenguatges en que fer això no és tan senzill.

En el gràfic que enganxo a continuació podem veure un esquema que he fet sobre això:

esquema idees de Gearman amb Redis

1) el nostre codi envia una tasca en ‘background’ (segon pla) a Gearman i aquest li torna un ‘Handler’ per identificar la tasca.

2) es guarda la tasca a Redis (set)

3) el nostre codi es subscriu al canal PubSub de la tasca

4) un worker demana la tasca

5) es publica l’estat de la tasca

6) es va actualitzant l’estat de la tasca

7) es van repetint els punts (5) i (6) fins acabar la tasca

Feedback

Com sempre s’accepten tota mena de crítiques i idees sobre la meva ‘paranoia’.

Apr 22

Integració continua: buildbot + codespeed + guppy-pe + resource

Reading time: 3 – 4 minutes

Degut a un requeriment que teniem a la feina he montat un entorn d’integració continua. En escència el que es busca és el següent:

  • Llençar de forma automàtica tests sobre els commits que es fan al codi (buildbot)
  • Tenir un repositori dels resultats dels tests fàcil de consultar (web) (buildbot)
  • Suportar tests sobre rendiment (profiling) automàtics (guppy-pe + resource)
  • Poder comprovar quina és l’evolució d’aquests tests de rendiment amb una eina visual (codespeed)

Per tal d’aconseguir aquests objectius s’ha usat:

  • buildbot: que permet automatitzar l’entorn de compilació i testeix dels commits que es van fent al repositori. (esta programat en python). Per entendre millor buildbot, ús recomano llegir l’apartat: system architecure del seu manual.
  • codespeed: és una eina feta amb python+django+mysql a través d’una interficie HTTP+JSON pot injectar informació a la BBDD i a través de la GUI ens mostra:
    • overview: a través d’una taula mostra les tendències dels resultats dels benchmark associats a un executable.
    • timeline: mostra en una gràfica l’evolució dels resultats arxivats sobre un benchmark concret fets sobre un host.
  • guppy-pe: ens permet extreure dades referents als recursos de sistema que esta consumint una part del codi: classe, funció, variable, etc.
  • resource: és un módul de python que permet saber (resource.getrusage(PID)) quins recursos esta consumint un PID en un moment donat.

Com que la documentació que he fet per la feina l’he hagut de filtrar per no revelar informació interna, la documentació que publico esta en format OpenOffice i PDF perquè sigui senzill per tothom llegir-la i modificar-la si vol.

  • Paquet .tar.gz, conté:
    • fitxer de configuració buildbot, master.cfg
    • codi d’exemple per provar l’entorn, buildbot-test
    • codi del tobami-codespeed modificat perquè sigui més generalista que la versió original
    • integracion-continua-instalacion.odt: document amb notes sobre els procediments que he seguit per la instal·lació de tot plegat.
    • integracion-continua-manual.odt: manual d’usuari de tot plegat. (també la versió en pdf)
  • integracion-continua-manual.pdf: enllaço de forma directa aquest manual per si hi voleu donar un cop d’ull per saber si ús interessa el tema.

Enllaços relacionats:

Apr 21

dues versions de python en un host

Reading time: < 1 minute

A vegades cal fer algún invent extrany amb el python, com per exemple, el haver de tenir dues versions instal·lades. Sovint la nostre distribució ja portarà una versió del mateix i a més moltes eines de les distribucions acostumen a anar lligades a aquesta versió que millor no malmetre.

Cookbook d'ordres per instal·lar un python 2.6.5 a més del 2.4.3 que ja portava el host:

cd /var/tmp
wget http://python.org/ftp/python/2.6.5/Python-2.6.5.tar.bz2
tar xvfj Python-2.6.5.tar.bz2
cd Python-2.6.5
./configure –prefix=/usr
make
make altinstall

si ara fem:

# python -V
Python 2.4.3
# python2.4 -V
Python 2.4.3
# python2.6 -V
Python 2.6.5

Feb 12

eines per XMPP

This entry is part 4 of 4 in the series xmpp

Reading time: 2 – 3 minutes

A continuació adjunto una petita descripció d’algunes eines per comunicar-se amb una xarxa XMPP que poden ser molt útils:

Idavoll

Implementació del XEP-0060, o sigui, d’un servei de publish-subscribe (PubSub) esta escrit amb Python i Twisted. Bàsicament el que permet és que sobre un servidor XMPP estàndard hi podem connectar un servei basat en PubSub, o sigui, que nosaltres publiquem una serie d’informació que un seguit de clients consulten perquè hi estan subscrits. És un mètode basat en events (no-polling) molt adient per disfondre certs tipus d’informació.

Switchboard

A vegades programem shell scripts que necessiten enviar el seu resultat a la xarxa XMPP, per exemple, imagineu que volem comunicar la caiguda d’un servei a través de GTalk, doncs aquest toolkit ens simplifica moltíssim aquesta tasca. Esta programat en ruby i a part de poder-se usar des de la CLI també podem integrar-ho com a llibreria dins d’un codi en ruby.

XMPP Poetry CLI tools

El seu nom ja ho diu tot, són una col·lecció d’eines que via CLI ens permeten interactuar amb una xarxa XMPP, algunes de les seves funcions són:

  • disco: recull informació sobre serveis
  • pubsub-config: crea, configura i llança queries contra serveis pub-sub

Aquestes eines estan escrites amb Python, Twisted i Wokkel.

XMPPPHP

Llibreria de PHP5 amb suport de:

  • XMPP 1.0 (pot connectar a: GTalk, LJTalk, jabber.org, etc)
  • Suporta TLS
  • Processa diversos formats XML

Sembla força senzill d’usar, per exemple, programar un bot és tan fàcil com això:

<?php
include("xmpp.php");
$conn = new XMPP('talk.google.com', 5222, 'user', 'password', 'xmpphp', 'gmail.com', $printlog=True, $loglevel=LOGGING_INFO);
$conn->connect();
while(!$conn->disconnected) {
    $payloads = $conn->processUntil(array('message', 'presence', 'end_stream', 'session_start'));
    foreach($payloads as $event) {
        $pl = $event[1];
        switch($event[0]) {
            case 'message':
                print "---------------------------------------------------------------------------------\n";
                print "Message from: {$pl['from']}\n";
                if($pl['subject']) print "Subject: {$pl['subject']}\n";
                print $pl['body'] . "\n";
                print "---------------------------------------------------------------------------------\n";
                $conn->message($pl['from'], $body="Thanks for sending me \"{$pl['body']}\".", $type=$pl['type']);
                if($pl['body'] == 'quit') $conn->disconnect();
                if($pl['body'] == 'break') $conn->send("");
            break;
            case 'presence':
                print "Presence: {$pl['from']} [{$pl['show']}] {$pl['status']}\n";
            break;
            case 'session_start':
                $conn->presence($status="Cheese!");
            break;
        }
    }
}
?>