Archive for the ‘apps’ Category

Tatsumaki, or how to write a nice webapp in less than two hours

Monday, December 21st, 2009

Until today, I had a script named “lifestream.pl”. This script was triggered via cron once every hour, to fetch various feeds from services I use (like github, identi.ca, …) and to process the result through a template and dump the result in a HTML file.

Today I was reading Tatsumaki’s code and some examples (Social and Subfeedr). Tatsumaki is a “port” tornado (a non blocking server in Python), based on Plack and AnyEvent. I though that using this to replace my old lifestream script would be a good way to test it. Two hours later I have a complete webapp that works (and the code is available here).

The code is really simple: first, I define an handler for my HTTP request. As I have only one things to do (display entries), the handler is really simple:

package Lifestream::Handler;   
use Moose;                     
extends 'Tatsumaki::Handler';  
 
sub get {                      
    my $self = shift;          
    my %params = %{$self->request->params};
    $self->render( 'lifestream.html', {
        memes    => $self->application->memes($params{page}),
        services => $self->application->services
    });
}
1;

For all the get request, 2 methods are called : memes and services. The memes get a list of memes to display on the page. The services get the list of the various services I use (to display them on a sidebar).

Now, as I don’t want to have anymore my lifestream.pl script in cron, I will let Tatsumaki do the polling. For this, I add a service to my app, which is just a worker.

package Lifestream::Worker;    
use Moose;                     
extends 'Tatsumaki::Service';  
use Tatsumaki::HTTPClient;     
...
sub start {
    my $self = shift;
    my $t; $t = AE::timer 0, 1800, sub {
        scalar $t;
        $self->fetch_feeds;
    };
}
....
sub fetch_feeds {
    my ($self, $url) = @_;
    Tatsumaki::HTTPClient->new->get( $url, sub { #do the fetch and parsing stuff });
}

From now, every 60 minutes, feeds will be checked. Tatsumaki::HTTPClient is a HTTP client based on AnyEvent::HTTP.

Let’s write the app now

package Lifestream;            
 
use Moose;
extends "Tatsumaki::Application";
 
use Lifestream::Handler;       
use Lifestream::Worker;        
...
sub app {
    my ( $class, %args ) = @_;
    my $self = $class->new( [ '/' => 'Lifestream::Handler', ] );
    $self->config( $args{config} ); 
    $self->add_service( Lifestream::Worker->new( config => $self->config ) );
    $self;
}
...
sub memes {
...
}
 
sub services {
....
}

The memes and services method called from the handler are defined here. In the app method, I “attch” the “/” path to the handler, and I add the service.

and to launch the app

my $app = Lifestream->app( config => LoadFile($config) );
require Tatsumaki::Server;      
Tatsumaki::Server->new(
    port => 9999,
    host => 0,
)->run($app);

And that’s it, I now have a nice webapp, with something like only 200 LOC. I will keep playing with Tatsumaki as I have more ideas (and probably subfeedr too). Thanks to miyagawa for all this code.

Riak, Perl and KiokuDB

Sunday, December 13th, 2009

As I was looking for a system to store documents at $work, Riak was pointed to me by one of my coworkers. I’m looking for a solution of this type to store various types of documents, from HTML pages to json. I need a system that is distributed, faul tolerant, and that works with Perl.

So Riak is a document based database, it’s key value, no sql, REST, and in Erlang. You can read more about it here or watch an introduction here. Like CouchDB, Riak provides a REST interface, so you don’t have to write any Erlang code.

One of the nice things with Riak it’s that it let you defined the N, R and W value for each operation. This values are:

  • N: the number of replicas of each value to store
  • R: the number of replicas required to perform a read operation
  • W: the number of replicas needed for a write operation

Riak comes with library for python ruby PHP and even javascript, but not for Perl. As all these libraries are just communicating with Riak via the REST interface, I’ve started to write one using AnyEvent::HTTP, and also a backend for KiokuDB.

Installing and using Riak

If you interested in Riak, you can install it easily. First, you will need the Erlang VM. On debian, a simple

sudo aptitude install erlang

install everything you need. Next step is to install Riak:

wget http://hg.basho.com/riak/get/riak-0.6.2.tar.gz
tar xzf riak-0.6.2.tar.gz
cd riak
make
export RIAK=`pwd`

Now, you can start to use it with

./start-fresh config/riak-demo.erlenv

or if you want to test it in cluster mode, you can write a configuration like this:

{cluster_name, "default"}.
{ring_state_dir, "priv/ringstate"}.
{ring_creation_size, 16}.
{gossip_interval, 60000}.
{storage_backend, riak_fs_backend}.
{riak_fs_backend_root, "/opt/data/riak/"}.
{riak_cookie, riak_demo_cookie}.
{riak_heart_command, "(cd $RIAK; ./start-restart.sh $RIAK/config/riak-demo.erlenv)"}.
{riak_nodename, riakdemo}.
{riak_hostname, "192.168.0.11"}.
{riak_web_ip, "192.168.0.11"}.
{riak_web_port, 8098}.
{jiak_name, "jiak"}.
{riak_web_logdir, "/tmp/riak_log"}.

Copy this config on a second server, edit it to replace the riak_hostname and riak_nodename. On the first server, start it like show previously, then on the second, with

./start-join.sh config/riak-demo.erlenv 192.168.0.11

where the IP address it the address of the first node in your cluster.

Let’s check if everything works:

curl -X PUT -H "Content-type: application/json" \
    http://192.168.0.11:8098/jiak/blog/lumberjaph/ \
    -d "{\"bucket\":\"blog\",\"key\":\"lumberjaph\",\"object\":{\"title\":\"I'm a lumberjaph, and I'm ok\"},\"links\":[]}"
 
curl -i http://192.168.0.11:8098/jiak/blog/lumberjaph/

will output (with the HTTP blabla)

{"object":{"title":"I'm a lumberjaph, and I'm ok"},"vclock":"a85hYGBgzGDKBVIsbGubKzKYEhnzWBlCTs08wpcFAA==","lastmod":"Sun, 13 Dec 2009 20:28:04 GMT","vtag":"5YSzQ7sEdI3lABkEUFcgXy","bucket":"blog","key":"lumberjaph","links":[]}

Using Riak with Perl and KiokuDB

I need to store various things in Riak: html pages, json data, and objects using KiokuDB. I’ve started to write a client for Riak with AnyEvent, so I can do simple operations at the moment, (listing information about a bucket, defining a new bucket with a specific schema, storing, retriving and deleting documents). To create a client, you need to

my $client = AnyEvent::Riak->new(
    host => 'http://127.0.0.1:8098',
    path => 'jiak',
);

As Riak exposes to you it’s N, R, and W value, you can also set them in creation the client:

my $client = AnyEvent::Riak->new(
    host => 'http://127.0.0.1:8098',
    path => 'jiak',            
    r    => 2,
    w    => 2,                 
    dw   => 2,
);

where:

  • the W and DW values define that the request returns as soon as at least W nodes have received the request, and at least DW nodes have stored it in their storage backend.
  • with the R value, the request returns as soon as R nodes have responded with a value or an error. You can also set this values when calling fetch, store and delete. By default, the value is set to 2.

So, if you wan to store a value, retrieve it, then delete it, you can do:

my $store = $client->store(                                           
    { bucket => 'foo', key => 'bar', object => { baz => 1 }, } )->recv;    
my $fetch  = $client->fetch( 'foo', 'bar' )->recv;
my $delete = $client->delete( 'foo', 'bar' )->recv;

If there is an error, the croak method from AnyEvent is used, so you may prefer to do this:

use Try::Tiny;
try {
  my $fetch = $client->fetch('foo', 'baz')->recv;
}catch{
  my $err = decode_json $_;
  say "error: code => ".$err->[0]." reason => ".$err->[1];
};

The error contains an array, with the first value the HTTP code, and the second value the reason of the error given by Riak.

At the moment, the KiokuDB backend is not complete, but if you want to start to play with is, all you need to do is:

my $dir = KiokuDB->new(
    backend => KiokuDB::Backend::Riak->new(
        db => AnyEvent::Riak->new(      
            host => 'http://localhost:8098',
            path => 'jiak',
        ),
        bucket => 'kiokudb',            
    ),
);
 
$dir->txn_do(sub { $dir->insert($key => $object)});

sd : the peer to peer bug tracking system

Tuesday, November 17th, 2009

SD is a peer to peer bug tracking system build on top of Prophet. Prophet is A grounded, semirelational, peer to peer replicated, disconnected, versioned, property database with self-healing conflict resolution. SD can be used alone, on an existing bug tracking system (like RT or redmine or github) and it plays nice with git.

Why should you use SD ? Well, at $work we are using redmine as our ticket tracker. I spend a good part of my time in a terminal, and checking the ticket system, adding a ticket, etc, using the browser, is annoying. I prefer something which I can use in my terminal and edit with my $EDITOR. So if you recognize yourself in this description, you might want to take a look at SD.

In the contrib directory of the SD distribution, you will find a SD ticket syntax file for vim.

how to do some basic stuff with sd

We will start by initializing a database. By default

sd init

will create a .sd directory in your $HOME. If you want to create in a specific path, you will need to set the SD_REPO in your env.

SD_REPO=~/code/myproject/sd sd init

The init command creates an sqlite database and a config file. The config file is in the same format as the one used by git.

Now we can create a ticket:

SD_REPO=~/code/myproject/sd ticket create

This will open your $EDITOR, the part you need to edit are specified. After editing this file, you will get something like this:

Created ticket 11 (437b823c-8f69-46ff-864f-a5f74964a73f)
Created comment 12 (f7f9ee13-76df-49fe-b8b2-9b94f8c37989)

You can view the created ticket:

SD_REPO=~/code/myproject/sd ticket show 11

and the content of your ticket will be displayed.

You can list and filter your tickets:

SD_REPO=~/code/myproject/sd ticket list
SD_REPO=~/code/myproject/sd search --regex foo

You can edit the SD configuration using the config tool or editing directly the file. SD will look for three files : /etc/sdrc, $HOME/.sdrc or the config file in your replica (in our exemple, ~/code/myproject/sd/config).

For changing my email address, I can do it this way:

SD_REPO=~/code/myproject/sd config user.email-address franck@lumberjaph.net

or directly

SD_REPO=~/code/myproject/sd config edit

and update the user section.

sd with git

SD provides a script for git: git-sd.

Let’s start by creating a git repository:

mkdir ~/code/git/myuberproject
cd ~/code/git/myuberproject
git init

SD comes with a git hook named “git-post-commit-close-ticket” (in the contrib directory). We will copy this script to .git/hooks/post-commit.

now we can initialize our sd database

git-sd init

git-sd will try to find which email you have choosen for this project using git config, and use the same address for it’s configuration.

Let’s write some code for our new project

#!/usr/bin/env perl
use strict;
use warnings;
print "hello, world\n";
git add hello.pl
git commit -m "first commit" hello.pl

now we can create a new entry

git-sd ticket create # create a ticket to replace print with say

We note the UUID for the ticket: in my exemple, the following output is produced:

Created ticket 11 (92878841-d764-4ac9-8aae-cd49e84c1ffe)
Created comment 12 (ddb1e56e-87cb-4054-a035-253be4bc5855)

so my UUID is 92878841-d764-4ac9-8aae-cd49e84c1ffe.

Now, I fix my bug

#!/usr/bin/env perl
use strict;
use 5.010;
use warnings;
say "hello, world";

and commit it

git commit -m "Closes 92878841-d764-4ac9-8aae-cd49e84c1ffe" hello.pl

If I do a

git ticket show 92878841-d764-4ac9-8aae-cd49e84c1ffe

The ticket will be marked as closed.

sd with github

Let’s say you want to track issues from a project (I will use Plack for this exemple) that is hosted on github.

git clone git://github.com/miyagawa/Plack.git
git-sd clone --from "github:http://github.com/miyagawa/Plack"
# it's the same as
git-sd clone --from "github:miyagawa/Plack"
# or if you don't want to be prompted for username and password each time
 git-sd clone --from github:http://githubusername:apitoken@github.com/miyagawa/Plack.git

It will ask for you github username and your API token, and clone the database.

Later, you can publish your sd database like this:

git-sd push --to "github:http://github.com/$user/$project"

Now you can code offline with git, and open/close tickets using SD :)