Páginas

jueves, 27 de diciembre de 2012

How to run Chromium v26 on Ubuntu

As you would know, since several months ago there's no official Chromium Nightly builds PPA, but since last week was enabled the support for native DataChannels on Chrome Canary (yeah!!! :-D ) I was decided to test it whatever it cost.

To do it, here we have two options: Canary versions only available for Windows, or hack a way to get to run a Nightly release on Linux. The Canary was fairly easy, just reboot on my dust-filled Windows partition, but to test and debug DataChannels-polyfill was a PITA thanks to Windows files protection idiosyncrasy so this morning I've managed to achieve the second method... and won :-D

First of all, we need to get a Nightly build. We can download or compile it by ourself, but I find fairly better to use this script that also makes a backup of previous versions, a command called chromium-cont to distinguish it from the stable one, and create a shortcut on the apps menu. Just a piece of cake. The problem here is that it's a vanilla compilation of Chromium, so it will try to use our default profile and if we have a previous version of Chromium running, it will just open a new window tab on it, so we'll need to launch it with a flag telling him a new folder where to store his config info. A good one would be ~/.config/chromium-cont, to be on pair with Chromium and Google Chrome config folders:
--user-data-dir=~/.config/chromium-cont
To do this just add the flag when launching from command line, or to add it to the shortcut right-click on the apps menu, select "Edit menus" and navigate up to "Internet > Chromium Updated" and set it there. Another option would be to just change the chromium-cont symlink to a full-fledged shell script that also pass automatically the selected config folder (more or less what Chrome Canary does) so it will be used everywhere is being launched, but I'll leave this as an exercise for the reader :-)

Finally, to enable native DataChannels on it you will have to add a --enable-data-channels flag when launching it, or better put on the browser navigation bar "about://flags", scroll down to the bottom of the page and click on "Enable RTCDataChannel". Now you have a full fledged Chromium v26 ready to start experimenting with native DataChannels directly from Linux!!! :-D

domingo, 23 de diciembre de 2012

Better... impossible

Now that's official I can be able to announce it.

What was the best I expected I could achieve with ShareIt!? That it could get a good reception on the community and some social repercussions.
What would be better? That it got taken in account for two degree and a doctorate thesis.
Better than that? It was referenced on a book.
Maybe the best?...

...a job offer (almost) directly related with it :-)

Merry Chistmas and Happy New Year to all!!! :-D

viernes, 21 de diciembre de 2012

ShareIt! 1.0 "Armageddon"

Some centuries ago some guys from central America supposed today would be a great day (you know, with Sun in the sky and singing birds all the way :-P ), so being today the End of the World, why don't try to collaborate a little bit on it on a so-signed date? ;-)

This is the reason why after an infernal week (literally, 6 exams in just four days... :-S ), some adjust on my scheudle and too much work coding up to late I'm so proud to announce that, finally, I've released the first stable, usable and feature complete (up to some degree) version of ShareIt!, the first server-less pure client-side Javascript and HTML5 P2P application in the world build over WebRTC DataChannels, that sweetly I've decided to nickname it "Armageddon" to remember this marvelous day (hey, at first I decided to name it "Doom's Day", but "Armageddon" starts by "A" that's fairly better for a first release :-P ).

So here you have it, with improved control on the transference code and an upgraded user interface. Finally it's working using MD5 for the hashes instead of TTH but it was just a lack of time to do it (basically, I will have to build my own implementation from scratch...) and currently there's no search support, but I have finished to add documentation on the code and hope to do this improvements soon and also some other cool ones like a headless daemon and a mobile version ;-) Obviously, all the code is on my GitHub repository, so go ahead, fork it, send me your patches and start using it with your colleages. Let's begin the party! :-D

martes, 18 de diciembre de 2012

The book is published!

I have just get noticed that the second edition of the book "HTML5 for Masterminds" by J.D. Gauchat have just been published on Amazon and will be ready on paper (also in spanish! :-D ) in some weeks, but the best part (at least for me) is the next paragraph:
IMPORTANT: At the time of writing, the specification for data channels is under development, and this part of the API was not yet implemented in browsers. To test the last example, we used a polyfill developed by Jesús Leganés Combarro (pirannafs.blogspot.com) and available at https://github.com/piranna/DataChannel-polyfill. This script implements data channels using its own Websocket server. For this reason, the script of Listing 24-12 might have to be modified to work with the official implementation. Please check our website for updates.
I'm happy :-)

jueves, 6 de diciembre de 2012

I have competence!

It was really a surprise when on the ShareIt! commits network graph I see a new history line under mine. Who is that guy? What's doing? And why didn't tell me he is working on my code?

QuickShare is a little web page whose only purpose is just share files between two peers though an intermediate server using websockets in a similar way to how PasteBin works, that it's exactly the idea I had when started to build ShareIt! up to the most minimal details before knowing the existence of the WebRTC technology and changed it to a full fledged P2P filesharing application. The truth is that is not using my code at all... it's a fork done directly from the same commit of DirtyShare where I started ShareIt! so our projects are somewhat siblings :-P

But hey, at least I would be able to use its terms of use as basis for my own ones... :-D

sábado, 1 de diciembre de 2012

A game changer

The last week I told you about the crazy weekend I had with the ReatTimeWeb conference and the 3DS seminary, but also I promised you to talk about some ideas they give me related to the signalling problem. Ok, here we go: they worked :-D

The problem is simple, althought not easy to solve (someone told me I touched the Holy Grail of Internet... :-P ): a web browser on a LAN can go and surf over Internet without problems, since it's a request from the internal network to a server the bigger Internet, there's no mistery here. Since this way every browser can access to Internet, they could be able to be reached on the other way from one browser to another, but how to do this without using a server, or at least without deploying a custom one, just using currently available Internet technologies?

On a first point, I though about SIP, and specially SIP-over-WebSockets, a specification to use WebSockets as transport layer for SIP communications instead of plain BSD sockets (and whose author I was able to meet and talk on person on the conference :-) ). I worked hard here until I got noticed by a bad point: public SIP servers require to have a registered account somewhere to allow to connect to them, what breaks annonimity in a very bad way (and having the user to create a new random account on every page reload it's all except user friendly...). Thinking about it, I took a look at XMPP (Jabber), since being a from-the-people builded protocol it would probably to have an annonimous session option... and yes, it has it, but only on the EJabberD server implementation and any of the public servers has it enabled. End road.

Being so frustated by not being able to send a little piece of text from one end to another one without a server or a previously created PeerConnection (who give us up to the chicken-or-the-egg problem...) and not being able to use directly the STUN servers (PeerConnection manage the connection creation just doing what I wanted to do, but the specification doesn't give access to this low-level functionality) I decided to wait until the conference, where they gave me a little proposition about how to solve it, although I was a little reluctant about it, and in fact I believe they didn't hope it would work flawlessly: PubNub.

PubNub is a web service that allow to publish messages to a group of peers subscribed to a channel. It's say:   you send a message, and it's received by everyone it's listening. It's a little bit like killing a fly with a gun since the signalling message is sent to everyone is connected, but checking by hand that the message is for you the problem is easy to solve and also it has several advantages:

  1. It's not a dedicated server, it's a public server, so it's dificult to break it down (there would be too much affected...)
  2. there are other alternatives, and also it's being developed a public specification
  3. the free accounts have a very restrictive limit about the number of connected peers, what helps to focus on it as a bootstrap protocol and change inmediatelly on a DataChannels based one, increaing the network density just as I designed originally (the last week I was too much focused thinking about using the signalling channel for everything...)
But also it has another good point: since I have been testing so much protocols these day and thinking about to be able to use several of them at a time since no one gave me the flexibility and annonimity I wanted, the fact is that I ended developing a SignalingManager that could be able to abstract the signalling mechanism and adding a new one was just a matter of build a little class, so I did a new one for PubNub (after registering me as a developer on their page), launched the webapp... and it worked, period. Just like magic the both peers were talking though PubNub without a dedicated server... and also from two different host domains!!! :-D This means that you can download the webapp from different hosting and all of them could be able to communicate, allowing more heterogenety: if one of them gets down, you just need to navigate to another one and keep sharing :-) I need to investigate about how to share IndexedDB between the different domains in case of problems, but it seems will be something difficult to achieve and will only be able to show "backup cache" link so you can import it on another one... :-/

But these are only the good news? No, there's another one, maybe more little, but with greater consecuences: yesterday I was helping to Arindra Das over Skype with her problems with ShareIt! (really, he found a bug :-P ) and asked to him to share something so I could be able to make some test on my side, and the fact was that "magically" a PDF was shared with me from Findland to Spain. Yes: ShareIt! WORKS!!! :-D Having problems previously on some demos and not able to test it before between machines (just my main computer and my parent's one, both on my home LAN), it was a great surprise to see that it worked on the wild Internet, so adding this the "server-less" signalling thanks to PubNub, when we got native DataChannels on the browsers this project will be able to take flight :-D Let's hope they will be ready for New Year Eve... ;-)

lunes, 26 de noviembre de 2012

The longest journey: the movie

One thing that I forgot to mention on my previous post related about my last freaking awesome weekend was the fact that I have proves about it happened, so like they say in Facebook "if there's no picture it didn't happen", here it's the video about my WebRTC DataChannels & ShareIt! project I did the last friday in front of 75 persons on the RealTimeWeb conference (sorry, audio in spanish... Having only about three minutes you don't have too much time to think in english and you can only hope to talk as fast as possible... :-P).



If you can't be able to see the video you can download it on MP4 or WebM.

Just to say that althoug in the video it "doesn't work" later I investigated and was a bug of Chrome v25 unstable (obviusly... ¬¬) and just closing the tabs and openning them again it worked the second time (now I need a new video to show that it happened... :-P )

Slides are availables on the RealTimeWeb site and also the ShareIt! repository.

The longest journey

The last 72 hours have been one of the longest and most full-filled weekends I have had ever.

First of all, the friday I did my first wide-spread demo and presentation of ShareIt! (if we don't take in account the little one that I did some weeks ago for the Python Madrid guys) at the RealTimeWeb conference here at Madrid in front of 75 persons (the biggest public I have had in a presentation). In short: an awesome success :-D It was just a little and fast presentation because the organization run out of time and also I needed to go the the 3 Day Startup later, but the fact is that in less of 3 minutes I did the presentation, showed a demo, and the public exploded in ovations :-D (the fact that being the (almost?) only one in all the world working in some really awesome high-edge technology just because it's not ready yet would be the cause... :-P) Also, the fact that I got some propositions from the UPM teachers to work on their investigation projects related with WebRTC and they also gave me some good ideas to solve the signaling problem are some really great news too, by the way... :-P Keep listening... ;-)

But if this was not enough, as I have just say I needed to go the the 3DS so didn't be able to participate on the hackathon of the afternoon (with some iPad-mini as prices, just some kind of deviavious temptation after my Galaxy Tab I won on the CUSL two years ago with PirannaFS was stolen the last week... ¬¬). What to say about the 3DS? Crazy, period. It was about just like a small-sized CampusParty but without my sleep sack under the table. Some of the projects were really interesting and in fact I needed to flip a coin in the last moment just to select between two of them about were to work (maybe with some telekinetics since It was complementary to my Priorities project... :-P), and the fact is that in the last three days I have work more hours than in a normal job week and spend more energies than in a month :-P Add to this the fact about going to bed not before of 4 o'clock and waking-up at 8:00 to be early in the morning on the event (I didn't want to do it, by finally they convinced me to take some beers all the nights... :-P) and now you would understand why this morning I seems a brain-less zombie :-P The bad news is that it was a one-shoot, so I will not be able to use the experience and propose the next year a better project (I was thinking about a "producer for genious" company to take out all the burocrazy and mind-disturbing things and let "genious" to concentrate on their work in a similar way movies producers take in account all the boring details and let the movies directors to do the magic) so maybe this is something I would change about it... :-( In any case, if I can, I'll repeat the experience :-D

But on the personal area the best news would be that after four years working on the private sector and forced to "back to the basis" (no job, no money and just have part-time university classes and being full-time freaking with my geek personal projects :-P) I'm remembering why I wanted to work on computers programming and how I spected my live would be, and yes, THIS is what I wanted (or at least is on the good way :-D). Maybe add some romantics and action-packet and this is the kind of blockbuster I would like to live ;-)

So in few words... in the last four days I would have sleep about no more than 16 or 20 hours :-P

viernes, 16 de noviembre de 2012

FirefoxOS and HTML5 myths

Recently I have had some discussions and mocks regarding being FirefoxOS as the platform of the future (they was the ones that joke about me being an Apple fanboy and now they got crazy with the Nexus 4 availability issues like Justin Bieber fans... :-P ), so this links would be useful to get the things clear: first steps about hacking on FirefoxOS and some HTML5 Myths unveiled. Just a piece of cake... :-)

Hosting anywhere

During this week I have got the good news that ShareIt! will be included as part of two PhD thesis (woah!!!) that it's something several light years far away about what I would consider a success (Stefan Dühring and Arindra Das, truly thanks you so much! :-D ) with the exception of an e-mail with a job offer from Google :-P

But in both cases they had problems to deploy and test the code locally because they didn't finish to get the concept of being a pure client-side webapp, but at the same time requiring a handshake signaling server and a DataChannels backend server, so both asked me about a non-existent node.js server that hosted and served the app (I got problems while developing ShareIt! and DataChannel-polyfill to change my mind from a client-server way of thinking to a pure distributed one, and the telling the truth the WebRTC specification doesn't help about this for the non-specialized people...). I got a little bit obsesed about this point and to prove that being a pure client side webapp there's no necesity of a hosting server (just a simple static file web server), inspired by a recent idea I got about using DropBox to increase speed of downloads (enabling more host peers) and as backup of peers transfer, I decided to retake the fact that DropBox can be used as a basic static web server and improve the support for it. This included change all external references to use secure connections since DropBox serve the files through a SSL enabled connection, and if the content is not secure the web browsers would complain to protect the user (and that's ugly). On the other hand this allowed to encrypt all the communications so it's a win-win situation :-)

But this was not enough, I needed to show more versatility, and got it: I found this blog entry that explain in an almost step-by-step way how to explote DropBox and GitHub as free static pages web servers, and specially for deploiment of webapps. Just a sweet :-)

So here we are, currently I'm able to serve and host ShareIt! on three different web services, all directly availables on the web and interoperable between them: 5Apps, DropBox and unexpectedly GitHub, and also it's installable as browser extension. Add to this the fact that Firefox 18 "Alder" now start to have native support for DataChannels and WebKit already has it (Chrome v25 will have to wait a little bit more), and we are almost up to a point where ShareIt! will be impossible to take down (I hope that on the RealTimeWeb hackathon I would be able to get a way to drop-off the handshake server and reach the Holy Grail of Internet... :-P).

Let's the revolution begin!!! :-D

jueves, 8 de noviembre de 2012

Scream if you wanna go faster

PageSpeed Insights is a webpage that allow to check the performance of a web page (specially about load time and bandwidth) both for desktop and mobile, but also give suggestions to improve it solving some typical errors, and also there are extensions for Firefox and Chrome to run it locally :-) At this moment it give a 73% value for desktop and 63% for mobile, I'll try later to make Google scream a little bit more (pun intended ;-) ).

viernes, 19 de octubre de 2012

Sleeping with the enemy

Today I have been at the monthly meeting of the Python Madrid group where I did a keynote about HTML5 and what benefits can offer to the Python web developers, and also showed ShareIt! as a proof of the technology potential. Althought some technical problems with the projector, finally I was able to show it and was a sucess :-)

They liked so much the idea behind of ShareIt! and were very interested on the technology behind it, specially about how I'm using WebSockets for the DataChannel-polyfill and if the final native implementations will support high estress use like the one ShareIt will so or maybe bigger ones (I believe someone is thinking about highly masive videochats... :-D ) but also they asked me a very interesting question that I didn't thought about: the most important building blocks on ShareIt! are annonimity and confidentiality, being the users identified by a random UID at load and with encrypted communications (both WebSockets with TLS and DataChannels by the specification), but since I'm not a security expert, there is an important security hole regarding to annonimity, so it's critical: to be able to do the PeerConnection, you need to transfer your SDP to the other peer to be able to do the connection, but the fact is that it has your public IP on the origin field (just the ID used by DataChannel-polyfill, by the way...), so this way the other end can be able to connect to you... but also know where you are. And it's done both ways. If at one of the ends there is a men in black listening (here at Spain we have La Innombrable, that it's scarier) and send him your shared files list, you have a problem.

They suggested me to use some type of friends white list based on public key for authenticity of the other pair, but since you can connect to anyone to fetch the data in a distributed way and not end having a lot of limited, private networks, this in unfeasable. Anyway, I got the idea banging on my head and think found a solution: just ask for authentification when you query a files list. This way, since for tranfering chunks you look for the files by their hash, you don't know what is being requested except if you have already the file with that hash, so you'll need to ask for all the combinations of the hash (on Tiger TTH, 2^192 combinations, bigger than the ZFS address space), and something similar would happen if you do a fulltext search over the network, so it's impracticable. The only attack point would be ask directly to a specific peer for its files list, and since this is something that you'll not do too much frequently (you want to fetch a file, doesn't matter where he comes), this can be easily filtered only allowing to do it if you have exchange a public key with the other peer (something you should do only if you know who is at the other end...), so you know the request is legit and also you can send the files list data cyphered with that key. Easy and unobstrusive :-)

Another option would be just to remove entirelly the files list request mechanism and only allow searching for files. This would limit the functionality of the protocol, but would be fairly more simple and secure, so maybe it's a good option for a future version...

sábado, 13 de octubre de 2012

How to develop a SVG logo

Although some days later, here you have the promised tutorial about how I did the ShareIt! logo fully with free software :-)

First of all, I wanted to develop it fully with Inkscape using an own font developed with FontForge like it's explained on this Inkscape tutorial (that showing an style similar to the one I wanted, it was a good starting point), but being a totally noob with this app, I decided to start with a vectorial app whom I'm more familiar: Dia. With it I could be able to anchor the lines to the grid so it's was faily easier to develop the text.

I created the grid on the left as a guide for the letters... Working with a 800% zoom becames the background grid a little useless :-P
Originally I only wanted to create the font to export it and follow the tutorial as originally intended, but being a vectorial app, why I would like to do this if at the end I'll convert it back to vectorial paths? It was no sense, so finally I exported it directly as SVG and imported it on Inkscape. Dia exported it as a lot of independent paths and objects so first I needed to convert all the objects to paths (select all the objects and later Path > Object to path) and later join all the independent paths ends between them to create some closed ones (select one path, click on the end node, select the other path and the other end node holding the shift key and later join the selected nodes on the toolbar).

With the 'a', the 'r' and the 'e' characters it needed one more step: use booleans operations with the objects. This way I would add the vertical line to the body of the 'a' and the vertical line to the head of the 'r' (select both paths and later Path > Union), and later remove the central hole of the 'a' and the 'e' (select the character path, later the hole one and finally apply Path > Difference). This way I have a single path for each characted (except the exclamation, that I just only group them because I wanted to do some independent effects).


Finally having created the text characters as paths, it was time to apply the color and the effects. The downside is that the tutorial of the beginning was not so specified as wanted (and in fact a lot of the comments were requesting a video tutorial), so looking on YouTube I found this two step-by-step ones about how to get the same effect :-)


I couldn't be able to apply the PathDinamic Offset but could be able to solve it with Path > Increase instead. Basically, it's just to select all the objects and apply the fill color that you want and remove the path color, and later duplicate the objects (Second click > Duplicate, they will appear the new ones over the originals so don't click anywhere or you'll lost the focus), move the duplicated ones to the bottom (Object > Move to the bottom), change the fill color and increase them. Et voilá! You have just created a text offset :-D Now repeat it with a different color, without the bar of the exclamation and a little bigger and you have the final result :-)


Just as a side note, say that being able to see and edit the XML tree directly on Inkscape it's VERY useful, not only to see the hierarchy of the objects but also to be able to clean them up if you have hidden duplicates or to change the nodes IDs to something with more sense that just a name (I just put the character names for each one to identify them easily).

As a finally drawback of Inkscape, the fact that it store the working area status data inside the SVG, so each time you open a SVG file it gets modified, but being an illness that also happen on Flash and other applications that don't have an independent workplace concept, I think it should be so important...

domingo, 7 de octubre de 2012

Class 101

Some days ago I finally was able to finish the problems that I got with DataChannel-polyfill and published a version using them so the guys from the WebP2P group could be able to test it. The fact was that regarding this, the first feedback I received* was about don't know how to use it, so I put my "plain user hat" on and got where was the problem.

Althought I was developing ShareIt! with usability and accesibility in mind, the fact was that being at a development stage I was thinking more about the developer (the guy that will go to GitHub and download the code) instead of the final user or just the curious, so the demo that I have uploaded to 5Apps didn't make a sense to them. This is the reason why in the last days I have been developing a "Start here" div that will be showed when there's no active sharings or downloads, with the tabs disabled and a big arrow pointing to the main menu, and also some links to the starting points of the app. This way also it could be used as a presentation page, so finally I developed the app logo and favicon (just a pretext to learn to use Inkscape... :-P), so now the app at 5Apps will looks prettier with a custom logo instead of the default one :-)

Tomorrow I'll put a little tutorial about how I did it ;-)

* the second one was about requesting collaborate in the project to integrate it in AtomOS as a FTP-like communications layer :-)

sábado, 6 de octubre de 2012

Si pagas en cacahuetes tendras monos


Oferta de trabajo que he recibido en el correo de una consultora:

Urge Programador C/unix
...
Requisitos: OBLIGATORIO:
- Experiencia REAL en lenguaje C sobre Unix (al menos 6 meses).
Requisitos deseados:
- Experiencia trabajando alguna de las siguientes tecnologías: C++, ProC, SQL contra Oracle, Tuxedo, Webservices.
...
Salario mínimo: 12.000 Euro
Salario máximo: 18.000 Euro
...
Por favor ,necesitamos perfiles ADECUADOS al salario de la oferta.

¿Mande? ¿"Urge" un programador C con experiencia en ProC, Tuxedo y Oracle (que siendo algo tan especializado y que requiere de alguien experto entiendo que si les corre prisa es porque se les ha echado el tiempo encima por una mala gestion) y aun asi solo ofrecen como maximo 18k y piden "por favor" que los perfiles sean "adecuados" al salario de la oferta?

Lo dicho: si pagas en cacahuetes tendras monos ¬¬

viernes, 5 de octubre de 2012

ShareIt! working over DataChannel-polyfill


I could be able to finish it two days ago (after an entire week -and weekend- going to sleep after 3:00 AM :-P) but I have been busy this two days with university. Anyway, I have finished to debug the code and now ShareIt! is using DataChannel-polyfill to do the communications between the peers. Also, I needed to develop an IndexedDB polyfill to by-pass the Chrome bug related to storing Blob objects, so there's no persistence but I could be able to continue with the experiments :-)

The only drawback I have seen is that communications were really slow (about 25-30 seconds just for a 500KB image) until I got on the fact i have a 10Mbps/1Mbps ADSL line, so I tested it using a DataChannel-polyfill backend server on localhost and it downloaded in just 2 seconds, so maybe it was a problem with my limited line upload. The good part is that for the tests i used Chrome SpeedTracer and didn't look any unusual (except comunication peaks were about each 5 seconds), so the app is very responsible :-) Also i have developed the code on a library way, so it could be exported to other projects (althought previously it needs some documentation and port the original, simple interface to it as a proof-of-concept).

Finally, you can test it (currently only on Chrome, DataChannel-polyfill is giving me problems on Firefox) at http://shareit.piranna.5apps.com, running against a handshake server and a datachannel backend server that I have hosted on two Nodejitsu testing sandboxes.

And obviously, you can get the code on GitHub :-D Things were I would need some help from now are related with the Kademlia implementation for searches (I was thinking about using KadOH), and file hashes where I would like to use Tiger TTH, but currently there's no JavaScript implementation. Another point I have been thinking about this days is just use the SDP IDs to do the handshake directly over the DataChannels, so there will be no need to use handshake or backend servers at all, but this need some investigation (a friend of mine told me that SDP IDs would expire in a few minutes so I can't be able to have a PeerConnection object ready to accept incoming connections just to do the handshake, any clue about this?).

And this is all for now. As usual, any comments or suggestions are welcome :-)

Online Python Tutor

Online Python Tutor, un tutor online de Python, que no solo permite hacer pequeños programas para aprender sino que ademas te muestra paso a paso todo lo que sucede internamente con una animacion: asignacion de variables, llamada a funciones, datos en la pila de programas... El unico pero que le veo es la reasignacion de variables que queda un poco confusa (un paso intermedio para mostrar el recolector de basura funcionando seria mucho mas claro y realista), pero si algo asi se usara en primero de carrera se prevendrian despues muchos dolores de cabeza... :-D

jueves, 20 de septiembre de 2012

What is WebRTC?

http://lincolnloop.com/blog/2012/sep/12/what-webrtc/

What is WebRTC, one of the most important building block of ShareIt!, explained for non-techies: what is, what is intended for and what is the current status of this technology. Cool :-)

sábado, 8 de septiembre de 2012

DataChannel polyfill


Han sido tres semanas de duro trabajo, pero finalmente he terminado una implementacion de DataChannel usando WebSockets :-D

Obviamente, no es P2P porque necesita un servidor funcionando como proxy entre los pares, pero puesto que lo he desarrollado a partir de la especificacion deberia ser compatible con su API cuando haya una implementacion nativa en Chrome o Firefox a final de año, o al menos deberia ser util para empezar a trabajar con una mentalidad distribuida en lugar de basada en servidor (esto es lo que mas me ha costado mientras desarrollaba la implementacion :-P ) y probar nuestras aplicaciones. Usarlos es tan simple como incluir datachannel.js en el codigo HTML (despues de cambiar la URL del servidor puesto que actualmente esta metida a pelo), arrancar el servidor proxy y listo, a partir de aqui es completamente autonomo :-D

El codigo se puede encontrar en https://github.com/piranna/DataChannel-polyfill. Tambien tengo una version modificada del codigo de la demo y del cliente de WebRTC.io que he usado para probarlo (sustituyendo el pequeño chat que tienen hecho basado en servidor a una arquitectura P2P enviando los mensajes a todos los pares conectados) que pueden encontrarse en https://github.com/piranna/webrtc.io-demo/tree/polyfill y https://github.com/piranna/webrtc.io-client/tree/polyfill y tambien he hecho un pull-request para que lo añadan en su rama maestra. Por favor mandadme cualquier comentario, consejo o mejora que le veais al codigo :-)

P.D.: por si alguien anda perdido, WebRTC es la especificacion que esta desarrollando para poder conectar los navegadores web directamente entre ellos sin necesidad de un servidor entre medias, y aunque en las ultimas version de Chrome y de Firefox ya hay soporte para realizar videoconferencia directamente desde el navegador y hay algunas aplicaciones que ya empiezan a usarlo (incluso Skype va a cambiar su protocolo para acogerse al estandar), lo cierto es que el soporte para el envio de datos todavia esta por definir y no hay ningun navegador que lo soporte hasta final de año, por lo que para ir preparandome para entonces y poder ir adaptando el codigo para estar listo he desarrollado esta libreria siguiendo la especificacion para que el codigo sea compatible de cara al futuro.

miércoles, 11 de julio de 2012

Achievement unlocked: Chinese spaghetti code

Dos dias y medio peleandome con la funcion de inicializacion de una tarjeta capturadora profesional cuyo codigo de ejemplo no se ajustaba a las especificaciones de la documentacion del fabricante y que devolvia un codigo de error no documentado y totalmente ilogico y descabellado, y descubrir que el problema estaba en que faltaba copiar una libreria dinamica de la cual no hay constancia en ninguna parte y el framework de la tarjeta no echaba en falta en ningun momento ni lanzaba ningun mensaje de error.

He visto cosas que jamas creeriais, returns incondicionales en mitad de una funcion sin venir a cuento, sistemas criticos sin tests cuya configuracion te obligaba a tocar 5 archivos distintos... pero lo de estos chinos no creo que lo supere nada. Despues de esto creo que ya estoy listo para retirarme al Tibet a dedicarme a la meditacion y encontrar mi yo interior...

domingo, 15 de abril de 2012

A veces veo eventos...

A pesar de los fallos relativos al git-svn y tener que trabajar unicamente con el repositorio de GitHub... no he podido resistirme ni tener las manos quietas y he picado mas codigo :-P ¿Y en que he estado liado estos ultimos dias en lugar de estudiar los examenes? Pues ni mas ni menos que con el task manager :-D

El primer paso fue hacer que se imprieran los ticks fuera del driver del temporizador, ya que ahi no hacian nada util. Ahora se estan enviando por el motor de eventos en distintos periodos de tiempo: milisegundos (para lo que he tenido que aumentar la precision del timer, suerte que solo es una variable :-) ), centesimas, decimas y segundos. Asi aunque quizas lo sobrecargue un poco simplemente tengo que acoplarme a la frecuencia adecuada, en este caso centesimas (lo estandar), aunque podria hacer que el cambio de contexto fuese incluso mas rapido si quisiera.

Despues, empece con la definicion basica de lo que seria un proceso internamente para poder delegarles eventos (registrarse directamente en el gestor de eventos del sistema queda un poco feo y complicado, y mas si de todas formas habra que buscar los callbacks dentro de los procesos). Al principio pense en reutilizar la libreria de threads que he hecho para la asignatura de Fundamentos de Sistemas Distribuidos... hasta que me di cuenta que setjmp() y longjmp() son dependientes de cada sistema o no tengo manera posible de implementarlos por el momento :-/ asi que descarte esa idea y me centre por el momento en como hacer para delegar los eventos a sub-diccionarios, y aqui me encontre con otro problema: ¡un diccionario no es una funcion! Asi que como solucion rapida estoy usando un segundo diccionario a la espera de desarrollar mas como seria el tipo Event.

Por ultimo y no menos importante, en un acto de inspiracion divina (en concreto de Morfeo ;-) ) se me ocurrio que aunque actualmente este todo funcionando en el mismo espacio de usuario, podria trabajar con los eventos de los procesos de forma independiente a traves de funciones estaticas... incluso aunque esten en un mismo archivo, siempre que sea este el que se importe. Esto redunda en codigo repetido, si, pero quizas se pueda arreglar pasando las estructuras por parametros. Lo que si que es interesante es el hecho de que el preprocesador se ejecuta de forma lineal, con lo que abusando de el un poco, he conseguido renombrar las funciones relaccionadas con los eventos en el lado de las aplicaciones igual que en el lado del kernel, con lo que solo hace falta cambiar el include para poder pasar el codigo de un lado a otro :-D Esto ultimo es mas util de lo que parece, ya que aparte de hacer el codigo mas limpio, quizas pueda aplicarlo tambien a las llamadas al sistema, y por tanto, que se puedan mover los drivers del espacio de usuario al espacio de kernel de forma totalmente transparente :-D

Como veis, esta todo bastante "en el aire" a la espera de poder dividir el codigo cuando termine el concurso y poder analizar y hacer pruebas independientes de cada parte, pero lo cierto es que al final me esta quedando un API bastante curiosa y flexible y, sobretodo, puramente orientada a eventos (que es lo que queria... :-D )

Update 23:39:

He intentado demostrar mi teoria respecto a usar la misma firma en los syscalls y ha funcionado, pero no como esperaba... sino mejor: puesto que ahora tengo el codigo mas aislado entre sus partes (y sobretodo a nivel de makefile), a la hora de compilarlo cada parte se compila con sus correspondientes syscall.h y syscall.c sin interferirse, luego no hacen falta hacer trucos de ningun tipo: las firmas de los syscalls son iguales que las de las funciones que representan dentro del kernel de forma nativa :-D Chulo, ¿eh? :-)

jueves, 12 de abril de 2012

(Problemas de) ultima hora

Etapa final del concurso de este año y en plena epoca de examenes (al menos para mi, que todavia estoy en el plan antiguo), la tension se vive en el aire... :-D Y me encuentro con problemas :-(

Anoche le estuve dando un repaso a Gaia haciendo que pueda delegar los eventos a "sub-managers" propios de cada aplicacion (el primer paso para poder aislar las aplicaciones del core y que pueda ser realmente multitarea mientras sigue funcionando por eventos) y lo cierto es que consegui que funcionara... hasta cierto punto. El caso es que el motivo por el cual se estaban imprimiendo por pantalla los caracteres dos veces (un bug realmente feo) es porque de hecho estaba procesando el evento dos veces, una al producirse y otra al bombear la cola. "Bien, un bug menos" direis... pues no: resulta que aunque la arquitectura es correcta y de hecho los eventos generados por las interrupciones se estan procesando correctamente, los eventos "software" (en concreto 'VGA/text/putchar', el encargado de escribir en pantalla) se estan llenando de 'V' al principio y por lo tanto no coinciden con ninguno de los registrados (obvio...). ¿Resultado? No se imprime nada en pantalla. Estupendo... Asi que como no consigo encontrar el error (puede deberse a una condicion de carrera o a una mala implementacion del diccionario, aunque visto que siempre ocurre igual supongo que es esto ultimo) y tampoco hay demasiado tiempo, he preferido que los eventos se lancen directamente sin pasar por la cola a espera de poder aislar libGaia cuando termine el concurso y hacer pruebas en condiciones. Esta es una de las razones por las que me gusta tanto Python, que todas las estructuras basicas vienen de serie y ademas estan muy probadas. La parte buena es que el origen del bug de imprimir dos veces ahora esta completamente identificado... :-D

Sin embargo hay otro problema no menos importante: era muy reticente a usar la forja del concurso para este proyecto (a diferencia del año pasado) puesto que por la complejidad del proyecto podia haber problemas... y los ha habido: puesto que al usar git-svn se me creo una nueva rama 'master', Masterbranch no me estaba recogiendo los cambios, asi que intente unir las dos ramas para que estuvieran sincronizadas... y ahora git-svn no funciona. Por suerte el codigo esta a salvo: en la forja del concurso esta una version con el bug anterior corregido y funcionando de forma estable, y puedo seguir subiendo cosas al repositorio de GitHub, luego no hay problemas en este aspecto. Sin embargo, si durante esta semana hago cambios grandes, o bien arreglo git-svn o bien sera mejor acceder directamente al repositorio principal en GitHub.

lunes, 2 de abril de 2012

Un empujoncito...

Bueno, como ya sabreis, nos encontramos en la recta final del concurso de este año, y aunque ya habia pensado en abandonarlo debido a la de lio que he tenido ultimamente y a que literalmente habia perdido la inspiracion... lo cierto es que soy un testarudo :-P

Asi que ya me veis, puesto que habia que entregar un pequeño informe detallado en el Readme del proyecto y tambien subirlo a la forja del concurso, me puse a revisar el codigo por si encontraba donde estaba el fallo por el cual no leia desde el teclado ni se procesaban correctamente los eventos lanzados por las interrupciones, y de pura casualidad los encontre, o al menos encontre una posible solucion añadiendole un pequeño retraso y cambiando los eventos a minusculas (creo que tiene que ver con la busqueda de entradas dentro del diccionario). Segun un amigo mio lo del retraso es debido a una condicion de carrera, pero lo cierto es que no tengo demasiadas ganas de investigarlo por ahora ya que tengo pensado hacer un rediseño completo del proyecto, principalmente convirtiendo el core en un proyecto independiente (libGaia) gracias al hecho de que en PyMite4Multiboot el codigo es practicamente el mismo, con lo que ademas me sera tambien mucho mas facil testearlo (como ya me paso cuando converti AntiORM en un proyecto independiente de PirannaFS).

En resumen: que ya leo desde el teclado correctamente, y acabo de darme cuenta que tenia muy cerquita y al alcance de la mano el poder tener "algo" que se pareciese minimamente a un sistema operativo multitarea y ademas con un esbozo muy claro de cual seria la API de las aplicaciones, en lugar de ser todo una macedonia de frutas callbacks lanzados por eventos. Vale, de acuerdo: un unico espacio de direcciones, todo hardcodeado, sin memoria dinamica... me referia mas al hecho de que aislando los eventos de las aplicaciones en su propia cola (en lugar de usar la del sistema) y el poder cambiar de "aplicaciones" a partir de las interrupciones del reloj del sistema quedaria mas claro cuales son los conceptos a partir de los que queria basar el proyecto. ¿Deberia haberme centrado mas en el proyecto en lugar de dedicar el tiempo a AntiORM? Probablemente. ¿Y respecto a PyMite4Multiboot? No lo creo, ya que justamente al ser mas facil desarrollar sobre el y permitirme ver las cosas desde otro punto de vista no solo he podido definir mejor como orientar el desarrollo futuro del proyecto (o sea: crear libGaia y modularizarlo) y ademas me ha sido mas facil resolver los fallos que tenia con el teclado. En cualquier caso, como dijo Linus Tordvalds y muy especialmente aplicado al software libre, si no es divertido no merece la pena hacerlo... :-D

Ahora, ¿que me depara el futuro? Bueno, a corto plazo centrarme en los examenes (me esperan dos semanas de aupa...), y despues quizas intente a definir la API de las aplicaciones si me da tiempo a hacerlo antes de que termine el plazo de evaluacion del concurso. Despues sin lugar a dudas aislar libGaia y todos los sub-proyectos que han aparecido a lo largo de este año y englobarlos dentro de ChaOS Project, el sistema operativo que llevo queriendo hacer desde que tenia 10 años y lo que realmente hizo que me motivara a desarrollar PirannaFS y Gaia (y que no subiera el codigo a la forja hasta el ultimo momento... :-P En Git los branchs y forks son cosas de cada dia, pero en SVN son casi como invocar a
Cthulhu...), y por ultimo continuar con el desarrollo de libGaia, Uranus y PyMite4Multiboot ya durante el verano o bien durante el año que viene, esta vez ya centrandome en darles una consistencia y una calidad al codigo, principalmente haciendo que funcione correctamente la memoria dinamica y el funcionamiento en espacio de usuario (aunque la tentacion de aprovechar PyMite para hacerme un sistema operativo y un kernel en Python me esta rondando mucho la cabeza... :-P ).

domingo, 26 de febrero de 2012

PyMite from Interruption Space

Se que ultimamente estoy hablando mucho de PyMite en lugar de sobre Gaia, mi verdadero proyecto para el concurso de este año, pero puesto que en cierto modo se me quedo la espinita clavada por la tonteria del bug por usar una version de Python demasiada moderna, lo cierto es que lo he estado usando como campo de pruebas para despues aplicar las mejoras a Gaia directamente. Sin embargo, esta vez mi trabajo en PyMite se merece un post por derecho propio:

PyMite capturando los scancodes del teclado mediante eventos. Si niños: he conseguido capturar y procesar interrupciones directamente desde dentro de Python :-D

¿Que como lo he hecho? Bien, vayamos por partes:

  • En primer lugar, hace falta tener funcionando un gestor de interrupciones en C. Esto no es demasiado problema, puesto que tambien es necesario para poder capturar las interrupciones del reloj del sistema (que eso ya lo habia conseguido) y para poder capturar las interrupciones del teclado para poder usarlo como entrada estandar, asi que eso ya estaba listo. Trivial, vamos.
  • Una vez hecho eso, el siguiente es añadir handlers para las interrupciones que queremos manejar (en principio todas). Para ello, me he hecho una funcion init() nativa dentro de events.py (un nuevo modulo que he hecho para gestionar los eventos, luego hablo mas de ello) que se encarga de inicializar la cola de eventos, de registrar el handler para las interrupciones en los que estamos interesados para que las guarde en la cola de eventos, y tambien de guardar un puntero a la funcion que se va a encargar despues de extraer los eventos y procesarlos, esta vez ya en Python. Todo el codigo esta sacado de Gaia con pequeñas modificaciones ya que la filosofia de diseño de hacerlo puramente orientado a eventos es comun para los dos, asi que he decidido reutilizar la idea de usar una unica cola global de eventos y que despues se vayan "bombeando" y procesando secuencialmente uno detras de otro como pequeñas unidades de codigo atomicas e independientes, muy inspirado en como funcionan Node.js o el motor de eventos Twisted (del cual soy un fan declarado... :-D ).
  • Una vez que se produce una interrupcion, se lanza el handler que hemos definido para manejarlos (tambien nativo) el cual simplemente añade un nuevo evento a la cola de eventos, llama al bombeador de eventos y sale de la interrupcion (esta fue sencilla... ;-) ).
  • Finalmente, el bombeador de eventos se asegura de que nadie mas los esta procesando (principalmente porque se haya producido una interrupcion mientras todavia no se habian terminado de procesar los pendientes) y en tal caso, va vaciando la cola de eventos y procesandolos uno a uno ejecutando las funciones que se hubiesen registrado para cada uno de ellos. Al tener que acceder a la cola de eventos y estar esta declarada en C estoy usando un par de funciones nativas para comprobar si esta vacia y para extraer uno de los eventos, nada mas.
Simple, facil y para toda la familia :-D Y por supuesto, todo subido al repositorio... :-)

Sin embargo hay truco: por un lado, no estoy generando eventos en Python propiamente dichos, sino que solo estoy guardando el nombre del evento. Esto es asi para que el handler fuera mas pequeño al posponer la conversion a objetos Python y volviera antes de la interrupcion, pero sin lugar a dudas si quiero usar una cola de eventos unica tendre que cambiarlo. Otra opcion seria el tratar las interrupciones en dos pasos, con una cola de interrupciones y despues convertirlas y añadirlas a la cola de eventos en un paso posterior. Esto aislaria por completo el procesamiento de interrupciones de el de eventos con lo que quedaria muchisimo mas limpio, pero tambien añadiria mas retrasos... habra que estudiarlo. Otro truco que usa que me ha sugerido el propio autor de PyMite (aunque al final no lo estoy haciendo como el me ha propuesto) y que es mas interesante, es que al tener PyMite su propio gestor de hilos y ademas puede cambiar automaticamente de uno a otro si ha estado uno de ellos mucho tiempo en la CPU (¿hilos preemptivos? eso en mi barrio se le llama procesos... :-P ) lo estoy aprovechando y en lugar de procesar los eventos directamente (con lo que el "proceso" que estaba en ejecucion cuando se produjo la interrupcion se queda esperando) los estoy lanzando en un nuevo hilo para que se procesen de forma autonoma mas adelante y asi poder volver inmediatamente de la interrupcion :-)


Por otra parte, hay espacio para limpiar codigo y para optimizar para aburrir. En primer lugar, actualmente no es threadsafe puesto que no estoy usando ninguna estructura que lo haga. En Gaia el bombeo de eventos esta protegido con un lock, pero al necesitar guardar la funcion a usar para el bombeo desconozco si podria usar una funcion nativa (supongo que si), por lo que estoy usando un simple booleano (¡¡¡error!!! :-S ), asi que eso tengo que arreglarlo pronto. Tambien estaria la posibilidad de usar la clase Queue de Python, pero tiene muchas dependencias que la libreria estandar de PyMite no me satisface, asi que por el momento descartado. Por ultimo, claro esta, lo que he comentado anteriormente de separar la cola de interrupciones de la de eventos, pero esa es otra historia... :-D En resumen, que en unos commits estara listo ;-)

Y eso es todo por ahora, me falta explicar como se usan dichas interrupciones desde Python pero eso lo explicare en otro post (aunque lo cierto es que ahora deberia centrarme en estudiar para los examenes... :-/ ). Lo que si me he dado cuenta es que el problema de la limitacion de memoria para el kernel en x86 es real, ya que me ha vuelto a pasar con PyMite aunque increiblemente en PyMite ha tardado mucho mas en aparecer que con Gaia: ha sido eliminar las funciones de acceso a los puertos de entrada/salida que no estaba usando y arreglarse el problema... :-/

P.D.: para los que no lo hayan entendido, el titulo del post es una parodia de Plan 9 from User Space, el port para Unix/Linux de las librerias del sistema operativo Plan 9, con el cual tengo una relacción de amor-odio digna de poner en el Facebook como "es complicado"... :-P

martes, 21 de febrero de 2012

It works!


PyMite corriendo sobre QEmu (x86) usando por debajo el codigo de Gaia mostrando un timer basado en interrupciones :-D

lunes, 20 de febrero de 2012

PyMite

Originariamente no iba a desarrollar Gaia, todo fue fruto de las circunstancias. Desde siempre tuve claro que mi sistema operativo tendria una arquitectura microkernel, sin embargo tambien queria que fuera seguro y facil de entender, de ahi que la arquitectura exokernel fuera ganando fuerza: el menor codigo posible corriendo como supervisor, y todo lo demas corriendo como espacio de usuario. Esto se podria potenciar mas si no solo se usan dos ejecutables distintos (Gaia y Uranus) sino que directamente estaban escritos en dos lenguajes distintos, y que dos mejores opciones que mis grandes amores C++ y Python :-D

Proyectos para hacer un sistema operativo en Python ha habido algunos, pero no han llegado a buen termino, en parte por la mala fama que tiene Python de ser lento (lo cual no es "tan" cierto...). Sin embargo poco antes de comenzar la edicion del concurso de este año descubri la existencia de PyMite, y en ese momento vi claro que es lo que debia hacer :-D

PyMite aka Python-on-a-chip es una maquina virtual Python diseñada para correr sobre microcontroladores de 8 bits... y sin sistema operativo por debajo, directamente sobre el metal :-) Ironicamente, aunque existe la posibilidad de compilarlo para escritorio para pruebas no habia ninguna plataforma echa para que corriera sobre PCs estandar directamente, luego ¿que mejor manera de colaborar con el software libre? Y ademas, me conseguia una base solida sobre la que programar mi sistema operativo comodamente sin tener que diseñarme mis propias estructuras de datos: dos por el precio de uno :-)

Asi que me puse a ello, mirando documentacion y haciendo pruebas. Lo tenia todo listo, y a la hora de ejecutar... fallo. Un bug tan raro que ni el programador original pudo decirme que podria pasar :-( Habia perdido un tiempo precioso y ademas ya estaba mentalizado en desarrollar de una vez por todas mi propio sistema operativo, por lo que decidi cambiar mi proyecto de portar PyMite a la arquitectura x86 a desarrollar mi propio exokernel que sustituyera la labor que realizaria PyMite de abstraer a bajo nivel el hardware, y asi surgio Gaia, la madre tierra.

Sin embargo, la semana pasada recibi un e-mail sobre no-se-que indicandome que podria ser mi version de Python ya que al ser muy reciente generaba bytecodes que eran interpretados como basura. Al principio no sabia a que se referia hasta que vi de donde procedia: ¡era el bug que notifique hacia 5 meses! La verdad que no confiaba mucho en una idea feliz tan absurda, aunque tenia sentido asi que decidi probarla: me baje mi viejo codigo, compile el entorno usando Python 2.6 en lugar del 2.7.2 que viene por defecto, ejecuto... y no me lo podia creer, la excepcion habia desaparecido. ¡El ultimo paso que me faltaba, al final lo tenia! :-D Tarde, pero al menos ya no me quedaba con el regusto de no haberlo conseguido: PyMite estaba corriendo sobre una nueva plataforma y todo gracias a mi... y al mensaje de un desconocido :-D

Asi que estos dias le he estado dando un pequeño empujon canibalizando el codigo de Gaia (al igual que hace 5 meses hice en sentido inverso) y lo cierto es que me estoy llevando una grata noticia: no solo me esta siendo mucho mas facil entender como hacer las cosas al haberme peleado antese-mail con Gaia (y ademas ya funciona el timer con PyMite :-P ) sino que ademas, ¡casi no estoy picando codigo! ¡¡Todo es copy & paste!! :-D Luego en cierto sentido creo que "parte" de mi proposito al desarrollar Gaia se esta cumpliendo: un framework para hacer facil el desarrollo de sistemas operativos sin tener que preocuparse de las menudeces porque ya estan hechas :-) Por el momento el copy&paste es descarado porque al pillarme la noticia un poco por sorpresa actualmente Gaia de framework tiene poco... pero si que el codigo esta bastante claro con lo que no me esta costando nada adaptarlo :-)

Lo bueno de esto es que me va a servir para tener otro entorno de pruebas aparte de ChaOS para aumentar la portabilidad y abstraccion de Gaia, lo cual es bueno, y ademas tambien me permite colaborar con un proyecto de software libre bastante grande, lo cual esta genial :-D De momento estoy pensando en separar la libreria del sistema a un proyecto aparte (GaiaLib), con vistas a en el futuro sustituirla por NewLib (aunque lo cierto es que no me esta quedando nada mal... :-D ), y quien sabe si no podre sacar mas codigo reutilizable. Al final con la tonteria, lo que iba a ser un simple proyecto para el concurso ya van colaboraciones en cuatro distintos... :-P

sábado, 11 de febrero de 2012

Featuring Norm

Como os dije en mi anterior entrada, debido al estres y desesperación que me estaba ocasionando el que Gaia cascara por cualquier tonteria decidi darme un respiro y mejorar en mi sistema de archivos, y una de esas mejoras fue justamente quitar todas las referencias a SQLite de la capa de abstracción a la base de datos y limpiarla un poquito. ¿Que pasa? Que como tiene la caracteristica de que es bastante generica al tener todas las consultas SQL en archivos externos, entonces ya no hay ninguna referencia al sistema de archivos y se podria aislar como un paquete independiente para poder usarlo en otros proyectos. Pues bien: un poco de magia con la ayuda de GitHub, un poquito de limpieza de codigo para que quede mas presentables y unas cuantas optimizaciones (las cuales incluso han hecho que PirannaFS sea mas limpio y rapido :-) ) y asi es como nacio Norm.

Tradicionalmente, los ORM se han usado para definir a alto nivel los datos, de forma que fuera facil de usar para el programador, pero de esta forma se pierde el control de como se estan guardando (lo cual no es malo, es la mayoria de los casos no es del todo importante), y ademas al hacerlo de una forma generica ralentizando el acceso y termina siendo un cuello de botella y creando problemas en aplicaciones que necesitan un gran rendimiento.

Sin embargo, Norm funciona al reves: en lugar de centrarse en la aplicacion y generar internamente el codigo SQL necesario para acceder a los datos, se centra justamente en estos y en como se accede a ellos en la base de datos y genera el codigo necesario para poder usarlos desde la aplicacion. De esta forma, se puede diseñar a mano codigo SQL optimizado para la aplicacion en concreto teniendo un control total sobre los datos sin tener que escribir todo el glue code necesario para poder usarlo ya que de esto ya se encarga Norm, y ademas genera una API especifica para la aplicacion muy sencilla de usar. Si a esto le añadimos que ademas el codigo SQL no esta embebido dentro del codigo del programa principal como se ha hecho hasta ahora cuando se necesitaba este tipo de optimizaciones sino que se guarda en archivos independientes faciles de mantener y de actualizar sin tocar el codigo del programa principal, no me extraña que al final de la presentacion que hice ayer en las oficinas de Tuenti para Python-Madrid la gente mostrara tanto interes e incluso me diesen ideas para mejorarlo o quisieran colaborar en su desarrollo... :-)


¿Sera posible que por primera vez haya hecho algo que realmente sea util para la gente? ¿Al final sera capaz PirannaFS de sacarme de pobre? :-P

domingo, 5 de febrero de 2012

Gaia is back

Bien es cierto que no escribo mucho por aca, pero lo cierto es que no soy muy dado a escribir... :-P Pero bueno, como considero que debo manteneros informados de mis avances, alla voy :-D

Lo cierto es que muchos avances no ha habido con Gaia a pesar de el tiempo dedicado, la paginacion me ha estado dando muchos problemas y a ser sinceros, me ha deprimido. He intentado solucionarlo usando el codigo original de James Mallory (de cuyos tutoriales sobre sistemas operativos he estado usando como referencia) para ir adaptandolo a mi arquitectura y ver en donde estaba fallando, pero lo cierto es que ya me aburri (que es lo peor que le puede pasar a alguien que desarrolla software libre, que deje de divertirse con lo que hace) y deje el proyecto aparcado/abandonado hasta que viera un poco de luz. Es por eso por lo que si veis mi perfil en Github vereis que le he estado dando un buen empujon a PirannaFS en las ultimas semanas: por alguna razon, me sigue motivando e inspirando :-)

Sin embargo... esa luz llego, aunque fuese solo con forma de cerilla: a traves de la wikipedia llegue por casualidad al sistema operativo Gavin, y justo en uno de los commits indicaba que estaba usando -O2 al compilar para optimizar el codigo porque añadia una variable y dejaba de arrancar (uno de los problemas que me sucedian a mi) ya que al parecer, al arrancar se dispone de muy poco espacio en memoria para el kernel. Añadir el flag, compilar... y adios problema :-D Asi que aprovechando la buena nueva decidi darle un empujon al gestor de interrupciones y limpiar un poco la arquitectura antes de continuar con la paginacion. Gracias a esto puedo decir: si, mi arquitectura funciona, y es correcta, se puede hacer un sistema operativo puramente orientado a eventos :-D Ahora el problema esta en que por alguna razon los syscalls ya no funcionan correctamente, con lo que no puedo leer del teclado :-( Bien es cierto que una de las razones por las que empece Gaia era precisamente para evitar a la gente en el futuro que se rompiera la cabeza como me la estoy rompiendo yo ahora, pero tampoco me imagine que x86 fuese una plataforma tan mala para trabajar a bajo nivel... :-(

En fin, permanezcan en antena, a ver si hacemos algo de provecho en las proximas semanas...