Thursday, August 30, 2012

libcouchbase overhauling..

When I laid out the requirements for libcouchbase one of my goals was that it should be binary compatible, and we've managed to keep that promise pretty well. We've extended the API in a number of ways, but always in a compatible way. We've been able to build client libraries for other languages such as Ruby; PHP; Perl and node.js (possibly others I forgot as well) on top of libcouchbase and life has been good..

We've been talking about how great it would be if we could store a "datatype" field on each item you're storing, so that different clients could "do smart things"™with the objects. Unfortunately I didn't create the API in an extendible way to make it easy to do so. I would either have to break the API, or I could extend the API with more specialized methods. Ideally I wouldn't like to break the API, but the thought of extending the API with all sorts of specialized functions would just make the API a nightmare to use.

Given that Couchbase server 2.0 is going to give you a lot of new cool stuff, it would be a good idea to change the API before people started to use all of this goodness and make the transition to a new API harder then it has to be.

The first major change you'll notice is that we've shortened all of the names from libcouchbase to lcb. The header file is still libcouchbase/couchbase.h and you should link with -lcouchbase. This change isn't very hard to work around, simply do a search and replace libcouchbase_ with lcb_.

We've also removed a lot of the entry points (all of the _by_key-methods), and renamed some of the methods to make the name clearer (get_locked instead of getl etc). Adapting to those changes shouldn't be that hard either. The change in the API that'll require some effort to fix is however that we've changed the signature of almost all of the functions and the callbacks. I've tried really hard to make the API consistent so that once you know how it works you can "guess" the signature for the function you're going to use. The common form is:

lcb_error_t lcb_operationname(lcb_t instance, 
                              const void *cookie, 
                              int number, 
                              const lcb_operation_cmd_t * const * commands);

What?? I have to send in an array of pointers to commands?? You might think that sucks and I'm only trying to make your life as a user miserable, but there is actually a good reason for not using an array of objects. To explain that, lets start looking at the internals of these lcb_operation_cmd_t. In order to allow us to extend the functionality in the future without breaking the binary compatibility we're using versioned structs. Let's take a look at the operation-struct you would use to retrieve an object:


    typedef struct {
        int version;
        union {
            struct {
                const void *key;
                lcb_size_t nkey;
                lcb_time_t exptime;
            } v0;
        } v;
     } lcb_get_cmd_t;


The version member in the structure tells us how we should interpret the rest of the structure. Given that the size of this struct may vary over time, we can't pass in an array of such objects (well, we could, but the internals in the function would have a harder time figuring the offset for the next object since it would need to know the alignment and struct packing you used).

So let's show you a working example on how you would use the new API to retrieve a value from your cache.

In C99 I would typically write something like this:



    const lcb_get_cmd_t c = { .version = 0,  
                              .v.v0 = { 
                                .key = "mykey", 
                                .nkey = 5 
                              }
                            };
    const lcb_get_cmd_t* cmds[] = { [0] = &c };
    lcb_get(instance, NULL, 1, cmds);



We've added constructers for the objects in C++, so all you need there is:


    const lcb_get_cmd_t c("mykey", 5);
    const lcb_get_cmd_t* cmds[] = { [0] = &c };
    lcb_get(instance, NULL, 1, cmds);


We're also using the same method in the callbacks (I've tried to make them as consistent as possible just as the commands), so the get callback now looks like:


    void get_callback(lcb_t instance,
                      const void *cookie,
                      lcb_error_t error,
                      const lcb_get_resp_t *resp)

A typical implementation could look like:

static void get_callback(lcb_t instance,


                         const void *cookie,
                         lcb_error_t error,
                         const lcb_get_resp_t *resp)
{
    if (error == LCB_SUCCESS) {
        if (resp->version != 0) {
            // I don't know how this object look like
            // Do some proper error handling
            return ;
        }

        // Use the information in resp->v.v0 

    } else {
        // Do error handling for miss/errors
    }
}


We've tried to update the documentation in the headerfile with more information and examples for each of the entry function. Please don't hesitate to drop me an email (or ask questions on #libcouchbase on IRC).

We're in the middle of updating clients to use the new API and write more and more automatic tests!

Happy hacking!


Monday, July 16, 2012

libcouchbase meets node.js


Matt asked me a while back if I could look at what it would take to utilize libcouchbase from node.js. When I initially designed libcouchbase one of the requirements was that it should be fully asynchronous, so from a design perspective it should fit very well for node.js. Another design goal of libcouchbase was that it should be modular so that I could swap out the underlying methods that does all of the network communications. This API isn't something the average developer would see / use, but I added it to (hopefully) make it easier to port to new systems. I've been using libevent for a couple of years now, and I have to admit that I had that mindset when I designed that API. Unfortunately it doesn't map that well to lets say IOCP or libuv, so I'd like to refactor the API. In order to get full integration with node.js I have to do this refactoring (the current version use it's own event loop and block the global event loop). Mordy implemented a version that allows you to use libuv, but it's not merged into libcouchbase yet. I think I'd prefer a refactor of the current io model before merging the patch.

Anyway. When I started to look into the details I quickly realized that this was a completely new territory for me. I’ve never done anything with Javascript before, so I had no idea what kind of API the hard-core Javascript folks would like. Instead of waiting for someone to come up with an API specification for me, I started playing around trying to figure out how to create a Javascript binding to libcouchbase. I’m a strong believer of that an API should feel natural in the language it’s been used (instead of a “port” of the underlying API), but no matter what I would need to know how to integrate it. If I had a “working skeleton” I could always refactor the API into something the user would like at a later time.

It turns out that building a basic extension for node.js in C++ isn’t hard at all. The one I’ve built got doesn’t qualify as a real extension for node.js (given that it “blocks” the global event notification loop by using it’s own), but it works as a good “proof of concept”. I don’t think looking at the API is that interesting, but given that it was so easy to build the extension I figured I could walk you through it to give you a head start if you want to build your own.

You can find the entire source code I’m talking about at https://github.com/trondn/couchnode. The code examples you'll find here will probably not match entirely to the code you'll find there because I may have removed stuff here to make the example smaller and easier to read (so the stuff you'll find here might not compile ;)). 

The first thing we need to do is to set up the boilerplate code:

#define BUILDING_NODE_EXTENSION
#include
class Couchbase: public node::ObjectWrap {
    static void Init(v8::Handle target);
};
static void init(v8::Handle target) {
    Couchbase::Init(target);
}
NODE_MODULE(couchbase, init)

The above fragment defines the class I'm going to use for the API (Couchbase), and the NODE_MODULE() macro registers the module name “couchbase” and tells node.js that it should call the function named init() to initialize the module. As you can see in init(), I’m calling the Init method in my Couchbase class to let the class initialize itself: 

void Couchbase::Init(v8::Handle target)
{
    v8::HandleScope scope;
    v8::Local t = v8::FunctionTemplate::New(New);
    v8::Persistent s_ct;
    s_ct = v8::Persistent::New(t);
    s_ct->InstanceTemplate()->SetInternalFieldCount(1);
    s_ct->SetClassName(v8::String::NewSymbol("Couchbase"));
    NODE_SET_PROTOTYPE_METHOD(s_ct, "get", Get);

    target->Set(v8::String::NewSymbol("Couchbase"), s_ct->GetFunction());
}

So what does the above code do? It defines the JavaScript API to my class and maps the JavaScript functions to a C++ function, so that when someone writes couchbase.get("foo"); in JavaScript we're calling Couchbase::Get() in C++.

Now let’s look at the Get() method. When I “defined” the API I allowed for get to be called in multiple ways. In the C version of libcouchbase you typically set up a global callback that is called whenever you receive a response for a get call. Originally I made it the same way for JavaScript as well, but that clearly isn't the "node.js-way" of doing stuff. Instead you would write the following JavaScript:

cb.get(function onGet(state, key, value, flags, cas) {
  if (state) {
     console.log("found \"" + key + "\" - [" + value + "]");
  } else {
     console.log("failed for \"" + key + "\"");
  }
}, "foo", "bar");

Given that I was doing all of this as part of my learning curve (I wouldn't be defining the real API now anyway), I decided to support both ways of calling the command. So let's take a look at the method:

v8::Handle Couchbase::Get(const v8::Arguments& args)
{
    if (args.Length() == 0) {
        const char *msg = "Illegal arguments";
        return v8::ThrowException(v8::Exception::Error(v8::String::New(msg)));
    }
    v8::HandleScope scope;
    Couchbase* me = ObjectWrap::Unwrap(args.This());
    void* commandCookie = NULL;
    int offset = 0;
    if (args[0]->IsFunction()) {
        if (args.Length() == 1) {
            const char *msg = "Illegal arguments";
            return v8::ThrowException(v8::Exception::Error(v8::String::New(msg)));
        }
        commandCookie = static_cast(new CommandCallbackCookie(args[0], args.Length() - 1));
        offset = 1;
    }
    int tot = args.Length() - offset;
    char* *keys = new char*[tot];
    libcouchbase_size_t *lengths = new libcouchbase_size_t[tot];
    // @todo handle allocation failures
    for (int ii = offset; ii < args.Length(); ++ii) {
        if (args[ii]->IsString()) {
            v8::Local s = args[ii]->ToString();
            keys[ii - offset] = new char[s->Length() + 1];
            lengths[ii - offset] = s->WriteAscii(keys[ii - offset]);
        } else {
            // @todo handle NULL
            // Clean up allocated memory!
            const char *msg = "Illegal argument";
            return v8::ThrowException(
                    v8::Exception::Error(v8::String::New(msg)));
        }
    }
    me->lastError = libcouchbase_mget(me->instance, commandCookie, tot,
            reinterpret_cast (keys), lengths, NULL);
    if (me->lastError == LIBCOUCHBASE_SUCCESS) {
        return v8::True();
    } else {
        return v8::False();
    }
}

As you see in the code I iterate over all of the parameters the user passed to build up the arguments to pass to libcouchbase_mget. I handle the special case with the function pointer as the first argument by storing it in the "command specific cookie" libcouchbase provides.


In order to build the plugin you need to create a file named wscript with the following content:



def set_options(opt):
  opt.tool_options("compiler_cxx")


def configure(conf):
  conf.check_tool("compiler_cxx")
  conf.check_tool("node_addon")


def build(bld):
  obj = bld.new_task_gen("cxx", "shlib", "node_addon")
  obj.cxxflags = ["-g", "-Wall"]
  obj.ldflags = ["-lcouchbase"]
  obj.target = "couchbase"
  obj.source = "src/couchbase.cc"

And set up the build environment by running:

$ node-waf configure

You can now build and "install" your pugin by running:

$ node-waf build install

You should now be able to test the plugin by creating a JavaScript file and run:

$ node myscript.js 
Happy hacking


Friday, January 27, 2012

So whats the story about libcouchbase and Windows?

A couple of days ago I showed you an example program using libcouchbase to create a small application to put data into a Couchbase cluster, but the code wouldn't compile on Windows. That does by no means imply that libcouchbase doesn't work on Windows, its more that I was in a hurry writing the blog post so I didn't have the time fixing everything up in time for the blog post.

In this blog post I'll show you how easy it is to get everything up'n'running using Windows 7 and Microsoft Visual Studio 2010. In addition to that you need to download and install git to be able to check out the source code (select the option that you want to put git in the path (not the full msys suite, but just git)).

I have to admit that I am far from a "hardcore Windows developer", so there is a lot of things I don't know about the platform. For instance I don't know where I should install third party header files and libraries, so I just decided that I'm going to install all of them into C:\local (with an install, lib and bin directory). I'd be happy if someone could tell me how I'm supposed to do this ;-)

So let's open up the Visual Studio Command Prompt and start building everything:

Setting environment for using Microsoft Visual Studio 2010 x86 tools.
C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC> cd %HOMEPATH%
C:\Users\Trond> mkdir build
C:\Users\Trond> cd build

Since we're going to build dll's you need to set C:\local\bin into your path so that the runtime linker finds the dll's:

C:\Users\Trond\build> set PATH=c:\local\bin;%PATH%

We need to install two dependencies before we can compile libcouchbase itself. Let's check out all of the source code we're going to use:

C:\Users\Trond\build> git clone git://github.com/membase/libisasl.git
C:\Users\Trond\build> git clone git://github.com/membase/libvbucket.git
C:\Users\Trond\build> git clone git://github.com/couchbase/libcouchbase.git
C:\Users\Trond\build> git clone git://github.com/membase/memcached.git
C:\Users\Trond\build> git clone git://github.com/trondn/vacuum.git

The first dependency we're going to build is the SASL library. This is the library libcouchbase use for authenticating to the Couchbase servers. To build and install the library, simply execute:

C:\Users\Trond\build> cd libisasl
C:\Users\Trond Norbye\build\libisasl> nmake -f NMakefile install

That will install libisasl with its header files and libraries into c:\local.

The next library we need to build is libvbucket; the library libcouchbase use to figure out where a a vbucket is located (if you don't know what a vbucket is, you don't really need to know). It is just as easy as libvbucket to build:

C:\Users\Trond\build\libisasl> cd ..\libvbucket
C:\Users\Trond\build\libvbucket> nmake -f NMakefile install

The next thing we need to do is to install some headerfiles libcouchbase needs during build time. These header files contains the protocol definitions libcouchbase needs (but it is not needed by the application). So let's go ahead and install them (to make it easier for us to build libcouchbase)

C:\Users\Trond\build\libvbucket> cd ..\memcached
C:\Users\Trond\build\memcached> git checkout -b branch-20 origin/branch-20
C:\Users\Trond\build\memcached> mkdir c:\local\include\memcached
C:\Users\Trond\build\memcached> copy include\memcached c:\local\include\memcached

So let's go ahead and build libcouchbase! 

C:\Users\Trond\build\memcached> cd ..\libcouchbase
C:\Users\Trond\build\libcouchbase> nmake -f NMakefile install

I guess that most Windows developers don't use nmake during their development, but use the full IDE instead. That's why I've created a project you may open in the vacuum project. So feel free to open that project now, and it should build without any problems. 

Now we're going to need a Couchbase server we can connect to. If you don't have any running, you should download and install one now. 

Let's go ahead and create the spool directory and start the vacuum server...

C:\Users\Trond\build\vacuum\Debug> mkdir c:\vacuum
C:\Users\Trond\build\vacuum\Debug> vacuum -h 127.0.0.1:8091

And you can start copy JSON files into C:\vacuum and see them being added to the Couchbase cluster!

Tuesday, January 24, 2012

So how do I use this "libcouchbase"?


Some of you may have noticed that we released Couchbase 1.8 earlier today, and a new set of smart clients for various languages. For me personally this is a milestone, because libcouchbase is now a
supported client for the C language.

So why do I care about that? Well, libcouchbase started out of my needs to easily test various components of the server. Since I did most of my development on the components on the server implemented in C, it made sense for me to use C for my testing.

I've received some questions on how libcouchbase work in a multithreaded context, so I should probably start off by clarifying that: libcouchbase doesn't use any form of locking to protect it's internal data structures, but it doesn't mean you can't use libcouchbase in a multithreaded program. All it means is that you as a client user must either use locking to protect yourself from accessing the libcouchbase instance from multiple threads at the same time, or just let each thread operate on it's own instance of libcouchbase. One easy way to solve this is to have a "pool" of libcouchbase instances each thread pop and push its instance to whenever they need to access a Couchbase server. Access to this pool should be protected with a lock (but I guess you figured that out ;-)

In this blog post I'll create a demo program you may use to upload JSON documents into a Couchbase server. You'll find the complete source available at https://github.com/trondn/vacuum if you would like
to try the example.

The idea of this program is that it will "monitor" a directory and upload all files appearing there into a Couchbase cluster. I'm pretty sure most of you start thinking: "how do we do that in a portable way?". That's not an easy task to do, so I'm not even going to try to do that. I'll try to write it in a semi-portable way so that it shouldn't be that hard to implement on other platforms. That means that I'm using the following limitations:

  • I'm using opendir and readdir to traverse the directory. This can easily be reimplemented with FindFirst and FindNext on Microsoft Windows.
  • Monitor of the directory means that I'm going to scan the directory, then sleep a given number of seconds before running another scan. I know some platforms supports subscribing of changes to the filesystem, but I'm not going to spend time on that (at least not right now ;-)).
  • To avoid file locking or accessing the file while others are writing the file, the clients should write the file into the directory with a leading "dot" in the filename, and then rename the file when they are done. The program ignores all files starting with a dot.

So let's jump to the code. The first piece of code that might be interesting to look at would be where we create the libcouchbase instance in main():

    instance = libcouchbase_create(host, user, passwd, bucket, NULL);
    if (instance == NULL) {
        fprintf(stderr, "Failed to create couchbase instance\n");
        exit(EXIT_FAILURE);
    }

The above code snippet creates the libcouchbase instance. There is no way you can use a static structure for this, because doing so will make it incredible hard to maintain binary compatibility. I like to be able to fix bugs within the library and release new versions you may use without having to recompile your program, and by hiding the internal datastructures from the clients makes it easier to ensure that the client don't depend on their size. The first parameter to libcouchbase_create is the name (and port) of the REST port for the couchbase server (default: localhost:8091). The second and third parameter is the credentials you'd like to use to connect to the REST port to get the pool information (default is to not authenticate). The forth parameter is the bucket you'd like to connect to, and if you don't specify a bucket you'll end up in the "default bucket". The fifth argument is a special object you may want to use if you are going to use "advanced" features in libcouchbase. Most users will probably just use the defaults and pass NULL here.

The next thing we need to do is to set up some callback handlers to be able to figure out what happens. In the example we're only going to use one operation (to load data into the cache) so we'll need to set up a handler to catch the result of storage operations. Unfortunately we may also encounter problems, so we need to set up an error handler (we'll get back to work in a bit).

    libcouchbase_set_storage_callback(instance, storage_callback);
    libcouchbase_set_error_callback(instance, error_callback);

Now that we've created and initialized the instance, we need to try to connect to the Couchbase cluster:

    libcouchbase_error_t ret = libcouchbase_connect(instance);
    if (ret != LIBCOUCHBASE_SUCCESS) {
        fprintf(stderr, "Failed to connect: %s\n",
                libcouchbase_strerror(instance, ret));
        exit(EXIT_FAILURE);
    }

Due to the fact that libcouchbase is fully asynchronous, all that happened above was that we initiated the connect. That means that we need to wait for the server to be connected to the Couchbase cluster and connect to the correct bucket. If our program should do other stuff now would be the time to do so, but since we don't have any other initialization to do we can just wait for it to complete:

    libcouchbase_wait(instance);

One of the "cool" features we've got in libcouchbase is that it provides an internal statistics interface, so we may tell it to collect timing information of the operations with the following snippet:

   if ((ret = libcouchbase_enable_timings(instance) != LIBCOUCHBASE_SUCCESS)) {
      fprintf(stderr, "Failed to enable timings: %s\n",
              libcouchbase_strerror(instance, ret));
   }

Our program is now fully initialized, and we can enter the main loop that looks like pretty much like:

   while (forever)
   {
      process_files();
      sleep(nsec);
   }

So how does our process_files() look like? I'm not going to make the example too big by pasting all of it, but the first piece in there looks like:

   if (de->d_name[0] == '.') {
       if (strcmp(de->d_name, ".dump_stats") == 0) {
           fprintf(stdout, "Dumping stats:\n");
           libcouchbase_get_timings(instance, stdout, timings_callback);
           fprintf(stdout, "----\n");
           remove(de->d_name);<
       }
       continue;
   }

As you see from the above code snippet we'll ignore all files that starts with a '.' except for the file named ".dump_stats". Whenever we see that file we dump the internal stats timings by using the timings_callback (I'll get back to that later).

The next thing we do is to try to read the file into memory and decode it's JSON before we try to get the "_id" field to use as a key. If all of that succeeds, we try to store the data in Coucbase with:

      int error = 0;
      ret = libcouchbase_store(instance, &error, LIBCOUCHBASE_SET,
                               id->valuestring, strlen(id->valuestring),
                               ptr, size, 0, 0, 0);
      if (ret == LIBCOUCHBASE_SUCCESS) {
         libcouchbase_wait(instance);
      } else {
         error = 1;
      }

The &error piece here is quite interesting. It is a "cookie" passed to the callback, so that I may know if I encountered a problem or not. You'll see how I'm using it when I discuss the storage_callback below.

This is basically all of the important logic in the example. I promised that I would get back to the different callbacks, so let's start by looking at the error callback:

   static void error_callback(libcouchbase_t instance,
                              libcouchbase_error_t error,
                              const char *errinfo)
   {
       /* Ignore timeouts... */
       if (error != LIBCOUCHBASE_ETIMEDOUT) {
           fprintf(stderr, "\rFATAL ERROR: %s\n",
                   libcouchbase_strerror(instance, error));
           if (errinfo && strlen(errinfo) != 0) {
               fprintf(stderr, "\t\"%s\"\n", errinfo);
           }
           exit(EXIT_FAILURE);
       }
   }

As you see from the above snippet libcouchbase will call the error_callback whenever a timeout occurs, but we just want to retry the operation. If we encounter a real error we print out an error message and terminate the program.

The next callback we use is the storage_callback. It is called when the store operation completed, so it is the right place for us to figure out if an error occured while storing the data. Our callback looks like:

   static void storage_callback(libcouchbase_t instance,
                                const void *cookie,
                                libcouchbase_storage_t operation,
                                libcouchbase_error_t err,
                                const void *key, size_t nkey,
                                uint64_t cas)
   {
      int *error = (void*)cookie;
       if (err == LIBCOUCHBASE_SUCCESS) {
           *error = 0;
       } else {
           *error = 1;
           fprintf(stderr, "Failed to store \"");
           fwrite(key, 1, nkey, stderr);
           fprintf(stderr, "\": %s\n",
                   libcouchbase_strerror(instance, err));
           fflush(stderr);
       }
   }

As you see we're storing the result of the operation in the integer passed as the cookie. The observant reader may see that we might as well could unlink the file and remove the memory from within the callback (if we provided that information as the cookie instead ;))

The last callback to cover is the timings callback we're using to dump out the timing statistics.

   static void timings_callback(libcouchbase_t instance, const void *cookie,
                                libcouchbase_timeunit_t timeunit,
                                uint32_t min, uint32_t max,
                                uint32_t total, uint32_t maxtotal)
   {
      char buffer[1024];
      int offset = sprintf(buffer, "[%3u - %3u]", min, max);
      switch (timeunit) {
      case LIBCOUCHBASE_TIMEUNIT_NSEC:
         offset += sprintf(buffer + offset, "ns");
         break;
      case LIBCOUCHBASE_TIMEUNIT_USEC:
         offset += sprintf(buffer + offset, "us");
         break;
      case LIBCOUCHBASE_TIMEUNIT_MSEC:
         offset += sprintf(buffer + offset, "ms");
         break;
      case LIBCOUCHBASE_TIMEUNIT_SEC:
         offset += sprintf(buffer + offset, "s");
         break;
      default:
         ;
      }

      int num = (float)40.0 * (float)total / (float)maxtotal;
      offset += sprintf(buffer + offset, " |");
      for (int ii = 0; ii < num; ++ii) {
         offset += sprintf(buffer + offset, "#");
      }

      offset += sprintf(buffer + offset, " - %u\n", total);
      fputs(buffer, (FILE*)cookie);
   }

When you request the timings from libcouchbase it reports all of the timing metrics collected by calling the timings callback. As you can see from the API you'll get the minimum, maximum value for the range, and the number of operations performed within that range. These metrics are not to be considered as exact numbers, because they depend on when what you do in your client code from the time you call the operation until you call libcouchbase_wait for the operation to complete.

So let's run the go ahead and run the program. I've prepopulated /var/spool/vacuum with a number of JSON files, to have the program do something.

trond@illumos ~> ./vacuum
sleeping 3 secs before retry..

From another withdow I execute the command:

trond@illumos ~> touch /var/spool/vacuum/.dump_stats

And when the timer expires in first window, it prints out:

Dumping stats:
[ 60 -  69]us |######################################## - 18
[ 70 -  79]us |## - 1
[240 - 249]us |## - 1
----
sleeping 3 secs before retry..

Hopefully this blog revealed how easy it is to use libcouchbase to communicate with a Couchbase cluster. We've got various clients for other programming languages like PHP and Ruby built on top of libcouchbase, so I can promise you that you'll see more functionallity added!

Thursday, January 12, 2012

Couchbase Server meets SmartOS!

I've loved Solaris since we first met back in 95. Since then I've been using Solaris as my primary os (including desktop). For a period of time I even ran Trusted Solaris 2.5 on my SS5 ;-) The kernel and all of the fantastic tools available makes it a superior platform for software development.

Ever since I started working for NorthScale (now Couchbase) I've done my very best to ensure that our stuff works on Solaris (if not I'd have a hard time doing any development ;), so getting it to work on SmartOS shouldn't be a big problem.

So far I've only been using the Sun Studio tools (I can't help it but I still find dbx superior to gdb...), but a few days ago I added a slave running SmartOS to my Jenkins cluster to see how much work it would be to get everything built with the tools and libraries I could install with pkgin. We do compile our software on different platforms and with different compilers, so I didn't expect too much trouble.

The "biggest" problem I had was to get libtool to stop trying to link 32bit object files into my 64 bit binaries. The workaround so far is to use:
CXX="g++ -m64 -L/opt/local/lib/amd64"
CC="gcc -m64 -L/opt/local/lib/amd64"

This was a small goal for me, but it will really ease my testing of a full cluster :-)

Now that I've got everything built on SmartOS, OpenIndiana, Soalris 10 I guess I should create packages for pkgin, IPS and SVr4 :)

Monday, January 9, 2012

Thank you Joyent, I love you!


I’ve always been a strong believer of that people should be able to choose the platform they feel suits their needs the most. If people want to make stupid decisions and not choose my beloved Solaris, I’m not going to stop them. This means that I need to ensure that the software I’m working on not only compiles, but also works on multiple platforms. In “the old days” I used to install a new os on my desktop box every time I upgraded my desktop (which always ran the latest bits of Solaris), but lately I’ve been using virtual machines to make it easier for myself ;)

You may wonder why I don’t just set up virtual machines in the cloud? The answer is pretty simple. I’m working from home, and I’ve had my share of problems with my ISP. I don’t want to end up in a situation where I can’t do my work just because my ISP fails to keep me connected with the rest of the world...
I guess it must be roughly a year ago since I decided to replace all of my VirtualBox instances running on a handful of old machines with KVM on top of Debian on my server. With the server running there I moved more and more stuff off my desktop box, and I ended up in a situation I really didn’t like. I had the services I “needed” running on top of a server without mirrored disks. To save money I had ordered that dell server with just a single disk. I’ve had enough disks dying on me over the years, so to me this feels like hiking in the middle of the freeway at midnight.. To get out of this situation I created an iSCSI share on my OpenIndiana box on top of a ZFS mirror that I connected to the Debian box. Now I could sleep a little bit better at night...

I had noticed the releases of SmartOS, and it looked really cool! Unfortunately for me I didn’t have a machine I could try it on, but luckily for me Debian gave me a helping hand in December to speed up the process! After upgrading packages with aptitude my box would no longer boot! I don’t have a keyboard/monitor attached to the box, so I had to bring the server into my office to “debug” the issue. I didn’t figure out why it wasn’t booting with the new kernel, but I was able to boot it with the old kernel and get the stuff I needed off the box. I could have spent more time trying to figure out why it was failing, but instead I took this as a golden opportunity to try out SmartOS. Doing so brought nothing but joy into my life!!!!!

After booting off the USB stick I had to answer a couple of questions to configure the system for the first time, and I was ready to create my first machine. I followed the instructions in "How to create a Virtual Machine in SmartOS" and I had my first VM up’n running in less than a minute! So simple, and yet so powerful!

Roughly a week later my box looks like:
[root@00-26-b9-85-bd-92 ~]# vmadm list
UUID                                  TYPE  RAM      STATE             ALIAS     
80658f56-0eb3-405f-a6eb-690461c2d9ce  OS    256      running           -       
9c441211-bb77-446f-abec-2291039aeca2  OS    256      running           smartos64 
b0e34876-cd7a-4922-ad6e-921452d34359  OS    512      running           jenkins   
13f4223b-a2c1-400a-b682-79372c3ba846  KVM   1024     running           solaris11 
7bad78f1-d202-4dfe-97f6-e421e8da8d58  KVM   1024     running           ubuntu64  
8e042001-bc79-48eb-a0bc-704ca64f20e0  KVM   1024     running           debian    
e1710b31-0270-43a3-89dc-71398ba3630a  KVM   1024     running           windows  
f165261a-6a27-4ee3-a6d3-f3814cf69bd6  KVM   1024     running           ubuntu32  

My "jenkins" vm is just running the Jenkins CI web application for http://www.norbye.org/jenkins/, and it connects via ssh into the other VMs (and a couple of other machines) to build software there. This is part of my automatic build process. I've got it on my ever growing todo list to set up NIS/LDAP, but in the mean time I'm just sync'ing the user definitions around so that I can log into all of the machines.

But wait, I said I didn’t like to keep stuff on filesystems that isn’t mirrored, and choosing another OS doesn't change this? Right now I don’t care if the disk dies, because I can easily recreate all of the vm’s from scratch (i’ve got the descriptions I used to create the vm’s stored somewhere else). All “users” on the vm’s mount their home directory from my NFS server, so none of those files would get lost. I guess I could use zfs send/receive to back up the vm itself while I’m waiting for another disk for the box. 

So is there anything I miss from the current release, or is it perfect? There is one thing I really miss, and that is the ability to use the alias instead of the uuid when I’m using vmadm. I know that the alias doesn’t have to be unique, but if the alias is unique it would be a lot easier to use (instead of having to do a vmadm list first).


The second thing I’d love to see would be something like:


# vmadm bootinstall name iso-file


it would expand into something like:


cp iso-file uuid/root/cdrom.iso
vmadm boot uuid order=cd,once=d cdrom=/cdrom.iso,ide
vmadm info uuid vnc

But hey, if this is the biggest problems I’ve got with SmartOS I must be pretty happy with it. After all how often do you really create and install new VMs? The fact that I may use the tools I know and love (dtrace, zfs, smf etc) is just awesome!

Thank you Joyent for bringing this to my fingertips! 

Wednesday, October 5, 2011

libcouchbase - Explore the full features of your Couchbase server from C

I started the implementation of libcouchbase almost year ago out of my personal need to test the inner workings of Couchbase. Since I work in "core" of Couchase I needed an easy way to test out the changes I made there. At that time there were only clients for Java, Python and C# with support for REST interface to Couchbase. I'm no fan of Python, and my Solaris machine doesn't support C# so Java was my only option. I do like Java a lot, so that was my language of choice initially when I had to test something. Unfortunately I do find it a bit of extra hassle having to deal with multiple languages (and that I can't link the test code into the core to test it "from the inside" ;-)) Given that I set off trying to come up with an alternative.

Over the past few years I have put some effort into libmemcached, so the first thing I did was look at what it would take to add support for a "smart client behavior" into libmemcached. If that would be possible I could have a full featured library people maintained. Unfortunately it turned out that it wasn't straight forward to add what I wanted due to the way the library works. libmemcached would initialize it's list of server structures at initialization time, and map the key to the server it would belong to. For Couchbase I would have to be able to replace the list of servers at any time. In addition to that Couchbase uses a two-level mapping of the key. First we map the key to a vbucket, then we try to look up the server where the bucket reside. At the time I felt that I would have to change too much of the inner workings of libmemcached to get it to work for Couchbase (and given the fact that libmemcached isn't a vendor-specific library I felt it was the wrong thing to do). Since I didn't want to sit on a "ticking bomb" when it comes to trying to merge my private "patch" to libmemcached with the upstream changes I decided to just write something that would fulfill my needs. I think it's worth mentioning that libcouchbase isn't meant to be a replacement for libmemcached, but an alternative for those of you who want / needs to explore the full features of Couchbase.

The "quick'n'dirty" solution would have been to just hardcode the stuff I needed into various test programs and use copy'n'paste until I met the grim reaper, but that wouldn't have been particulary innovative (or fun). Instead I sat down and defined some criterias for the library:

  • It must all asynchronously
    I believe that all libraries should provide an asynchronously interface, and if the library provides a synchronously interface it should be built on top of the asynchronously interface and wait for the completion.
  • No internal locking
    Using locks internally may lead to lock contention. If I can avoid locking inside the library it will potentially scale better. It will be left entierly up to the client of the library to protect the variables from access by multiple threads.
  • It has to be cross platform!
    I do all of my development on Solaris, but I do respect that others may have different needs than myself. Some people prefer Mac OS, some prefer Windows and I've even heard of people using Linux. Why shouldn't all of them be able to use libcouchbase?
  • It shall not depend of a "shit load" of other modules
    It is not that I suffer from the not-invented-here-syndrome, but I do find it a PITA to have to compile tons of other libraries (which may have additional dependencies etc) just to get the library working (and keeping all of them in sync with each other as new releases comes). All library use should be justified.
  • Binary compatibility
    The binary interface should be stable and not change all the time. Coming up with a good API isn't easy, so during development the api is expected to evolve. If a client only use a committed interface he shouldn't have to do _anything_ except replacing the shared object when the new version is released.
  • No GPL
    I just can't stand the GPL license.

Although I started working on libcouchbase a year ago, it doesn't  mean that I have worked full time on it. My primary job is working on the core, so I've only extended the library when I've needed the functionality for my own testing. More recently I'm happy to say I've received some contributions from some people who've picked it up and used it and from some other Couchbase developers (thanks Sergey, Paul, Sebastian, Jan, and Bill!).  No doubt, there's something we can do better, so please drop an email to the Couchbase development mailing list (couchbase@googlegroups.com) if there's something you think needs some fixin'. I still think that the library has some rough edges that needs to be sorted out before you can start using it in production ;-)

Building the software

If you're trying to build libcoucbase on Solaris / *BSD / MacOS or Linux you can just use the "configure && make" way you're so used to. For the Windows users I've written an NMakefile you may use to compile and install the various bits. Since I'm doing almost all of my development I might have done stuff "wrong", but I'll be happy if you drop me an email telling me what I need to change.

I've been using Windows 7 with Microsoft Developer Studio 2010 to build and test the library. Execute the following commands to build and install the bits:


nmake -f NMakefile install

By default it will use c:\local as the root directory (to make it easy for you to create an installer or move it wherever you want). You can always override this by specifying INSTALL like:

nmake -f NMakefile INSTALL=c:\couchbase install

Prerequisites

We do have some prerequisites for libcouchbase. You might find binary packages available for your platform, but it shouldn't be very hard to build from source.

1) The header files from the engine branch of memcached.

Simply copy the memcached directory from https://github.com/memcached/memcached/tree/engine-pu/include to c:\local\include (or whatever you choose as your directory)

2) A sasl implementation.

libcouchbase needs to run SASL authentications to the different buckets. If you don't want to install a full featured SASL library you could always install "libisasl" from: https://github.com/membase/libisasl

3) libvbucket

The mapping between a key and the vbucket (and to locate which server the vbucket is located on) is provided by this library. https://github.com/membase/libvbucket

4) libevent (optional)

libcouchbase allows plugins to different event notification frameworks. The default framework for UNIX-like systems is libevent, so unless you're going to create your own plugin you might want to install this. Please note that the default for windows is something else so you don't need this at all for windows.

So how does the library work?


The primary idea with the library is that everything should be event driven, and that a callback should be triggered when something happens. That means that you must set up callbacks to handle everything you want. There is no simple:

std::string myvalue = libcoucbase->get("hello");

but you can easily implement that if you want.

Given the fact that there is no locking within libcouchbase you may think that it's not suited for use in a multithreaded process, but thats not true. As long as you don't use the same handle to libcouchbase from multiple threads you can use as many threads as you want (if you want to use the same libcouchbase instance from multiple threads you need to provide locking)

Enough talk, show me the code!

All you need to do in your program to start using libcouchbase is to include libcouchbase/couchbase.h. and link with libcouchbase. The first thing you would need to do is to create an instance to libcouchbase:

#include
...

const char *host = NULL; /* Use localhost:8091 */
const char *username = NULL; /* No user specified */
const char *password = NULL; /* No password specified */
const char *bucket = NULL; /* use default bucket */
struct libcouchbase_io_opt_st *io = NULL; /* Use default io options */

libcouchbase_t handle = libcouchbase_create(host, username, password,
                                            bucket, io);

if (handle == NULL) {
   /* Failed to create the handle */
}

The code fragment above does nothing more than allocate the handle to libcouchbase, and it did not try to connect it to the server to receive the list of servers etc. The username/password combination here will be used to authenticate to the REST server listening on the host port. With the handle in place we should set up the first callback: the error handler. Let's create a simple error callback that prints out the error and terminates the application:

static void error_callback(libcouchbase_t instance,
                           libcouchbase_error_t error,
                           const char *errinfo)
{
    fprintf(stderr, "%s", libcouchbase_strerror(instance, error));
    if (errinfo) {
        fprintf(stderr, ": %s", errinfo);
    }
    fprintf(stderr, "\n");
    exit(EXIT_FAILURE);
}

The callback is installed with:

libcouchbase_set_error_callback(handle, error_callback);

Now that we've got our error callback installed, we can start connecting to the server and receive the list of servers. Since everything is asyncronous we need to wait for the connect to complete (I'm not going to show you how to use the library in a shared event loop in this example).

libcouchbase_connect(handle);
// Wait for the connect to compelete
libcouchbase_wait(handle);

At this time we've got a "working" instance to libcouchbase we may use. So let's go ahead and store some items in the cache. If we don't care about the response message from the server we don't need to set up a callback, but to make the example more complete lets create a callback that terminates the program if we fail to store one of the items:

static void storage_callback(libcouchbase_t instance,
                             const void *cookie,
                             libcouchbase_storage_t operation,
                             libcouchbase_error_t error,
                             const void *key, size_t nkey,
                             uint64_t cas)
{
    if (error != LIBCOUCHBASE_SUCCESS) {
        fprintf(stderr, "Failed to store \"");
        fwrite(key, nkey, 1, stderr);
        fprintf(stderr, "\"\n");
        exit(EXIT_FAILURE);
    }
}

I don't have a good example of what we want to store, so let's just loop and store some numbers:

libcouchbase_set_storage_callback(instance, storage_callback);

for (int ii = 0; ii < 10; ++ii) {
    char key[80];
    size_t nkey = sprintf(key, "%d", ii);
    libcouchbase_store(handle, NULL, LIBCOUCHBASE_SET,
                       key, nkey, &ii, sizeof(ii), 0, 0, 0);
}
/* Wait for all of them to complete */
libcouchbase_wait(handle);

Timings

One of the things I find cool about libcouchbase is the ability to get some timings statistics about the current traffic. Everyone familiar to DTrace loves the ability to dump a histogram representing whatever you decided to measure. A lot of the times when you're running your stuff in production you might want to look at the response times you've got from your Couchbase cluster. In order to help you do that I've added some relatively lightweight timings you may use. Due to the asyncronous nature of libcouchbase (and that you're responsible to drive the event loop) you may impose a large effect on the timings so that they no longer represents the truth.. Anyway, let's add an example that utilize them to crate a histogram of the store section above (but instead of running all of them in a single batch, use a
synchronous set.

libcouchbase_enable_timings(handle);
for (int ii = 0; ii < 10; ++ii) {
    char key[80];
    size_t nkey = sprintf(key, "%d", ii);
    libcouchbase_store(handle, NULL, LIBCOUCHBASE_SET,
                       key, nkey, &ii, sizeof(ii), 0, 0, 0);
    libcouchbase_wait(handle);
}

/* Get the current timings */
libcouchbase_get_timings(handle, stdout, timings_callback);

/* Stop collecting timing information */
libcouchbase_disable_timings(handle);

So how does this "timings_callback" look like? That's completely up to you, but we could create a simple histogram with the following code:

static void timings_callback(libcouchbase_t instance, const void *cookie,
                            libcouchbase_timeunit_t timeunit,
                            uint32_t min, uint32_t max,
                            uint32_t total, uint32_t maxtotal)
{
    char buffer[1024];
    int offset = sprintf(buffer, "[%3u - %3u]", min, max);
    switch (timeunit) {
    case LIBCOUCHBASE_TIMEUNIT_NSEC:
        offset += sprintf(buffer + offset, "ns");
        break;
    case LIBCOUCHBASE_TIMEUNIT_USEC:
        offset += sprintf(buffer + offset, "us");
        break;
    case LIBCOUCHBASE_TIMEUNIT_MSEC:
        offset += sprintf(buffer + offset, "ms");
        break;
    case LIBCOUCHBASE_TIMEUNIT_SEC:
        offset += sprintf(buffer + offset, "s");
        break;
    default:
        ;
    }

    int num = (float)40.0 * (float)total / (float)maxtotal;
    offset += sprintf(buffer + offset, " |");
    for (int ii = 0; ii < num; ++ii) {
        offset += sprintf(buffer + offset, "#");
    }

    offset += sprintf(buffer + offset, " - %u\n", total);
    fputs(buffer, (FILE*)cookie);
}

This would generate something like:

[140 - 149]us |# - 2
[150 - 159]us |## - 3
[160 - 169]us |######################################## - 47
[170 - 179]us |###################### - 26
[180 - 189]us |########### - 14
[190 - 199]us |# - 2
[210 - 219]us | - 1
[220 - 229]us | - 1
[230 - 239]us | - 1
[250 - 259]us | - 1
[280 - 289]us | - 1
[400 - 409]us | - 1

Source code

I guess you want to try the program yourself :)



/* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
#include
#include
#include

static void error_callback(libcouchbase_t instance,
                           libcouchbase_error_t error,
                           const char *errinfo)
{
   fprintf(stderr, "%s", libcouchbase_strerror(instance, error));
   if (errinfo) {
      fprintf(stderr, ": %s", errinfo);
   }
   fprintf(stderr, "\n");
   exit(EXIT_FAILURE);

}

static void storage_callback(libcouchbase_t instance,
                             const void *cookie,
                             libcouchbase_storage_t operation,
                             libcouchbase_error_t error,
                             const void *key, size_t nkey,
                             uint64_t cas)
{
   if (error != LIBCOUCHBASE_SUCCESS) {
      fprintf(stderr, "Failed to store \"");
      fwrite(key, nkey, 1, stderr);
      fprintf(stderr, "\"\n");
      exit(EXIT_FAILURE);
   }
}

static void timings_callback(libcouchbase_t instance, const void *cookie,
                             libcouchbase_timeunit_t timeunit,
                             uint32_t min, uint32_t max,
                             uint32_t total, uint32_t maxtotal)
{
   char buffer[1024];
   int offset = sprintf(buffer, "[%3u - %3u]", min, max);
   switch (timeunit) {
   case LIBCOUCHBASE_TIMEUNIT_NSEC:
      offset += sprintf(buffer + offset, "ns");
      break;
   case LIBCOUCHBASE_TIMEUNIT_USEC:
      offset += sprintf(buffer + offset, "us");
      break;
   case LIBCOUCHBASE_TIMEUNIT_MSEC:
      offset += sprintf(buffer + offset, "ms");
      break;
   case LIBCOUCHBASE_TIMEUNIT_SEC:
      offset += sprintf(buffer + offset, "s");
      break;
   default:
      ;
   }

   int num = (float)40.0 * (float)total / (float)maxtotal;
   offset += sprintf(buffer + offset, " |");
   for (int ii = 0; ii < num; ++ii) {
      offset += sprintf(buffer + offset, "#");
   }

   offset += sprintf(buffer + offset, " - %u\n", total);
   fputs(buffer, (FILE*)cookie);
}

int main(int argc, char **argv)
{
   const char *host = NULL; /* Use localhost:8091 */
   const char *username = NULL; /* No user specified */
   const char *password = NULL; /* No password specified */
   const char *bucket = NULL; /* use default bucket */
   struct libcouchbase_io_opt_st *io = NULL; /* Use default io options */

   libcouchbase_t handle = libcouchbase_create(host, 

                                               username, 
                                               password,
                                               bucket, io);

   if (handle == NULL) {
      /* Failed to create the handle */
      fprintf(stderr, "Failed to create instance\n");
      exit(EXIT_FAILURE);
   }
   libcouchbase_set_error_callback(handle, error_callback);
   libcouchbase_connect(handle);
   // Wait for the connect to compelete
   libcouchbase_wait(handle);
   libcouchbase_set_storage_callback(instance, storage_callback); 
   libcouchbase_enable_timings(handle);
   for (int ii = 0; ii < 100; ++ii) {
      char key[80];
      size_t nkey = sprintf(key, "%d", ii);
      libcouchbase_store(handle, NULL, LIBCOUCHBASE_SET,
                         key, nkey, &ii, sizeof(ii), 0, 0, 0);
      libcouchbase_wait(handle);
   }

   /* Get the current timings */
   libcouchbase_get_timings(handle, stdout, timings_callback);

   /* Stop collecting timing information */
   libcouchbase_disable_timings(handle);
   libcouchbase_destroy(handle);

   return 0;
}