GNOME.ORG

24 horas al día, 7 días a la semana, 365 días al año*, esto es Planeta GNOME Chile

May 28, 2013

Monkey project news

Two short news:

May 15, 2013

Wed 2013/May/15

April 26, 2013

Fri 2013/Apr/26

  • Oh the WebKits! During the past few weeks, thanks to Igalia's collaboration with the good folks at Bloomberg, I have descended from the heights of Epiphany and WebKitGTK+ to the depths of WebCore, that obscure but cleverly assembled part of WebKit that magnificently takes care of the logic inherent to layouting, rendering, and the inner representation of HTML documents. A fascinating aspect of WebCore is that its architecture, completely decoupled from the actual implementation in the different WebKit ports, means that any change to its parts will affect all ports and browsers built upon this marvelous piece of engineering. Let me assure you, dear reader, the challenges this implies are comparable only to the joy it brings to this humble hacker, as the following will reveal!

    Among the many duties of WebCore lies controlling the logic behind user interaction with HTML documents — something that has changed considerably in recent years. While originally, most interactive editing in the web was limited to plain and boring web forms, in this brave new world of ours it is also possible to build complete HTML editors using nothing but HTML and JavaScript access to the DOM. Have you seen Wordpress' fantastic editor? Then you shall agree with me that this is an extremely powerful feature.

    But with great power comes great responsibility, as the old saying goes. And with great responsibility come bugs, says a more recent variation of the same maxim. And where bugs are to be found, relentless minds work tirelessly in order to ensure that your browsing experience never ceases to improve. This is one of the goals that Igalia, humbly but boldly, pursues with utmost seriousness. And so it has been that I, your humble servant, have spent countless hours mastering my way through the DOM and editing features of WebCore. Bugs have been fixed already — some affecting editing in Windows, others affecting editing in GNU/Linux, and others affecting all platforms equally. More will be fixed in the forthcoming weeks. I can only attempt to share my excitement through these words, for I am unable to express it in a way that would do it justice.

  • As a side note, I am a committer to the WebKit project for a little while now. This is pretty cool, as it means I get a direct chance to break your browser. Or unbreak it, shall it be the case. I try to lean towards the latter but trust me, it is not an easy task!

April 16, 2013

Building evince with jhbuild under a fresh install of Ubuntu 12.04

In the last year or so, Jhbuild has received a lot of  love and know it is much easier to use (for the first time) than it used to, but how much? Since Google Summer of Code is coming, I wondered whether was easy for a person with no experience building GNOME to build Evince. It turns out it is not that trivial, although it is quite better than the first time I managed to compile Evince using jhbuild.  Since the Jhbuild manual seems to be still a little outdated, I publish here the steps I needed, on a fresh install of Ubuntu 12.04.


  1. Install all the things jhbuild won't install for you. 
    $sudo apt-get install build-essential
    $sudo apt-get install git
    $sudo apt-get install gettext xsltproc docbook-xml docbook-xsl
    $sudo apt-get install apt-file autopoint
  2. Install jhbuild from git (if you have previously installed from apt-get, use apt-get remove jhbuild to remove it)
    $git clone git://git.gnome.org/jhbuild
    $cd jhbuild
    $./autogen.sh
    $make
    $make install
    $echo PATH=$PATH:~/.local/bin >> ~/.bashrc
  3. Prepare your first .jhbuildrc config file.
    $cp examples/sample.jhbuildrc ~/.jhbuildrc
  4. Edit ~/.jhbuildrc file
    • Search for the line starting with "prefix" and change the directory to a writable one (the default /opt/gnome is not writable by default on ubuntu it seems)
    • For evince, you need to add the following lines to ~/.jhbuildrc
      skip=['libnotify','polkit','nautilus','vala']
      module_autogenargs['evince'] = autogenargs + ' --enable-debug --disable-nautilus'
  5. Install dependencies using the new "sysdeps" command of jhbuild
    $jhbuild sysdeps --install
  6. Building evince
    $jhbuild build evince --ignore-suggests --nodeps
NOTE: For the time being, this will give you an error because jhbuild won't compile libsecret when compiling using --ignore-suggests. See this bug for more info. If it fails for you with a LIBSECRET not found error, then start a shell, do
$jhbuild buildone libsecret

and then resume the compilation of evince. If you want, you could do, at this stage
$jhbuild buildone evince
to trigger just the compilation of evince and NONE of its dependencies.
We use --ignore-suggests to ignore compiling a lot of modules that are not really important for developping with evince.
If everything goes right, you should have evince 3.8 compiled. If you want master, you need to choose the "gnome-suites-core-3.10" moduleset

April 12, 2013

Monkey Project joins Google Summer of Code 2013

thanks Google for the opportunity! , this week the results for the Mentoring Organizations for Google Summer of Code 2013 were released. I am very happy to announce that Monkey Project will be part of the program as second consecutive year.

We are a very small group of people developing an open source stack for web technologies and take part of the program means a big recognition, we are glad to be able to mentor students that will be hacking with us during three months.

Our last year experience was very positive, most of projects were developed successfully and those students have take an important role in our community and project development in general, so we have high expectations for this second round, as you can see there is a good scope of project ideas to develop in areas such as protocols (SPDY), OSX, Raspberry Pi, Web Services, etc.

You can get more details about the incoming work in our Monkey GSoC project ideas page.

April 09, 2013

Apache2 + SSL en ambiente de pruebas

Tiempo atrás escribí este documento (para cuando era Apache1.3), ahora lo actualicé para Apache2 en Debian7. Si a alguien le interesa se los comparto Apache2_SSL.

March 29, 2013

iOS Kernel Panic

today happened something that i was told many times that will not happen: iOS hanged in my Wife’s iPad, it wrote some trace messages alerting a Kernel Panic.



Kernel Panics are Apple’s friends too :)

March 19, 2013

Aclaraciones sobre el acceso a mi colección de videos y música simplificado

Con la publicación de mi artículo sobre cómo simplifiqué el acceso a mi colección de videos y música, tuve varias conversaciones con personas que habían hecho algo similar, y como en los asados, cada uno tiene su propia y “mejor” forma de hacer las cosas.

Para los amigos que aun están en la etapa de ver cómo hacerlo, quiero hacer algunas aclaraciones para ayudarlos a entender mi experiencia y el por qué de algunas decisiones que tomé en la implementación.

Creo que lo primero que conviene saber es qué es lo que ya había probado (y no era suficiente).  Por ejemplo muchas de las soluciones que me indicaron del tipo “pero es más fácil si …” eran justamente lo que tenía como punto de partida, y quería mejorar.

Implementación original

Incialmente tenía un Zotac Mag con XBMC conectado a uno de los televisores.  Este equipo tenía parte de mi contenido en su disco duro, y el resto lo leía desde una biblioteca compartida en otro PC via red.  Este es el equivalente a tener por ejemplo un computador con una biblioteca de iTunes compartida y un AppleTV o un Mac Mini conectado al televisor actuando como reproductor.

Esta solución tiene varios problemas para mis necesidades personales:  Uno es que necesitas tener al menos un equipo siempre encendido, en este caso el que comparte la biblioteca (sea iTunes u otro), y si es un Apple, necesitas además tener un reproductor Apple por cada televisor.  Si no es Apple, pues es lo mismo que ya tenía con el Zotac Mag.  Por otra parte, el contenido del disco del Zotac Mag no podía ser compartido fácilmente.

Mientras tanto, el segundo televisor no tenía nada conectado, y la única forma de acceder al contenido era sacando el disco USB con mi biblioteca para conectarlo directamente al PC.  Engorroso si son las 2AM o estás compartiendo un buen momento con otra persona. Ni hablar si eso implicaba copiar archivos o que el televisor no pudiera reproducir los archivos.

Pensé en algún momento conseguir otro equipo como reproductor, pero en el camino y por otros motivos, me hice de un GoogleTV y un AndroidTV, ambos con capacidad de reproducir contenido via DLNA.

Entra el NAS

Para eliminar el equipo que siempre está encendido, fue donde recurrí al NAS.  También es un equipo que siempre está encendido pero tiene ventajas bien interesantes:  Su consumo de energía es mínimo, es un server puro (no hay capacidad ociosa), y ocupa tan poco espacio que es como si no existiera.

Aca pueden ver una foto del NAS, y para apreciar su reducido tamaño, le puse encima un DigiPass, que es del porte de un llavero.

NAS

NAS junto a un DigiPass

Tener el NAS es como si mi biblioteca estuviera simplemente “en la red” de mi casa.  Es tan pequeño que el router motorola de VTR parece una torre al lado de él.  Lo único molesto es su led rojo cuando está encendido, pero se nota sólo si la pieza en donde está tiene todo apagado.  Tampoco tiene ventiladores, por lo que es absolutamente silencioso.

Los reproductores

Para la reproducción de video, independiente de que ocupara XBMC, un computador con VLC, un televisor Smart, GoogleTV, Android TV, etc, el denominador común siempre terminó siendo DLNA.  Es más, en el televisor Smart sólo enchufas el NAS y te aparece lo que muestra la foto de abajo.

NAS en LG Smart TV

NAS en LG Smart TV

Una de las críticas a mi implementación era que era “muy hacker”.  Pero las “hackers” de mi casa no tienen mayor problema presionando el botón “input” para seleccionar el NAS.

Acá hay una captura de lo que se ve cuando selecciono el NAS en el televisor.

Selección de videos del NAS en LG SmartTV

Selección de videos del NAS en LG SmartTV

Por el lado del televisor “no smart”, este ya se encontraba conectado a un GoogleTV. Lo único que me costó fue decidir qué aplicación usar para acceder al NAS, y justamente escribir este artículo es para ahorrarles ese tiempo. Basta instalar MediaHouse desde Google Play, seleccionar el NAS y listo, verán las mismas carpetas que se ven en la foto.

Transcodificación

El no poder reproducir el contenido por encontrarse en un formato no procesable por los reproductores es algo que sólo se puede evitar conectando un computador con XBMC o VLC al televisor, en donde la disponibilidad de codecs es infinita.  Pero eso es volver al punto de inicio, cuando ya tenía el Zotac Mag con XMBC.  Lo mismo sería conectar un Mac Mini o un AppleTV, es volver al punto de inicio del que quería escapar.

La transcodificación tiene sus pro y sus contras. El principal contra es que es un proceso lento, dependiendo del computador puede tomar unos 10 minutos por hora de video.

A su favor tiene varias cosas, sobre todo considerando que el video se transcodifica sólo una vez. Vamos viendo:

  • El archivo resultante generalmente es más pequeño que el original, dependiendo del bitrate seleccionado.  Por ejemplo muchos DVD’s de 4.7GB terminan convertidos en archivos de 500MB con la misma calidad aparente.
  • Se puede integrar en un solo archivo el video con sus subtítulos, nada de andar con los archivos sueltos por ahí
  • Muchos de los videos en HD que pululan en la red ya están en el formato correcto (MKV/H.264), no hay que transcodificarlos
  • El archivo SIEMPRE funcionará en todos los dispositivos.  Aquí your mileage may vary porque depende de tus dispositivos.
  • En mi caso, la mayoría del contenido que estoy moviendo al NAS lo tengo originalmente en DVD, por lo que la transcodificación es INELUDIBLE.  Por otro lado, la ganancia en espacio físico es altísima, ya que el CD/DVD se puede descartar una vez transcodificado.

Lo que no se vió

Hay una parte del proceso que quizás confundió a algunos que lo encontraron “muy hacker” y fue la actualización del firmware para instalar Snake OS.

En la realidad, los “complejos” pasos fueron:

  • Conectar el NAS a la red
  • Encenderlo
  • Abrir la página web de administración (como si fuera un router)
  • Seleccionar el archivo con SnakeOS y darle Aceptar
  • Esperar a que terminara la instalación y posterior reinicio.
Video en 1080p corriendo sobre LG SmartTV conectado al NAS

Video en 1080p corriendo sobre LG SmartTV conectado al NAS

Los costos

La parte de costos no es menos importante.  No me gusta llenarme de equipos con capacidades que no voy a usar, y si puedo reutilizar algo que ya tengo, mejor aún.  Por otro lado me si voy a gastar en algo, tiene que ser proporcional al uso que le voy a dar.  Como a veces le digo a mis amigos, para qué quiero un auto caro si pasará casi todo el tiempo estacionado.

Esto era lo que ya tenía antes de comenzar esta implementación:

  • 1 Televisor con soporte de DLNA
  • 1 Televisor sin soporte de DLNA
  • 1 Google TV enchufado al televisor sin DLNA
  • 1 Disco duro de 500GB que me sobró cuando le cambié el disco al Mac Mini
  • 1 Red Wifi :-P

Estos fueron mis costos en hardware:

  • 1 NAS : USD$40
  • 1 Adaptador para el enchufe : USD$1

Total : USD$41 (unos CLP$20.500)

Mis costos en horas hombre (aproximado):

  • Actualización del Firmware : 5 minutos considerando lo que tuve que leer

También hay costos del “noviciado” y que se evitarán con este par de artículos sobre el tema. No tengo estimaciones ni tampoco interesa mucho, porque no tendrán que pasar por eso nuevamente:

  • Reformatear disco NTFS a EXT
  • Buscar solución al problema de Mac OSX con versiones antiguas de SMB
  • Probar el codec que funcionara mejor, junto a su configuración

A modo de comparación de costos, aquí están los costos calculados de las alternativas “más fáciles”, pero que tenían el pequeño inconveniente de ser iguales a mi problema original, el que ya tenía solucionado:

Alternativa 1:

Time Capsule + 1 Mac Mini por cada televisor, o sea 2 Mac Mini

  • 2 Mac Mini = 2 * CLP$384.000 = CLP$768.000
  • 1 Time Capsule para alojar la biblitoeca (2TB) = CLP$192.000

Costo total sólo en hardware : CLP$960.000

Una diferencia de un 4.800% con el costo de mi implementación.

Alternativa 2:

1 Mac Mini + 1 Apple TV por cada televisor, es decir, 2 Apple TV

  • 2 Apple TV = 2* CLP$76.000 = CLP$152.000
  • 1 Mac Mini  = $384.000

Costo total sólo en hardware : CLP$536.000

Una diferencia aproximadamente de 2.600% con el costo de mi implementación.

Además hay que agregar que con un sistema basado en Apple no podría acceder al contenido desde los 2 computadores con Linux que además se usan en la casa, ni los Android’s.

En mi caso personal también podría descontar el Mac Mini, porque hay uno.  Pero ni loco lo dejaría encendido 24×7.  Aún así la implementación sería un 700% más cara que lo que conseguí finalmente.

February 27, 2013

Architecture of a Linux based Web Server

this post is all about Monkey HTTP server, i consider that is very important that besides we open our source code, the developers be also able to describe the project internals, there is no black magic, just thousands of hours of effort in programming, testing and improvement.

Introduction

Monkey is an open source project started on 2001 with the goal to learn C, the long story is here . Along this years, the code have been improved in many aspects, since nomenclatures to heavy architecture changes, all have been made for good and nowadays thanks to the community of core developers and contributors around the project, Monkey is one of the top performance web servers around, and i would claim that the best option for Embedded Linux.

Understanding the basics of a human readable protocol: HTTP

The Hyper Text Transfer Protocol is basically a language with simple grammar to communicate two components: a HTTP client and a HTTP server. In a common context, the communication starts from a client performing a request to the server and for hence the server replying back with some result for the request performed. As a result we can consider a status response plus a content or simply an error.

Each HTTP request performed by the client is composed by a request method, URI, protocol version, and optionally a bunch of headers, so described that, we can say that a server must take care of:

  • Listen for new connections
  • Accept connections
  • Once the connection is accepted, start reading the HTTP request sent by the client
  • Parse the HTTP request, understand what the client wants
  • Depending of the request type, the sever can: serve some content, close the connection because some exception, proxy back the request to somebody else, etc.
  • Close the connection or keep it opened waiting for more requests. This depends of the protocol version and client HTTP headers.

Depending of the server target, it can be implemented in many ways with different architecture strategies, so the architecture described in this post only aims to describe what have worked better for us in terms of high performance and low resources usage.

Architecture design facts

  • Monkey is a web server designed with a strong focus in Linux. It do not aims to be portable across other operating system, focusing in the top and widely used mainstream operating system allow us to put our energies and effort in one place in the best way, and of course take the most of Linux Kernel to achieve high performance.
  • Event driven: well known as asynchronous, an event driver web server aims to use non-blocking system calls to perform it works reducing the computing time in the user-space context, e.g: if we are sending a file content to a client, we do not block the whole process or thread when sending the data, instead we instruct the kernel through a system call to send N bytes from the file and just notify me where i am able to send more bytes, in the meanwhile.. i process other connections and send other pending data.
  • Embedded Friendly: our embedded context is Embedded Linux, we care a lot of resources consumption, that means that under a heavy load don’t use more than 2.5MB of memory. Even Monkey binary size is around 80KB, once is load in memory it takes like 350KB, and depending of the load, more resources can be needed.
  • Small core, flexible API: it implements a basic core to handle HTTP protocol, it exposes a flexible API through the plugin interface where is possible to hook plugins for transport layer, security, request type and event handlers.

Contexts

In Monkey, we have defined two contexts of work: process context and thread context. The process context represents the main process waiting for incoming connections and the scheduler balancing the new connection for the worker threads. The thread context belongs to each thread working the active connections:

The number of workers are defined in the configuration, it scale properly well in single and multi-core CPUs solutions. There is no need to set thread affinity through CPU masks, the Linux Kernel Scheduler is smart enough to assign CPU time to each worker request, by default all workers are assign to all CPUs.

From a system administrator point of view, is possible to assign each worker to a different set of CPUs, but this approach is not suggested unless we are totally aware about what the Linux scheduler does in terms of interruptions,  context switches and CPU time for Kernel and User space applications. Do it only if you can do it better than the running scheduler.

Scheduler

Before to enter in the server loop, the scheduler launch and initialize each worker, taking care of set the initial data structures and the interfaces for the interaction between the components mentioned, this stage involves the creation of a epoll(7) queue per worker. Is good to mention that each epoll(7) queue created through epoll_create(2) is managed through a specific file descriptor.

Once the workers are up and running, the next Scheduler job is to to manage the incoming connections. So for each new connection accepted, it determinate who is the lowest loaded worker and assign the connection to it. The chosen worker is the one that have less connections in its epoll(7) interface, so the scheduler  goes around the worker counters and chose one. On this specific point the scheduler have two file descriptors: the connection file descriptor returned by accept(2) and the file descriptor that represents the epoll(7) of the chosen worker. So it basically register the new file descriptor in the proper epoll(7) queue.

Workers

Each worker or thread, runs in an infinite loop through the epoll(7) interface, which is basically a Linux specific polling mechanism to register, enqueue and notify about events in file descriptors registered by the Scheduler (sockets on this case).

The worker stay in a loop waiting for events in the epoll_wait(2) system call. Every time the Scheduler register a new file descriptor, an event will be reported in the worker epoll(7) interface, and it will do same when for subsequent events such as “there is data available for read” (EPOLLIN), “now you can write to the socket” (EPOLLOUT), “connection closed” (EPOLLHUP), etc.

So for each event triggered, the worker keeps a status of the connection to determinate if is a new connection, its receiving the HTTP request, HTTP request completed, parsing the request or sending out some response. Besides events, every a fixed time of seconds set in the configuration, it checks the connections that timed out due to an incomplete request or another anomaly.

Plugins Architecture

Monkey defines three categories of API where the plugins can hook: Context, Events, Stages and Networking.

Context
Define callbacks  that can be invoked when the server is starting up, it covers the process and thread contexts described earlier.

Events
For every type of event reported in a worker loop, a plugin can implement a hook to perform specific actions:

Stages
Every new connection, enter in a stage status, so for each step of the HTTP cycle it passed along different phases, and each plugin can hook to a specific one:

Networking
Monkey is not aware about networking, for hence it intentionally depends of a plugin that provides the transport layer, this approach allows to change from common sockets communication to encrypted one as SSL in a easy manner. The networking plugin only needs to provide the required API functions for the communication:

Scaling up

Every time a connection have performed a successful request, this is allocated in a global list of the worker scope (implemented through a pthread_key). for each event reported, the worker needs to lookup the internal data associated to it, so the file descriptor or socket number  acts like a primary key for the search. The solution of data structure implemented for Monkey v1.2, is the use of red-black tree algorithm. This algorithm have shown to behave very fairly and scalable when handling thousands of active connections per worker, maintaining a good balance between performance and cost.

The cost of each file descriptor lookup is critical for the server performance, having a O(n) solution will work fine for a few connections but under high concurrency a O(log(n)) solution will end up providing the highest performance.

Memory Management

One of the success key to reduce overhead in a server, is to reduce as much as possible the memory allocation requests performed  to the system within the main loop. Current Monkey implementation only performs 1 memory allocation per new connection, if it needed because the incoming request will post too much data, it will allocate more memory as it needs. Other web server solutions implements caching mechanism to reduce even more the memory allocations, as our focus is Embedded Linux we focus into speed at low resources usage, and implement a caching mechanism will increase our costs. So we dropped that common approach to do not abuse of system memory, just a decision based in the target.

Linux Kernel system calls

The Linux Kernel exposes a useful of non-portable set of system calls to achieve high performance when creating networking applications. The first one is epoll(7), as described earlier this interface allow to watch a set of file descriptors for certain defined events. Similar solutions like select(2) or poll(2) do not perform so well as epoll(7) does.

When sending a static file, the old-fashioned way is to open the file, get the file descriptor and perform multiples read(2)/write(2) to write out the file content. This operation requires the Kernel to copy data between Kernel and User spaces back and forward which obviously generate an overhead. As solution, the Linux Kernel implements a Zero-Copy strategy through the system call sendfile(2). This system call do not copy data to user space, instead it allows to send it directly to other file descriptor achieving good performance reducing the latency of the old fashioned way described.

In our architecture, the Logger plugin requires to transfer data through a pipe(2)  (a unidirectional data channel that can be used for interprocess communication). A common mechanism is to use read(2) and write(2) on each end, but in a similar way as sendfile(2) works, a new system call takes place for this kind of situation called splice(2). This system call moves data from one point to other without the copy-data overhead. The main difference between sendfile(2) and splice(2), is that splice(2) requires that one end must be a pipe(2).

In my previous post, i mentioned how to usage the new Linux Kernel feature called TCP_FASTOPEN, being something very simple to implement, it requires the cooperation of both sides: the client and the server. If you have full control of your networking application (client and server), consider to use TCP_FASTOPEN, it will increase performance decreasing the TCP handshake roundtrip.

Monkey Plugins

Based in the architecture and API described, the following plugins are distributed as part of the core:

Liana: basic sockets connectivity layer

PolarSSL: provides a transport layer based in SSL

Cheetah: plugin that provides a command line interface to query the internals of a running server through a unix socket

Mandril: security layer that aims to restrict the access by URI strings or sub networks.

Dirlisting: directory listing

Logger: log writer

CGI: old fashioned CGI interface

FastCGI: provide fast-cgi support

 

Bonus track: Full HTTP Stack for web services implementation

Besides to be a common web server to serve static or dynamic content, Monkey is a full stack for the development of web applications. In order to provide an easy API for web application or web services development, we have created Duda I/O , which is an event-driven C framework for rapid development based in Monkey stack.

Duda implements a core API of pseudo-objects and provide extra features  through a packages system, everything in a friendly C API. The most relevant features supported at the moment are WebSocket, JSON, SQLite3, Redis, Base64 and SHA1.

Due to it high performance nature and open source ecosystem around, is being used in production from Embedded Linux products to Big Data solutions. The License of Duda allows to create closed-sourced services or applications and link them to Duda I/O stack at zero cost.

For more details please refer to Duda I/O main site.

Monkey organization believes in Open Source and is fully committed to create the best networking technology for different needs. If you are interested into participate as a contributor or testing our stack, feel free to reach us on our mailing lists or irc channel #monkey at irc.freenode.net.

February 21, 2013

Linux TCP FASTOPEN in your sockets

Few years ago the concept of TCP_FASTOPEN (TFO) was introduced as a solution to improve performance on TCP connections reducing one roundtrip of the handshake process. The first operating system that implements TFO is Linux and have been demonstrated good improvements when used in a common network.

The implementation in the Linux Kernels have been made by parts, being Linux Kernel 3.6.1 the first one into implement the client side requirements and then Linux Kernel 3.7 who implements the server side socket behavior.

Client side

In a common TCP client flow, the following calls takes place:

1
2
3
4
5
6
7
8
9
10
11
12
13
/* create socket file descriptor */
fd = socket(domain, type, protocol);
 
/* connect to the target server/port */
connect(fd,...);
 
/* send some data */
send(fd, buf, size);
 
/* wait for some reply and read into a local buffer */ 
while ((bytes  = recv(fd, ...))) {
    ...
}

When using TCP_FASTOPEN the behavior its a little different. You not longer need to use connect(2), instead you use sendto(2) and it also gives you the opportunity to let the Kernel buffer some initial outgoing data. For short, the call sendto(2) its like an implicit connect(2) and send/write(2) same time:

1
2
3
4
5
6
7
8
9
10
11
12
13
/* create the socket */
fd = socket();
 
/* connect and send out some data */
sendto(fd, buffer, buf_len, MSG_FASTOPEN, ...);
 
/* write more data */
send(fd, buf, size);
 
/* wait for some reply and read into a local buffer */ 
while ((bytes  = recv(fd, ...))) {
    ...
}

Server side

A common (old-fashion) TCP server is created with the following calls:

1
2
3
4
5
6
7
8
/* create the socket */
fd = socket();
 
/* connect and send out some data */
bind(fd, addr, addrlen);
 
/* this socket will listen for incoming connections */
listen(fd, backlog);

Adding TCP_FASTOPEN support to the server side code is very easy, the required changes are minimum, you only need to set a new socket option between bind(2) and listen(2):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/* a hint value for the Kernel */
int qlen = 5;
 
/* create the socket */
fd = socket();
 
/* bind the address */
bind(fd, addr, addrlen);
 
/* change the socket options to TCO_FASTOPEN */
setsockopt(sockfd, SOL_TCP, TCP_FASTOPEN, &qlen, sizeof(qlen));
 
/* this socket will listen for incoming connections */
listen(fd, backlog);

Required macros

Even you are running the latest Linux Kernel 3.8, you will face some problems as in most of the cases the required macro values for  TCP_FASTOPEN and MSG_FASTOPEN will not be available  at compile time. As a workaround you can include the following code in one of your header files:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/* 
 * A generic protection in case you include this 
 * from multiple files 
 */
#ifndef _KERNEL_FASTOPEN
#define _KERNEL_FASTOPEN
 
/* conditional define for TCP_FASTOPEN */
#ifndef TCP_FASTOPEN
#define TCP_FASTOPEN   23
#endif
 
/* conditional define for MSG_FASTOPEN */
#ifndef MSG_FASTOPEN
#define MSG_FASTOPEN   0x20000000
#endif
 
#endif

Enabling TCP_FASTOPEN in your Kernel

By default the TCP_FASTOPEN feature is not enabled at runtime (unless you instructed that in the sysctl.conf file). Before to test this new feature make sure is enabled with the following command:

# echo 1 > /proc/sys/net/ipv4/tcp_fastopen

If you try to use a client with TCP_FASTOPEN enabled, its mandatory that the server have this same option set in the listener socket, otherwise the client will faill at the connection phase (due to protocol mismatch).

For a TCP_FASTOPEN server, it does not matter if the client uses the new protocol or not, it will work anyways. So if you develop a TCP server you can give it a try adding a simple system call to add this feature. If your project is open source, feel free to use the header macros example provided above.

Btw, of course Monkey Web Server have added this feature recently in our development repository

References


February 03, 2013

Add Color to your Life, Add color to your Terminal OSX

Trabajar con un terminal en Linux es muy agradable dado a que es muy fácil diferenciar los archivos de las carpetas por sus colores, pero a la hora de abrir un Terminal en OS-X nos damos cuenta que esos colores no existen por lo que se hace fundamental agregar colores para hacer mas agradable el trabajo.
Terminal sin Colores

Lo siguiente es abrir el Terminal y escribir lo siguiente:

sudo nano bash_profile
A continuación copiamos y pegamos el siguiente texto:

export CLICOLOR=1
export LSCOLORS=GxFxCxDxBxegedabagaced
Luego para guardar los cambios Ctrl + O 

Reiniciamos el Terminal y vemos los cambios.

Ahora para entender un poco la asignación de colores en:

export LSCOLORS=GxFxCxDxBxegedabagaced
Asignación de colores:
a black
b red
c green
d brown
e blue
f magenta
g cyan
h light grey
A bold black, usually shows up as dark grey
B bold red
C bold green
D bold brown, usually shows up as yellow
E bold blue
F bold magenta
G bold cyan
H bold light grey; looks like bright white
x default foreground or background

Y el orden de los atributos:
1. directory
2. symbolic link
3. socket
4. pipe
5. executable
6. block special
7. character special
8. executable with setuid bit set
9. executable with setgid bit set
10. directory writable to others, with sticky bit
11. directory writable to others, without sticky bit


Si quieres personalizar los colores, por Ej: que tus directorios sean de color Azul, es tan solo reemplazar   el primer carácter por E.

export LSCOLORS=ExFxCxDxBxegedabagaced
Guardamos Ctrl + O, reiniciamos el terminal y veremos los cambios efectuados.
Terminal con los directorios de color Azul.

De esa manera puedes agregar y personalizar colores de un Terminal en OSX.

December 27, 2012

111

1111

testing gnome-blog

testing gnome-blog with gtk3 and gsettings.

gnome-blog home

:D

Portando gnome-blog a gtk3.

Como muchas otras aplicaciones, ésta también necesita ser migrada a GTK3. Y como en otras migraciones, también es necesario portar de gconf a gsettings. Es el caso de gnome-blog, que necesita de tal tarea. El bug es éste.

He realizado ya los cambios principales y la prueba es éste post (que espero que aparezca :D ).

Los cambios hechos son:

+ paso de pygtk a pygobject.

+ paso de gconf a gsettings. (creación de su esquema y eliminación de gconf)

+ pruebas con MetaWeblog Protocol. (el resto de los protocolos hay que testearlos)

Pendientes:

+ Drag and Drop para las imágenes.

+ Pruebas en otros equipos.

Unas pruebas… (http://avaldes.gnome.cl/?p=554)

Screenshot from 2012-12-27 15:52:27 Screenshot from 2012-12-27 15:54:49

a

aaaa aaaaaa aaaaaa aaaaaaaa

December 11, 2012

Tue 2012/Dec/11

  • The WebKitGTK+ hackfest has been ongoing for the last three days in the Igalia offices in the not-that-rainy city of A Coruña. We're over twenty people here and we've been hacking, discussing, and ranting over whatnot -- all to make sure that your browsing experience in the forthcoming years will be better than it has ever been. Here's a brief summary of what's been going on hitherto:

    P1020822

    There is, of course, much more going on and it's hard to keep track of the activity of these brave and energetic hackers. Yours truly has had a hard time distracting them from their relentless hacking in order to compile this report -- rest assured that there is probably much more happening between these four walls than what you have just read here. Nevertheless, we all want to thank the GNOME Foundation and all the sponsors who have made this gathering possible.

December 03, 2012

Día GNOME 2012

El pasado Sábado 27 de octubre, se llevó a cabo el Día GNOME 2012 en la ciudad de Curicó, Chile.

La asistencia fue espectacular y gracias al auspicio de la GNOME Foundation se pudo seguir con la costumbre de entregar a cada uno de los asistentes un pequeño almuerzo y así poder compartir entre todos los asistentes y continuar con el espíritu del Software Libre.

Mon 2012/Dec/03

  • Igalia is looking for a Free Software enthusiast living in the San Francisco Bay Area to work with us in the role of Sales Engineer. If you're reading this, chances are that I don't need to tell you who we are, what we do, how we do it, and what our core values are, nevertheless, if you want to know more, please read the job opening in our webpage.

    If you have specific inquiries don't hesitate to contact any of us through the usual channels!

November 18, 2012

Tiling rendering in Evince

One of the oldest bug in evince is the ability to zoom-in a large scales, like 1600% or more. This happens because the Cache that render the pages can only render full pages and rendering full pages at large scales eats a lot of memory. So some days ago I started to work on making the cache in evince "tile" aware, that is, to render only portions of a full page. I am happy to say that a preliminary result can be found in
my evince repo in github (github.com/jaliste/evince) in the wip/tiling_manager branch. Right now a lot of things still don't work, but tile rendering in single and continuous mode are working (not in dual mode yet)...



In the video above, you can see evince rendering a page using 256 tiles. The red tiles only appear while there is no rendered tile, and are just there to test the code.

Note that the rendering 256 tiles is quite slow because Poppler will reparse the pdf file each time we render a tile... So why bother? In fact, the video is only for ilustration, ideally evince will use tiles of the size of the screen or around that size, so you only get to see a few tiles at a time. The main advantage of this code is that now we can easily implement larger zoom modes. The next picture shows Evince running the Pdf 1.7 reference document at 1600% using 256 tiles for each page. Memory used by evince is around 150 M with this.



Unfortunately, there are a lot of things that still don't work...selections, dual_page mode, and other... Also since this is a main refactor/rework of the Cache code, it will need a lot of testing and review before it gets merged into master (as new code it is likely to have more bugs and we don't want to evince to be unstable) ... but we are right in the begining of the 3.7 cycle, so I hope I can get this merged into evince 3.8.


September 03, 2012

Mon 2012/Sep/03

  • On Friday I landed into Epiphany master the first iteration of a new feature that us the Igalia webkit hackers and the GNOME design team have been collaborating on for a while. We codename this feature the overview but, in its first iteration, you can think more of it as a speed dial for new pages, that will allow you to quickly jump to the pages you frequent more often when opening a new tab or window.

    This will certainly be the most prominent new feature of Epiphany in GNOME 3.6, and we believe you'll love it. Personally, I think that this is a huge usability improvement, but I'm much more excited about the possibilities this brings from here on. For 3.8, our plans are more ambitious, but I guess that we will talk more about it when the time is due.

February 10, 2012

That's why Windows Movie Maker is so popular

Bajar videos de Youtube en Linux, a pesar de haber miles y miles de aplicaciones, no encuentro absolutamente ninguna que me caliente lo suficiente (sic) como para usarla por un tiempo. Use abby en Ubuntu 11.04, pero debido a un grave problema mental de la aplicacion, dejo de funcionar para bajar videos de Youtube (LP #784724).

Despues de estar casi dos horas cepillando para poder bajar y convertir en MP4 dije el tipico "stop". Mas bien fue un "estas puro hueveando"

Volvamos a la consola. Necesitan cclive y umph.. No saquen ninguno de los repositorios de su distro, por que ambos estan quebrados. CClive desde fuente y Umph tambien.

En el caso de umph van a necesitar algunas bibliotecas de Perl (Getopt::ArgvFile, XML::DOM y Umph::Prompt, conseguibles en su CPAN favorito). Ambos deben andar.

Y, la receta magica. Yo al menos soy fan del canal de videos de ScienceOnline, sobre todo por que gastar 5 minutos en aprender algo, no es perder el tiempo ;-) Asi que para bajar el feed entero... (si, completo)


$ umph -a -t u ScienceOnline | cclive

Antes, claro, dense una vuelta para ver los formatos soportados. Usen esto para mostrar los soportados del video:


$ cclive --query-formats http://www.youtube.com/watch?v=XhEiz-2cS8k
fmt05_240p|fmt18_360p|fmt34_360p|fmt35_480p|fmt43_360p|fmt44_480p : http://www.youtube.com/watch?v=XhEiz-2cS8k

El formato de mas de la derecha es 480p.

Ahora, corrigiendo el primer llamado...


$ umph -a -t u ScienceOnline | cclive -f fmt44_480p

La hombria no me llego a tanto como para convertirlos a MP4 dentro de la misma linea.

Bitch-ass motherfucking update!


$ umph -a -t u ScienceOnline | cclive -f fmt44_480p --exec "ffmpeg -i '%f' '%f.mp4'"

No es la gran cosa, pero siento que esto se esta convirtiendo cada vez mas en rocket science.
A todo esto, algun editor de video en Linux similar a WMM? Openshot me sirve, pero agregar un texto SIN TENER QUE USAR EL MALDITO BLENDER...digamos que no es de mi agrado.

February 02, 2012

Just something that I may not forget

Handbrake-CLI. You're awesome.

--start-at duration:150 --stop-at duration:300

O bien

--start-at frame:2000 --stop-at frame:5000

Y mi receta personal:

HandBrakeCLI -e x264  -b 2500  -a 1 -E faac -B 160 -R Auto -5 -2  -D 0.0 \
-f mp4 -m -x rc-lookahead=50:ref=1:bframes=0:subme=6:trellis=0 \
-i inputfile.fmt -o file.avi

December 28, 2011

This is the most strange ransom note I've ever done...

Disculpen que mande este post desde Paranal, pero desafortunadamente (duh) no estoy en Santiago para hacer efectivo esto de forma inmediata.


Exhibit A : Nerdom

Bueh, para los que no estan enterados, me llego de sorpresa (si, claro) una PS3 Slim 160 GB. Algo mas que agregar a mi nerdom.

La cosa es la siguiente : ya tengo (mas de una). Asi que mi decision es rematarla. Podria cobrar lo que sale una de esas nueva (esta esta en near-perfect-mint status, o sea, salio de la caja un par de veces), o bien cambiarla por algun item/itemes de similar equivalencia monetaria.

Los interesados, email a <bidps3 at codemonkey.cl> dando su oferta. O en el quebrado sistema de comments que tengo en la pagina.

Y apurense, ya hay interesados...


I saved it from his cold dead hands

November 17, 2011

Expolibre 2011

Como ya es tradicional, GNOME se hará presente en este importante evento de la región del Maule.

El sitio del evento es : http://www.expolibre.cl/index.php

October 12, 2011

About a trip to Canada, or Montreal Summit

So in the last two weeks I have been for the first time in Canada. I was first some days at the Banff Centre, which is awesome, and spent last weekend in Montreal for the GNOME Montreal Summit.

This was my first international GNOME (no)conference, and it was great to finally meet people like Colin, Owen, Ryan, Cosimo, Karen, etc.

I discussed and asked a lot of questions to Ryan, Cosimo and Colin about some ideas of the future of Evince related technologies. For instance, we agreed with Cosimo that it probably makes sense to have a evince-based plugin for your browser (finally!!) because it could be better for the workflow where you don't
want to download the document (and you don't need to). I also asked Ryan and Colin for ways of making evince safer by splitting the rendering code into a sandboxed process. And I asked many other things with cosimo about evince, gtk, css.

I also participated in some sessions like the jhbuild session, the GSoC session, and I even organized a short session about online metadata for our desktop. Although not many people were excited about my ideas, it was nevertheless great to have the feedback of many talented hackers in GNOME.

I also discussed with Andreas the idea of getting some cool Laptop Skins with GNOME designs, so hopefully he will get some cool designs soon, and with Marina I discussed about Women outreach and how the gnome-chile community is working to promote GNOME and all these programs.


Overall, it was really great for me to meet all the prople, and I thank all the people i met for all their feedback, surely I have now a lot of ideas about how to improve evince... if only i would have more time. The GNOME Foundation for sponsornig my trip and to an anonymous friend for letting me crash at his couch on Montreal.

Time to go into the plain.... some 10 hours ahead to be back in a sunny Santiago again

October 06, 2011

El mundo sin Steve Jobs

Y llegó el día que no queríamos que llegara, se ha ido Steve Jobs. Para muchos es un genio, y para otros un tirano, lo que no queda en duda es su aporte a la vida moderna: Tienes que vivir en una caverna para poder decir que la influencia de Steve no afecta tu vida diaria.

Puede no ser el inventor de muchas cosas, pero esas invenciones probablemente estarían perdidas en un laboratorio o hubiesen sido una curiosidad tecnológica sin la visión y el liderazgo de Steve. Se necesita alguien que sea capaz de alinear a los expertos técnicos y comerciales – muchas veces rock stars que son muy difíciles de manejar – sólo así puedes sacar adelante productos y conceptos como los que hoy atribuimos a Steve.

A modo de homenaje, recordemos cómo era o sería el mundo sin Steve Jobs.

  • Antes de Apple los computadores estaban destinados a hacer cálculos balísticos o financieros, costaban una fortuna y se necesitaban expertos para manejarlos.  La gente normal “no necesitaba computadores”, ya que no había nada que hacer con ellos.  Steve Jobs creía que lo computadores podían darle poder a la gente normal, y afortunadamente fue capaz de convencer al genio de Steve Wozniak de que esa idea tenía sentido.
  • Antes de Apple los computadores se manejaban con comandos crípticos, todo se realizaba por medio del texto, tanto las instrucciones que se le daban al computador, como la propia respuesta del computador a esas instrucciones.  Steve conoció en los laboratorios de Xerox el concepto de la interfaz gráfica y el ratón, el problema era hacer que esa tecnología funcionara en las limitadas capacidades de los computadores personales que Apple podía producir, a un costo razonable.

Procesador de Texto WordStar sobre CP/M

  • Antes de Apple la música digital sólo se podía obtener de forma ilegal.  Los músicos estaban condenados a ser pirateados o seguir siendo abusados por los sellos discográficos.  iTunes demostró que había un mercado para la distribución de música en formato digital, y que la red no servía sólo para piratear.  En poco tiempo se convirtió en el primer canal de distribución de la música, dejando atrás a los medios tradicionales.
  • Antes de Apple tenías que seleccionar qué musica llevabas contigo, a menos que quisieras andar con un bolsito en tu mochila.  Apple logró poner horas y horas de música en tu bolsillo, incluso en el bolsillo más pequeño de tu pantalón con el iPod Nano.  Como si esto fuera poco, incorporó una sencilla interfaz de usuario basada en una ruedita tactil desde donde puedes realizar todas las operaciones que necesita el dispositivo.
  • Antes de Apple la producción musical estaba estrictamente reservada a grandes estudios, con equipos carísimos basados en hardware.  Si bien Apple no inventó el concepto, ni la tecnología directamente, tenía un computador y un sistema operativo suficientemente fiable y poderoso para que empresas como Digidesign creyeran en que los computadores podían ayudar a tareas de edición, grabación, mezcla y postproducción musical.  Gracias a esta simbiosis, hoy puedes tener un estudio musical en tu casa.

Reproductor de MP3 RIO

  • Antes de Apple los teléfonos inteligentes tenían muchos botones, carecían de aplicaciones y servían para ver planillas de cálculo o leer correos electrónicos.  Se manejaban con un lapiz y su interfaz de usuario imitaba a la interfaz de un sistema de escritorio, con menú de inicio incluido.  Hoy todo smartphone trata de imitar al iPhone de Apple de alguna forma, ya sea por su pantalla táctil, su único botón o su interfaz gráfica basada en lanzadores de aplicaciones que corren a pantalla completa.
  • Antes de Apple los desarrolladores de software necesitaban una fuerte inversión para llevar sus productos al mercado, si es que lograban obtener algo de notoriedad.  Por otra parte los usuarios tenían que salir a buscar el software “a la calle”, sin que nadie asegurara la calidad del software disponible.  Junto con el iPhone, no sólo se creó un sistema operativo que hoy es un referente respecto al software base y ambiente que se debe proveer a los desarrolladores, sino que también achicó la brecha existente entre éstos y sus usuarios.  El AppStore hizo millonarios a muchos, permitió que la distribución de las aplicaciones se democratizara, y al mismo tiempo permitió que los usuarios lograran tener acceso a software de calidad en un solo lugar.  Hoy todas las compañías tratan de tener su propio AppStore.

IPaq - Smartphone de HP

  • Antes de Apple la televisión sólo servía para… ver televisión.  Aunque nunca ha sido un éxito, el AppleTV abrió las puertas para ver la televisión de otra forma.  AppleTV convirtió a los televisores en un dispositivo más conectado a Internet.  Pese a sus problemas de comercialización, y desencanto en la propia compañía, hoy los SmartTV son un lejano descendiente de este concepto.
  • Antes de Apple los tablets eran unos computadores que no tenían mayor gracia que permitir tomar notas con un lapiz stylus.  Se trataba de notebooks con un teclado escondido, en donde el sistema operativo y su interfaz eran iguales a lo que podemos encontrar en los escritorios.  El iPad de Apple demostró que esa dirección estaba equivocada, y no se trataba simplemente de un notebook (o netbook) sin teclado, sino que se trataba de un computador con raza propia.  Eliminó el stylus, y adaptó la interfaz de usuario para ser usada sólo con los dedos.  Al igual que con el iPhone, hoy todos los tablets se quieren parecer al iPad, pero ninguno cuenta con el nivel de terminación y el ecosistema de aplicaciones que distingue al iPad.

Sketch de Mickey Mouse

  • Antes de Apple el navegador más usado en el mundo era el nefasto Internet Explorer.  Si bien Mozilla logró que los más techies impulsaran una alternativa de calidad en el mundo de los navegadores, fue Apple quien tomó KHTML (KDE) y lo convirtió en una competencia en el mundo del usuario común y corriente al incorporarlo en sus productos estrella a través de Safari.  Con esta incorporación se le terminó la excusa a los desarrolladores de que sólo valía la pena probar que sus creaciones sólo funcionaran en Internet Explorer.
  • Antes de Apple, el sistema operativo Unix era sólo para privilegiados expertos.  Aunque en Linux se han hecho intentos por llevar esta tecnología a los usuarios “de a pie”, fue Mac OSX el que logró construir todo lo que hacía falta para llevar este sistema al público. Sus distintas tecnologías que agregan valor a Unix y lo convierten en un producto de lujo, han sido imitadas tanto por Linux como por Windows con años de retraso.
  • Antes de Pixar – otra de las empresas con el sello de Steve – se necesitaban grandes ejércitos de dibujantes para crear películas animadas.  Steve ayudó a John Lasseter a convertir el sueño del cine animado por computadores en una realidad.  Lasseter despreciado por Disney y más tarde abandonado por George Lucas tuvo la suerte de encontrar en Steve a alguien quien creía que el mundo del cine podía ser distinto, así nació Toy Story y el cine cambió para siempre.

Seguramente se me quedaron cosas en el tintero, pero con lo expuesto ya es suficiente para entender el peso de Steve Jobs en nuestra vida, de alguna forma trajo el futuro a nuestro presente.

Te extrañaremos Steve.

 

September 30, 2011

Encuentro Linux y Dia GNOME 2011

Después de un largo tiempo sin postear en mi querido y olvidado Blog, Este año se realiza el Encuentro Linux 2011 el día 20 y 21 de octubre en la universidad Austral de Chile en Puerto Montt. Este evento esta organizado por el grupo de usuario de Linux Puerto Montt GULIPM y la Escuela de Ingeniería en Computación que también se suma en esta organización. Ademas que hay que mencionar que el Este Encuentro Linux cuenta con una frase que salio de un concurso abierto.

"Naciendo Libres, Aprendiendo en Comunidad"

Sin duda al igual que en anteriores Encuentros tenemos expositores de Gran trayectoria en el mundo del Pinguino Toda la Información la puedes obtener en http://2011.encuentrolinux.cl

Dia GNOME 2011

Como ya es tradición el Día GNOME se realizara dentro del macro del Encuentro Linux el Día 22 de Octubre para asistir tan solo te tienes que registrar en http://registro.gnome.cl Ahora si quieres difundir el Día GNOME puedes usar los banners disponibles.


Siéntete Libre de poder usar, modificar o difundir este evento en tu Blog, wiki, Twitter, Facebook etc. Puedes encontrar el SVG. Aqui Nos vemos en Octubre en Puerto Montt.

September 27, 2011

Sorry for the crossposting

Efectivamente. Volvemos al ciclo de Charlas del 2011 (algo tarde, no?). Esta vez, hablando de Software Libre, estrellas, computadores que no quieren encender y otras historias.

Apuntense! Para el nodo Santiago (donde estare), sera el Sábado 1 de octubre de 2011, en Universidad Central Sede Santa Isabel, Santa Isabel 1186, de 10:00 am a 19:00 hrs (o hasta que nos echen).

Los veo alla.

September 21, 2011

Día GNOME 2011

http://projects.gnome.org/diagnome/

September 17, 2011

I am going to the Montreal Summit

This is just a quick note to say that I am going to the Montreal GNOME Summit. Contrary that for many the move from Boston to Montreal was bad, I just happened to be in Canada on the same dates, so for me it was a lucky move! I am looking forward to meet some GNOME devs for the first time on live.


Greets

Feeds