Load balancing and improved failover in Hector

Balance the load, woman!

I’ve added a very simple load balancing feature, as well as improved failover behavior to Hector. Hector is a Java Cassandra client, to read more about it please see my previous post Hector – a Java Cassandra client.

In version 0.5.0-6 I added poor-man’s load balancing as well as improved failover behavior.

The interface CassandraClientPool used to have this method for obtaining clients:

/**
 * Borrows a client from the pool defined by url:port
 * @param url
 * @param port
 * @return
 */
CassandraClient borrowClient(String url, int port)
    throws IllegalStateException, PoolExhaustedException, Exception;

Now with the added LB and failover it has:

/**
 * Borrow a load-balanced client, a random client from the array of given client addresses.
 *
 * This method is typically used to allow load balancing b/w the list of given client URLs. The
 * method will return a random client from the array of the given url:port pairs.
 * The method will try connecting each host in the list and will only stop when there's one
 * successful connection, so in that sense it's also useful for failover.
 *
 * @param clientUrls An array of "url:port" cassandra client addresses.
 *
 * @return A randomly chosen client from the array of clientUrls.
 * @throws Exception
 */
CassandraClient borrowClient(String[] clientUrls) throws Exception;

And usage looks like that:

// Get a connection to any of the hosts cas1, ca2 or cas3
CassandraClient client = pool.borrowClient(new String[] {"cas1:9160", "cas2:9160", "cas3:9160"});

So, when calling borrowClient(String[]) the method randomly chooses any of the clients in the array and connects to it. That’s what I call poor man’s load balancing, just plain dumb random, not real load balancing. By all means, true load balancing which takes into account performance measurements such as response time and throughput is infinitely better than the plain random selection I’m employing here and in my opinion should be left out for your ops folks to deal with and not to the program, however, if you only need a very simplistic approach of random selection, then this method may suite your needs.

A nice side effect of using this method is improved failover. In previous versions hector implemented failover, but in order to find out about the ring structure it had to connect to at least one host in the ring first and query it to learn about the rest. The result was that if a new connection is made and it’s so unfortunate that this new connections is made to unavailable host, then this new client cannot connect to the host to learn about other live hosts so it fails right away. With this new method which sends an array of hosts the client keeps connecting to hosts in the list in random order until it finds one that’s up. In the example above the client may choose to connect to cas2 first; if cas2 is down it’ll try to connect to (say) cas3 and if cas3 is also down it’ll try to connect to cas1; only if all three hosts are down will it give up and return an error. Failing to connect to hosts is considered an error, but a recoverable error, so it’s transparent to the client of hector but is reported to JMX and has its own special counter (RecoverableLoadBalancedConnectErrors).


Hector – a Java Cassandra client

UPDATE: I added a downloads section, so you may simply download the jar and sources if you’re not into git or maven.

UPDATE 2: I added license clarification; the license it MIT, which is the most permissive license I know of and basically lets you do anything with the software: use it commercially or uncommercially, copy it, fork it (but I’ll be happy to accept patches and committers) and whatnot. I added a LICENSE file and over time I’ll add that block of comment to every file.

In the Greek Mythology, Hector was the builder of Troy, the greatest warrior ever and brother of Cassandra.

Nowdays, Cassandra is a high scale database and Hector is the Java client I’ve written for it.

Over the last couple of days I got the the conclusion that the java client I’ve been using so far to speak to cassanrda wasn’t satisfactory. I used the one simply called cassandra-java-client, which is a good start but had some shortcomings I could just not live with (no support for Cassandra v0.5, no JMX and no failover). So I’ve written my own.

For anyone not familiar with cassanra, it’s client API is just a simple thrift client. This means that, unlike other datastore clients such as jdbc etc, the client provided has somewhat limiter functionality; It can sent messages to cassanra, write values and read values of course, but other client goodies required for large scale applications are not provided, features such as monitoring, connection pooling etc. The client I initially used provides connection pooling, which is a very nice start, but I decided it was missing too much so I’d write my own.

As a good open-source citizen, I initially contacted the authors of cassandra-java-client asking their permission to contribute and make the suggested improvements, but after weeks without reply I realized I’ll need to go solo. I started with the concepts captured by the folks who had built the java-client, but pretty soon the code has morphed to be something completely different.

Here’s how code that uses Hector looks like. This is an implementation of a simple distributed hashtable over cassandra. By the virtue of cassandra, this hashtable can grow pretty large:

  /**
   * Insert a new value keyed by key
   * @param key Key for the value
   * @param value the String value to insert
   */
  public void insert(final String key, final String value) throws Exception {
    execute(new Command(){
      public Void execute(final Keyspace ks) throws Exception {
        ks.insert(key, createColumnPath(COLUMN_NAME), bytes(value));
        return null;
      }
    });
  }
 
  /**
   * Get a string value.
   * @return The string value; null if no value exists for the given key.
   */
  public String get(final String key) throws Exception {
    return execute(new Command(){
      public String execute(final Keyspace ks) throws Exception {
        try {
          return string(ks.getColumn(key, createColumnPath(COLUMN_NAME)).getValue());
        } catch (NotFoundException e) {
          return null;
        }
      }
    });
  }
 
  /**
   * Delete a key from cassandra
   */
  public void delete(final String key) throws Exception {
    execute(new Command(){
      public Void execute(final Keyspace ks) throws Exception {
        ks.remove(key, createColumnPath(COLUMN_NAME));
        return null;
      }
    });
  }

Out of the box Cassanra provides a raw thrift client, which is OK, but lacks many features essential to real world clients. I’ve built Hector to fill this gap.

Here are the high level features of Hector, currently hosted at github.

  • A high-level object oriented interface to cassandra. As noted before, Cassandra’s out of the box client is a thrift client, which isn’t always that nice and clean to work with. I wanted to provide higher level and cleaner API. This part was mainly inspired by the mentioned cassandra-java-client. The API is defined in the Keyspace interface. See for example methods such as Keyspace.insert() and keyspace.getColumn()
  • Failover support. Cassandra is a distributed data store and it may handle very well one or several hosts going down. However, out of the box thrift provides no support for failing clients. What it the client is configured to connect a cassandra host that just happened to be down right now? In hector, if a client is connected to one host in the ring and this host goes down, the client will automatically and transparently search for other available hosts to perform its operation before giving up  and returning an error to its user. There are currently 3 ways to configure the failover policy: FAIL_FAST (no retry, just fail if there are errors, nothing smart), ON_FAIL_TRY_ONE_NEXT_AVAILABLE (try one more host before giving up) and ON_FAIL_TRY_ALL_AVAILABLE (try all available hosts before giving up). See CassandraClient.FailoverPolicy.
  • Connection pooling. This is a real necessity for high scale applications. The usual pattern for DAOs (Data Access Objects) is large number of small reads/writes. Clients cannot afford to open a new connection with each and every request, not only because of the overhead in the tcp handshake (thrift uses tcp), but also because of the fact that sockets remain in TIME_WAIT so a client may easily run out of available sockets if it operates fast enough. This part was also inspired by cassandra-java-client but was improved in my version. Hector provides connection pooling and a nice framework that manages all its gory details.
  • JMX support. It’s a widely known fact that applications have a life of their own. You built it to do X but it does Y b/c you didn’t expect Z to happen. Running an application without the ability to monitor it is like walking blindfolded on a dark highway; sooner or later you’ll get hit by something. Hector exposes JMX for many important runtime metrics, such as number of available connections, idle connections, error statistics and more.
  • Support for the Command design pattern to allow clients to concentrate on their business logic and let hector take care of the required plumbing. This is demonstrated in the code above.

I’ve been using hector internally, at outbrain and so far so good. I’d be happy to get the comminuty feedback – API, implementation, features and so on and hope you can find it useful.


Running Cassandra as an embedded service

While developing an application at outbrain, using Cassandra I was looking for a good way to test my app. The application consists of a Cassandra Client package, some Data Access Objects (DAOs) and some bean object that represent the data entities in cassandra. I wanted to test them all.

As unit test tradition goes, my requirement was zero-configuration, zero preparation, no external dependencies, full isolation, fully reproducible results and fast. Database testing has always been a challenge in this perspective, for example when testing SQL clients in java often HSQLDB is used to to mock the database. Cassandra, however, did not have something ready just yet so I had to build it.

One way to go was to setup a cassandra instance just for unit testing. There are many downsides to this approach, such as it’s not zero-configuration, tests need to cleanup before they execute, if two tests are run at the same time by two developers they can collide and change the results in unexpected way, it’s slow… out of the question, not good.

Enter the embedded cassandra server.

With the help of the community I’ve built an embedded cassandra service ideal for unit testing and perhaps other uses. I’ve also built a cleanup utility that helps wipe out all data before the service starts running so the combination of both provides isolation etc. Now each test process runs an in-process, embedded instance of cassandra.

Below is the source code, already committed to cassandra SCM on trunk. If you want to use it for the current stable release(0.5.0) only a small package rename is required (in trunk some classes moved a bit), and it’s presented at the end of the post.

The embedded service:

package org.apache.cassandra.service;
 
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
 
import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.io.util.FileUtils;
import org.apache.cassandra.thrift.CassandraDaemon;
import org.apache.thrift.transport.TTransportException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
/**
 * An embedded, in-memory cassandra storage service that listens
 * on the thrift interface as configured in storage-conf.xml
 * This kind of service is useful when running unit tests of
 * services using cassandra for example.
 *
 
 * This is the implementation of https://issues.apache.org/jira/browse/CASSANDRA-740
 *
 
 * How to use:
 * In the client code create a new thread and spawn it with its {@link Thread#start()} method.
 * Example:
 *
 *      // Tell cassandra where the configuration files are.
        System.setProperty("storage-config", "conf");
 
        cassandra = new EmbeddedCassandraService();
        cassandra.init();
 
        // spawn cassandra in a new thread
        Thread t = new Thread(cassandra);
        t.setDaemon(true);
        t.start();
 
 *
 * @author Ran Tavory (rantav@gmail.com)
 *
 */
public class EmbeddedCassandraService implements Runnable
{
 
    CassandraDaemon cassandraDaemon;
 
    public void init() throws TTransportException, IOException
    {
        cassandraDaemon = new CassandraDaemon();
        cassandraDaemon.init(null);
    }
 
    public void run()
    {
        cassandraDaemon.start();
    }
}

The data cleaner:

package org.apache.cassandra.contrib.utils.service;
 
import java.io.File;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
 
import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.io.util.FileUtils;
 
/**
 * A cleanup utility that wipes the cassandra data directories.
 *
 * @author Ran Tavory (rantav@gmail.com)
 *
 */
public class CassandraServiceDataCleaner {
 
    /**
     * Creates all data dir if they don't exist and cleans them
     * @throws IOException
     */
    public void prepare() throws IOException {
        makeDirsIfNotExist();
        cleanupDataDirectories();
    }
 
    /**
     * Deletes all data from cassandra data directories, including the commit log.
     * @throws IOException in case of permissions error etc.
     */
    public void cleanupDataDirectories() throws IOException {
        for (String s: getDataDirs()) {
            cleanDir(s);
        }
    }
    /**
     * Creates the data diurectories, if they didn't exist.
     * @throws IOException if directories cannot be created (permissions etc).
     */
    public void makeDirsIfNotExist() throws IOException {
        for (String s: getDataDirs()) {
            mkdir(s);
        }
    }
 
    /**
     * Collects all data dirs and returns a set of String paths on the file system.
     *
     * @return
     */
    private Set getDataDirs() {
        Set dirs = new HashSet();
        for (String s : DatabaseDescriptor.getAllDataFileLocations()) {
            dirs.add(s);
        }
        dirs.add(DatabaseDescriptor.getLogFileLocation());
        return dirs;
    }
    /**
     * Creates a directory
     *
     * @param dir
     * @throws IOException
     */
    private void mkdir(String dir) throws IOException {
        FileUtils.createDirectory(dir);
    }
 
    /**
     * Removes all directory content from file the system
     *
     * @param dir
     * @throws IOException
     */
    private void cleanDir(String dir) throws IOException {
        File dirFile = new File(dir);
        if (dirFile.exists() && dirFile.isDirectory()) {
            FileUtils.delete(dirFile.listFiles());
        }
    }
}

And an example test that uses both:

package org.apache.cassandra.contrib.utils.service;
 
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
 
import java.io.IOException;
import java.io.UnsupportedEncodingException;
 
import org.apache.cassandra.service.EmbeddedCassandraService;
import org.apache.cassandra.thrift.Cassandra;
import org.apache.cassandra.thrift.ColumnOrSuperColumn;
import org.apache.cassandra.thrift.ColumnPath;
import org.apache.cassandra.thrift.ConsistencyLevel;
import org.apache.cassandra.thrift.InvalidRequestException;
import org.apache.cassandra.thrift.NotFoundException;
import org.apache.cassandra.thrift.TimedOutException;
import org.apache.cassandra.thrift.UnavailableException;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;
import org.junit.BeforeClass;
import org.junit.Test;
 
/**
 * Example how to use an embedded and a data cleaner.
 *
 * @author Ran Tavory (rantav@gmail.com)
 *
 */
public class CassandraServiceTest {
 
    private static EmbeddedCassandraService cassandra;
 
    /**
     * Set embedded cassandra up and spawn it in a new thread.
     *
     * @throws TTransportException
     * @throws IOException
     * @throws InterruptedException
     */
    @BeforeClass
    public static void setup() throws TTransportException, IOException,
            InterruptedException {
        // Tell cassandra where the configuration files are.
        // Use the test configuration file.
        System.setProperty("storage-config", "../../test/conf");
 
        CassandraServiceDataCleaner cleaner = new CassandraServiceDataCleaner();
        cleaner.prepare();
        cassandra = new EmbeddedCassandraService();
        cassandra.init();
        Thread t = new Thread(cassandra);
        t.setDaemon(true);
        t.start();
    }   
 
    @Test
    public void testInProcessCassandraServer()
            throws UnsupportedEncodingException, InvalidRequestException,
            UnavailableException, TimedOutException, TException,
            NotFoundException {
        Cassandra.Client client = getClient();
 
        String key_user_id = "1";
 
        long timestamp = System.currentTimeMillis();
        ColumnPath cp = new ColumnPath("Standard1");
        cp.setColumn("name".getBytes("utf-8"));
 
        // insert
        client.insert("Keyspace1", key_user_id, cp, "Ran".getBytes("UTF-8"),
                timestamp, ConsistencyLevel.ONE);
 
        // read
        ColumnOrSuperColumn got = client.get("Keyspace1", key_user_id, cp,
                ConsistencyLevel.ONE);
 
        // assert
        assertNotNull("Got a null ColumnOrSuperColumn", got);
        assertEquals("Ran", new String(got.getColumn().getValue(), "utf-8"));
    }
 
    /**
     * Gets a connection to the localhost client
     *
     * @return
     * @throws TTransportException
     */
    private Cassandra.Client getClient() throws TTransportException {
        TTransport tr = new TSocket("localhost", 9170);
        TProtocol proto = new TBinaryProtocol(tr);
        Cassandra.Client client = new Cassandra.Client(proto);
        tr.open();
        return client;
    }
}

To use this source code in v0.5.0 a small package rename is required:
org.apache.cassandra.io.util.FileUtils => org.apache.cassandra.utils.FileUtils
org.apache.thrift.transport.TTransportException => org.apache.transport.TTransportException
org.apache.cassandra.thrift.CassandraDaemon => org.apache.cassandra.CassandraDaemon

One nifty detail: When running multiple tests serially, make sure to spawn each test in a separate JVM (fork mode) since cassandra doesn’t shut down all threads immediately. Running each in separate jvm ensures the previous test dies before the next one begins.


Introduction to NOSQL and cassandra, part 2

In part 1 of this talk I presented few of the theoretical concepts behind nosql and cassandra.

In this talk we deep dive into the Cassandra API and implementation. The video is again in Hebrew, but the slides are multilingual ;-)

  • Started with a short recap of some of RDBMS and SQL properties, such as ADIC, why SQL if very programmer friendly, but is also limited in its support for large scale systems.
  • Short recap of the CAP theorem
  • Short recap of what N/R/W are
  • Cassandra Data Model: Cassandra is a column oriented DB which follows a similar data model to Google’s BigTable
  • Do you know SQL? So you better start forgetting it, Cassandra is a different game.
  • Vocabulary:
    • Keyspace – a logical buffer for application data. For example – Billing keyspace, or statistics keyspace, appX keyspace etc
    • ColumnFamily – similar to SQL tables. Aggregates columns and rows
    • Keys (or Rows). Each set of columns is identified by a key. A key is unique per Column Family
    • Columns – the actual values. Columns are represented by triplets – (name, value, timestamp)
    • Super-Columns – Facebook’s addition to the BigTable model SuperColumns are columns who’s values is a list of Columns. (but this is not recursive, you can only have one level of super-columns)
  • One way to think of cassandra is as a key-value store, but with extra functionality:
    • Each key has multiple values. In Cassandra jargon those are Columns
    • When reading or writing data it’s possible to read/write a set of columns for one specific key (row) atomically. This set of columns may either be a specified by the list column names, or by a slice predicate, assuming the columns are sorted in some way (that’s a configuration parameter)
    • In a addition, a multi-get operation is supported and a row-range-read operation is supported as well.
    • Row-range-read operations are supported only of a partitioner is defined which supports that (configuration parameter)
  • Key concept: In SQL you add your data first and then retrieve it in ad-hoc manner using select queries and where clauses; In Cassandra you can’t do that. Data can only be retrieved by it’s row key, so you have to think about how you’re going to be reading your data before you insert it. This is a conceptual diff b/w SQL and Cassandra.
  • I covered the Cassandra API methods:
    • get
    • get_slice
    • multiget
    • multiget_slice
    • get_count
    • get_range_slice
    • insert
    • batch_insert
    • delete
    • (these are the 0.4 api method. In 0.5 it’s a little different)
  • Between N/R/W, N is set per keyspace; R is defined per each read operation (get/multiget/etc) and W is defined per write operation (insert/batch_insert/delete)
  • Applications play with their R/W values to get different effects, for example they use QUORUM to get high consistency levels, or DC_QUORUM for a balance of high consistency and performance, W=0 to have async writes with reduced consistency.
  • Cassandra defines different sorting orders on it’s columns. Sort order may be defined at the ColumnFamily level and is used to get a slice of columns, for example, read all columns that start with a… and end with z…
  • There are several out of the box sort types, such as ascii, utf, numeric and date; Applications may also add their own sorters; This is as far as I recall the only place where Cassandra allows external code to be hooked in.
  • Thrift is a protocol and a library for cross-process communication and is used by Cassandra. You define a thrift interface and then compile it to the language of your choosing – C++, Java, Python, PHP etc. This makes it very easy for cross-language processes to talk to each other.
  • Thrift is also very efficient serializing and  deserializing objects and is also space-efficient (much more than Java serialization is).
  • I did not have enough time to cover the Gossip protocol used by Cassandra internally to learn about the health of its hosts.
  • I also did not have enough time to cover the Repair-on-reads algorithm used by Cassandra to repair data inconsistencies lazily.
  • I did not have time to talk about consistent hashing, which is what cassandra implements internally to reduce overhead of joined or dropped hosts occurrences.

So, as you can see, this was an overloaded, 1h+ talk with a lot to grasp. Wish me luck implementing Cassandra into outbrain!


Maven Code Quality Dashboard and TeamCity

I’ve recently implemented a code-quality dashboard at outbrain for maven java projects and hooked it into the our TeamCity continuous integration server. I was very pleased with the result, but the process had a few hickups, so I thought I’d mention them here for future generations.

A code quality dashboard includes the following components:

  • Tests status – failed, passed and  skipped count along with good looking graphs
  • Code coverage report detailing all covered and uncovered lines and branches, including nice coverage graphs
  • Copy-Paste detection by CPD
  • FindBugs report
  • jDepend report

The process had two phases: phase one is where I add the dashboard report to maven’s site goal in my pom.xml and phase two is where I make this report available at TeamCity, which is a bit of a manual work bot not too bad.

To add those nice reports, edit your pom.xml to add:

  <reporting>
    <plugins>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>cobertura-maven-plugin</artifactId>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-pmd-plugin</artifactId>
        <version>2.3</version>
        <configuration>
          <linkXref>true</linkXref>
          <targetJdk>1.5</targetJdk>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-report-plugin</artifactId>
        <version>2.4.2</version>
      </plugin>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>jdepend-maven-plugin</artifactId>
      </plugin>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>findbugs-maven-plugin</artifactId>
        <version>2.0.1</version>
        <configuration>
          <xmlOutput>true</xmlOutput>
          <effort>Max</effort>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>dashboard-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </reporting>

Now, in theory, that would have been all. All you have to do is run mvn site and bang – you have the reports under target/site. That’s why maven is nice.

However, if you’re running a multi-module project then mvn-site is buggy… all links to the subproject are broken links. But no despair, here’s the solution – configure the site plugin to place its generated content where the site plugin expects it to be… yeah, I know it sounds confusing, the thing is that the site plugin has a bug so it’s links to the submodule projects are broken, but here’s an easy fix that worked for me (as long as the projects are only one directory deep under the parent pom.xml). In the parent pom.xml add:

      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-site-plugin</artifactId>
        <configuration>
          <outputDirectory>../target/site/${project.name}</outputDirectory>
        </configuration>
      </plugin>

Now the reports are fixed.

Next step is to add them into TeamCity.

Step one: Tell teamcity to collect the site artifacts (html, css, js…). Go to the build configuration and under Artifacts Paths add **/target/site/**/*

Step two: Add a Code Quality tab to the build results. You do that by ssh-ing to the teamc host and editing

vi /teamc/TeamCity/.BuildServer/config/main-config.xml

to add

<report-tab title="Code Quality" basePath="target/site/" startPage="dashboard-report-details.html" />

Here’s the result:

That’s it! Now run your build with mvn site and get those gorgeous looking reports right in your teamcity build results page.


Moved hosting away from #godaddy #sucks


This blog has moved away from GoDaddy hosting to bluehost. I don’t know how good bluehost is (so far it’s been OK) but I know for sure that GoDaddy is pretty darn awful.

Awful as in
  • So slow that it’s a nightmare to be editing posts online. I had to do them offline and then copy-paste (and reformat), what a waste of time.
  • So fragile that my pingdom monitor reports it unavailable for more than 5 minutes at least twice a day.
  • So unresponsive that I’m sometimes ashamed to share permalinks to my blog in fear it would be offline. Why did I even pay them?

I didn’t wait for the one year I paid up front to end, just packed my stuff and moved over to bluehost. I don’t know how good bluehost is, but at least it’s fun again to be editing online and my pingdom monitor hasn’t told me anything bad yet, so knock on wood, looking good so far.


Introduction to NOSQL and cassandra, part 1

I recently gave a talk at outbrain, where I work, about an introduction to no-sql and Cassandra as we’re looking for alternatives of scaling out our database solution to match our incredible growth rate.

NOSQL is a general name for many non relational databases and Cassandra is one of them.

This was the first session of two in which I introduced the theoretical background and explained few of the important concepts of nosql. In the second session, due next week, I’ll talk more specifically about Cassandra.

The talk is on youtube, video below, but it’s in Hebrew so I’ll share it’s outline in English here. Slides are enclosed as well.


  • SQL and relational DBs in general offer is a very good general purpose solution for many  applications such as blogs, banking, my cat’s site etc.
  • RDBMS provide ACID: Atomicity, Consistency, Isolation and Durability
  • RDBMS + SQL (the query language) + ACID provide a very nice and clean programming interface, suitable for banks, online merchants and many other applications, but not all applications really actually do require full ACID and one has to realize that ACID and SQL features are not without costs when systems need to scale out. Cost is not only in $$, it’s also in application performance and features.
  • The new generation of internet scale applications put very high demands on DB systems when it comes to scale and speed of operation but they don’t necessariry require all the good that’s in RDBMS, such as Full Consistency or Atomicity.
  • So, a new brand of DB systems has grown over the past 5 or so years – nosql, which either stands for No-SQL or Not-Only-SQL.
  • Leading actors in the nosql arena are Google with its BigTable, Amazon with Dynamo, Facebook with Cassandra and there’s more.
  • I presented intermediate solutions before going no-sql, namely RDBMS sharding which is very common and FriendFeed’s particularly interesting solution of application level indexing for using mysql with a schema-less data model.
  • CAP Theorem: At large scale systems you may only choose 2 out of the 3 desired attributes: Consistency, Availability and Partition-Tolerance. All three may not go hand in hand and application designers need to realize that.
  • A Consistent and Available system with no Partition-tolerance is a RDBMS system that comes to a halt if one of it’s hosts is down. That’s a very commonly used solution and perfect for small systems. This blog, for example, which uses Wordpress, also uses a single mysql server which, if happens to be down, will also take the blog down. However, for internet scale systems where at almost any point in time there’s a good chance that one of the nodes is either down, or there are network disruptions, the No-Partition-Tolerance approach just isn’t going to cut it and they will have to choose a different approach for providing their SLAs.
  • Systems that are Available at all times and are capable of handling Partitions must sacrifice their consistency. As it turns out, though, this isn’t bad as it seems, as there are pretty good alternatives for lower levels of consistently, one such solution is Eventual Consistency, which actually works pretty nicely for “social applications” such as Google’s Facebook’s and Outbrain’s
  • I introduced the concept of NRW – N is the number of database replicas data is copied to one must replicate data in order to withstand partitions. W is the number of replicas a write operation would block on until it returns to it’s caller and is “successful” and R is the number of replicas a read operation would block on before returning to its caller.
  • N, R and W are crucial when dealing with Eventual Consistency as their values usually determine the level of consistency you’re going to have. For example, when N=R=W you have a full consistency (which isn’t tolerant to partitions or course). When W=0 you have async writes, which is the lowest level of consistency (you never know when the write operation actually finishes)
  • I introduced the concept of Quorum, which means R=W=ceil((N+1)/2)
  • Introduced a (very partial) list of currently available nosql solutions, such as Cassandra, BigTable, HBase, Dynamo, Voldemort, Riak, CouchDB, MongoDB and more.

Overall this was a very interesting talk, a lot of (fun and interesting) theory. The next part is going to be specific about Cassandra – how all this theory fits into Cassandra and how does one use Cassandra’s API, so stay tuned.


StringTemplate – a step forward to a better web MVC

MVCMVC, Model View Controller is a well known design patten from the field of UI frameworks. It advocates the separation of a Model, an application specific data and business logic, Controller, which takes user input, consults the model and determines the correct view to present a user based on its result and a View, the actual UI component the user interacts with.

In the context of web applications it’s common to consider a Database along with the application business logic as the Model, a web framework, such as Struts, as the Controller and the rendering engine, such as JSP as the View. MVC are widely used in both web development as well as in desktop application development.

StringTemplate is a rendering engine, a View, I’ve recently became familiar with and immediately fell in love with. StringTemplate is a step forward true MVC implementation, but before presenting the solution, let’s see what the problem is.

The MVC design pattern states that in a UI framework there should be 3 components – the Model, the View and the Controller. It also states that the Controller should have direct access to the Model and the View, the View have direct access to the Model when presenting the data as seen in the diagram below.

MVC diagram

There are many MVC implementations in many languages. In Java only, there are more than 17 mentioned on the Wiki page. Many of the frameworks use JSP as their rendering engine and add their specific features to it, so for example struts2 implements a very nice controller and as a rendering engine uses JSP with either struts2 tags or another tag library. The problem lies within JSP.

JSP, similar to PHP, ASP and many other simple and fast-start rendering engines, compromise the MVC model; they allows too much in their View component.

JSP allows code to be executed within the context of the page (using the <% %> notation), which is very nice when you want to hack something fast but is extremely dangerous from code maintenance perspective and is a clear violation of the MVC agreement. If code can be executed within a page, that code can easily alter the model or take actions a controller should have taken. A View should be able to READ the model, but not ALTER it. Even the most disciplined programmers who adhere to clean JSP code by not allowing actual Java code inside their pages (using the <% %>) actually suffer from the same problem without even knowing it… The alternative to the <%  and the <%= constructs are tags, such as JSTL tags, struts2 tags etc. These tags commonly access the model by invoking its getters, but the real problem with them is that the order in which they execute is very important – read it again – the order in which they are displayed on the page is crucial to the correctness of the values returned by their backing model. More about this here. So with JSP, when using tags, the View implementor has to understand how a Model works in order to succeed. That’s both inconsistent with the pure MVC model and inconvenient to the UI designer. Lastly are side effect, which cannot be ignored. Views can create side effects by calling methods (even getters can have side effects!) , which I think there’s no need to mention, is very bad.

StringTemplate comes to the rescue. As a matter of fact, when I programmed django MVC in python, as well as Cheetah in python, I have to say that both MVCs were much stricter than JSP and were therefore a lot more programmer-friendly. But in Java we had Velocity, which is strict, but also less powerful and now we have StringTemplate which is both strict and powerful. (and no – freemarker isn’t any better than just plain JSP, sorry).

At outbrain we use struts2 as our MVC driver and so to be able to use StringTemplate as the View engine I’ve implemented a struts2 View Renderer. Full code and details below. This code is “unstable” which means it’s been developed and tested, so far no bugs or missing features, but hasn’t gone to production yet.

struts.xml:

<struts>
<include file="webwork-default.xml" />
<package name="regular" namespace="/" extends="struts-default">
<result-types>
<result-type name="stringtemplate" class="org.apache.struts2.dispatcher.StringTemplateResult"/>
</result-types>
<action name="st" class="com.mysite.StringTemplateTestAction">
<result name="success" type="stringtemplate">/WEB-INF/st/page.st</result>
</action>
</package>
</struts>
Java source code:
package org.apache.struts2.dispatcher;
 
import java.io.IOException;
import java.io.InputStream;
import java.io.Writer;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
 
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
 
import org.antlr.stringtemplate.NoIndentWriter;
import org.antlr.stringtemplate.StringTemplate;
import org.antlr.stringtemplate.StringTemplateGroup;
import org.antlr.stringtemplate.StringTemplateWriter;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.StrutsConstants;
import org.apache.struts2.views.util.ContextUtil;
import org.apache.struts2.views.util.ResourceUtil;
 
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.LocaleProvider;
import com.opensymphony.xwork2.inject.Inject;
import com.opensymphony.xwork2.util.ValueStack;
 
import freemarker.template.Configuration;
import freemarker.template.TemplateException;
 
/**
 * Defines the StringTemplate result type for struts2.
 *
 * To use this result type add the following configuration to your struts.xml:
 *
 * <code>
 * &lt;result-types&gt;
 *   &lt;result-type name="stringtemplate"
 *       class="org.apache.struts2.dispatcher.StringTemplateResult"/&gt;
 * &lt;/result-types&gt;
 *</code>
 *
 * Template files should be located relative to /WEB-INF/st/, so for example a common layout
 * would be:
 *
<ul>
 *
	<li>/WEB-INF/st/pages/page1.st</li>
*
	<li>/WEB-INF/st/layouts/layout1.st</li>
*
	<li>/WEB-INF/st/snippets/header.st</li>
*
	<li>/WEB-INF/st/snippets/footer.st</li>
*</ul>
*
 * So page1.st would look like:
 * <code>
 * $layouts/layout1(header=snippets/header(), footer=snippets/footer())$
 * </code>
 *
 * And the associated struts action would be:
 *
 * <code>
 * &lt;action name="page1"
 *      class="com.mycompany.Page1Action"&gt;
 *        &lt;result name="success"
 *          type="stringtemplate"&gt;/WEB-INF/st/pages/page1.st&lt;/result&gt;
 * &lt;/action&gt;
 * </code>
 *
 * Localization:
 * All string property files should be packed into the classpath (in one of the jars) at
 * /lang/.
 * For example:
 *
<ul>
 *
	<li>/lang/en_US.properties</li>
*
	<li>/lang/fr_FR.properties</li>
*</ul>
*
 * @author Ran Tavory (ran@outbrain.com)
 *
 */
public class StringTemplateResult extends StrutsResultSupport {
 
  /**
   * Base path of StringTemplate template files.
   * This is usually something like /WEB-INF/ or /WEB-INF/st/.
   * Must end with /.
   * All templates should reside in subdirectories of this base path and when referencing
   * each other the reference point should be relative to this path.
   * For example, if you have /WEB-INF/pages/page1.st and /WEB-INF/layouts/layout1.st, and assuming
   * the base path is at /WEB-INF then page1 is pages/page1 and layout1 is layouts/layout1.
   * To reference layout1 from page1: $layouts/layout1()$
   */
  public static final String TEMPLATES_BASE =
      "/WEB-INF/st/";
 
  /**
   * Path to the language resource files within the classpath.
   *
   * Resource should be packed inside a jar under /lang/.
   * For example: /lang/en_US.properties
   */
  public static final String LANG_RESOURCE_BASE = "/lang/";
 
  /**
   * If there was an exception during execution it's accessible via $exception$
   */
  public static final String KEY_EXCEPTION = "exception";
 
  /**
   * Session values are accessible via $session.key$
   */
  public static final String KEY_SESSION = "session";
 
  /**
   * All localized strings are accessible via $strings.string_key$
   */
  public static final String KEY_STRINGS = "strings";
 
  /**
   * Request parameters are accessible via $params.key$
   */
  public static final String KEY_REQUEST_PARAMETERS = "params";
 
  /**
   * Request attributes are accessible via $request.attribute$
   */
  public static final String KEY_REQUEST = "request";
 
  private static final Log log = LogFactory.getLog(StringTemplateResult.class);
 
  private static final long serialVersionUID = -2390940981629097944L;
 
  private static final Locale DEFAULT_LOCALE = Locale.US;
 
  /*
   * Struts results are constructed for each result execution
   *
   * the current context is available to subclasses via these protected fields
   */
  private String contentType = "text/html";
 
  private String defaultEncoding;
 
  public StringTemplateResult() {
    super();
  }
 
  public StringTemplateResult(String location) {
    super(location);
  }
 
  public void setContentType(String aContentType) {
    contentType = aContentType;
  }
 
  /**
   * allow parameterization of the contentType the default being text/html
   */
  public String getContentType() {
    return contentType;
  }
 
  @Inject(StrutsConstants.STRUTS_I18N_ENCODING)
  public void setDefaultEncoding(String val) {
    defaultEncoding = val;
  }
 
  /**
   * Execute this result, using the specified template location.
   *
 
   * The template location has already been interpolated for any variable
   * substitutions.
   *
   * NOTE: The current implementation is still under development and has several restrictions.
   *
<ul>
   *
	<li>All template files must end with .st</li>
*</ul>
*/
  public void doExecute(String location, ActionInvocation invocation) throws IOException,
      TemplateException {
 
    final HttpServletRequest request = ServletActionContext.getRequest();
    final HttpServletResponse response = ServletActionContext.getResponse();
 
    if (!location.startsWith("/")) {
      // Create a fully qualified resource name.
      // final ActionContext ctx = invocation.getInvocationContext();
      final String base = ResourceUtil.getResourceBase(request);
      location = base + "/" + location;
    }
 
    final String encoding = getEncoding(location);
    String contentType = getContentType(location);
 
    if (encoding != null) {
      contentType = contentType + ";charset=" + encoding;
    }
 
    response.setContentType(contentType);
 
    final String basePath = ServletActionContext.getServletContext().getRealPath(TEMPLATES_BASE);
    final StringTemplateGroup group = new StringTemplateGroup("webpages", basePath);
    String fileName = location;
    if (fileName.endsWith(".st")) {
      // If filename ends with .st, remove it.
      fileName = fileName.substring(0, fileName.length() - ".st".length());
    }
    if (fileName.startsWith(TEMPLATES_BASE)) {
      // If filename includes the base dir then remove it.
      fileName = fileName.substring(TEMPLATES_BASE.length());
    }
    final StringTemplate template = group.getInstanceOf(fileName);
 
    final Map model = createModel(invocation);
    template.setAttributes(model);
 
    // Output to client
    final Writer responseWriter = response.getWriter();
    final StringTemplateWriter templateWriter = new NoIndentWriter(responseWriter);
    template.write(templateWriter);
    // Flush'n'close
    responseWriter.flush();
    responseWriter.close();
  }
 
  /**
   * Retrieve the encoding for this template.
   *
   * People can override this method if they want to provide specific encodings
   * for specific templates.
   *
   * @return The encoding associated with this template (defaults to the value
   *         of 'struts.i18n.encoding' property)
   */
  protected String getEncoding(String templateLocation) {
 
    String encoding = defaultEncoding;
    if (encoding == null) {
      encoding = System.getProperty("file.encoding");
    }
    if (encoding == null) {
      encoding = "UTF-8";
    }
    return encoding;
  }
 
  /**
   * Retrieve the content type for this template.
   *
   * People can override this method if they want to provide specific content
   * types for specific templates (eg text/xml).
   *
   * @return The content type associated with this template (default
   *         "text/html")
   */
  protected String getContentType(String templateLocation) {
    return "text/html";
  }
 
  /**
   * Build the instance of the ScopesHashModel, including JspTagLib support
   *
   * Objects added to the model are
   *
   *
<ul>
   *
	<li>Application - servlet context attributes hash model</li>
*
	<li>JspTaglibs - jsp tag lib factory model</li>
*
	<li>Request - request attributes hash model</li>
*
	<li>Session - session attributes hash model</li>
*
	<li>request - the HttpServletRequst object for direct access</li>
*
	<li>response - the HttpServletResponse object for direct access</li>
*
	<li>stack - the OgnLValueStack instance for direct access</li>
*
	<li>ognl - the instance of the OgnlTool</li>
*
	<li>action - the action itself</li>
*
	<li>exception - optional : the JSP or Servlet exception as per the servlet
   * spec (for JSP Exception pages)
   *</li>
*
	<li>struts - instance of the StrutsUtil class
   *</li>
*</ul>
*/
  protected Map createModel(ActionInvocation invocation) {
 
    ServletContext servletContext = ServletActionContext.getServletContext();
    HttpServletRequest request = ServletActionContext.getRequest();
    HttpServletResponse response = ServletActionContext.getResponse();
    ValueStack stack = ServletActionContext.getContext().getValueStack();
 
    Object action = null;
    if (invocation != null) {
      action = invocation.getAction();
    }
    return buildTemplateModel(stack, action, servletContext, request, response, invocation);
  }
 
  private Map buildTemplateModel(ValueStack stack, Object action,
                                                 ServletContext servletContext,
                                                 HttpServletRequest request,
                                                 HttpServletResponse response,
                                                 ActionInvocation invocation) {
 
    Map model = buildScopesHashModel(servletContext, request, response, stack);
    populateContext(model, stack, action, request, response);
    populateStrings(model, deduceLocale(invocation));
    return model;
  }
 
  /**
   * Populates the <code>strings</code> attribute of the model according to the current locale
   * value.
   * @param model
   * @param local
   */
  private void populateStrings(Map model, Locale locale) {
    log.debug("Local: " + locale);
    Properties p;
    try {
      p = getLanguageProperties(locale);
      model.put(KEY_STRINGS, p);
      return;
    } catch (IOException e) {
      if (locale.equals(DEFAULT_LOCALE)) {
        log.error("Unable to load language file for the default locale " + locale);
        return;
      } else {
        log.warn("Unable to load language file for " + locale + ". Will try to load for the " +
            "default locale");
      }
    }
 
    // Try once again with the default locale.
    populateStrings(model, DEFAULT_LOCALE);
  }
 
  /**
   * Tries to load language properties for the given locale.
   *
   * The file is loaded from /LANG_RESOURCE_BASE/locale.properties in the classpath, so for example
   * that may be /lang/en_US.properties
   *
   * @param locale
   * @return
   * @throws IOException When the language file isn't found or can't read it.
   */
  private Properties getLanguageProperties(Locale locale) throws IOException {
    final InputStream in =
      getClass().getClassLoader().getResourceAsStream(LANG_RESOURCE_BASE + locale + ".properties");
    final Properties prop = new Properties();
    prop.load(in);
    return prop;
  }
 
  protected Map buildScopesHashModel(ServletContext servletContext,
                                                     HttpServletRequest request,
                                                     HttpServletResponse response,
                                                     ValueStack stack) {
 
    Map model = new HashMap();
 
    // Add session information
    HttpSession session = request.getSession(false);
    if (session != null) {
      model.put(KEY_SESSION, generateAttributeMapForSession(session));
    }
 
    // Add requests attributes
    model.put(KEY_REQUEST, generateAttributeMapFromRequest(request));
 
    // Add request parameters.
    model.put(KEY_REQUEST_PARAMETERS, request.getParameterMap());
 
    return model;
  }
 
  @SuppressWarnings("unchecked")
  private Map generateAttributeMapForSession(HttpSession session) {
 
    Map attributes = new HashMap();
    for (Enumeration e = session.getAttributeNames(); e.hasMoreElements();) {
      String name = (String) e.nextElement();
      attributes.put(name, session.getAttribute(name));
    }
    return attributes;
  }
 
  @SuppressWarnings("unchecked")
  private Map generateAttributeMapFromRequest(HttpServletRequest request) {
 
    Map attributes = new HashMap();
    for (Enumeration e = request.getAttributeNames(); e.hasMoreElements();) {
      String name = (String) e.nextElement();
      attributes.put(name, request.getAttribute(name));
    }
    return attributes;
  }
 
  @SuppressWarnings("unchecked")
  protected void populateContext(Map model, ValueStack stack, Object action,
                                 HttpServletRequest request, HttpServletResponse response) {
 
    // put the same objects into the context that the velocity result uses
    Map standard = ContextUtil.getStandardContext(stack, request, response);
    model.putAll(standard);
 
    // Support for JSP exception pages, exposing the servlet or JSP exception
    Throwable exception = (Throwable) request.getAttribute("javax.servlet.error.exception");
    if (exception == null) {
      exception = (Throwable) request.getAttribute("javax.servlet.error.JspException");
    }
 
    if (exception != null) {
      model.put(KEY_EXCEPTION, exception);
    }
 
    // Add action model.
    if (action instanceof StringTemplateAction) {
      StringTemplateAction stAction = (StringTemplateAction) action;
      model.putAll(stAction.getModel());
    }
  }
 
  /**
   * Returns the locale used for the
   * {@link Configuration#getTemplate(String, Locale)} call. The base
   * implementation simply returns the locale setting of the action (assuming
   * the action implements {@link LocaleProvider}) or, if the action does not
   * the {@link #DEFAULT_LOCALE}
   */
  protected Locale deduceLocale(ActionInvocation invocation) {
 
    if (invocation.getAction() instanceof LocaleProvider) {
      return ((LocaleProvider) invocation.getAction()).getLocale();
    } else {
      return DEFAULT_LOCALE;
    }
  }
}
 
package org.apache.struts2.dispatcher;
 
import java.util.Map;
 
/**
 * Interface defining the required behavior from a StringTemplate result type.
 *
 * The result should prepare the model for the page to display.
 * The model is a map of attributes -&gt; Objects where each object may either be a simple string, int,
 * etc or another map.
 * So. for example $username$ is accessible from the template of the model contains a String under
 * the value "username" and $strings.hello$ is accessible if the model contains a map under the key
 * "strings" and this map contains an attribute under the key "hello"
 *
 * @author Ran Tavory (ran@outbrain.com)
 *
 */
public interface StringTemplateAction {
 
  /**
   * Get the root of the display model.
   *
   * The display model is a map of attributes interpolated by StringTemplate at runtime by
   * substituting the $values$ in the template source.
   * For example to replace $user$ with Ran add
   * <code>map.put("user", "Ran");</code>
   * @return A map of attributes used by StringTemplate to replace in the template.
   */
  public Map getModel();
}

The joy of deleting code

What could be more fun than writing a new shiny super-functional, super-tested piece of code? Deleting it!
When deleting code you know that

  • You have not introduced new bugs. Perhaps you deleted some potential bugs from the old code but chances are you did not introduce new ones.
  • You don’t have to maintain it. It’s deleted.
  • Code was probably poorly written. Good code is never deleted. In many cases there’s poorly written code that you just don’t have the guts to delete it. Now you did, that’s great.
  • You’ve probably found a good way to reuse another piece of code, that’s why you’re deleting this piece of code. Code reuse is good.
  • Or that you’ve taken off a feature from your product. Taking off features is good, is very good. Perfection is achieved, not when there is nothing more to add, but when there is nothing left to take away
  • Or that you’ve found a more compact and elegant way to do what you want to do.

Bottom line: Deleting code makes me happy. How about you?

Delete


Mavenizing our code base

Maven is a build tool for Java. It’s more than that actually, but let’s just call it a build tool.

Maven - Welcome to Apache Maven-1

In outbrain we decided we want to replace good old ant with maven.

Changing the company wide used build tool is not a decision taken lightly and may have consequences on product release cycle, but we weighted our options and decided to go for it, so I thought it might be worth mentioning our endeavor.

Everyone familiar with Java programming has probably used ant or at least heard of it. For many years it has been the de-facto standard build tool with large and growing audience, numerous plugins, excellent documentation and IDE support (for example most Java IDEs can automatically generate ant build files). But ant has its shortcomings which we, at outbrain decided we just couldn’t live with. We found maven to fill up most of the gaps.

How do ant and maven differ?

Maven is newer and was built from scratch with many of the lessons learned by ant in mind. Both projects are written and maintained by the high quality, high standard apache software foundation, home of many other wonderful open source products. Both ant and maven are still actively developed and maintained, so it would not be fair to say that maven replaces ant, though many developers tend to think so (including myself).

Ant and maven differ in many ways, but at least to me these are the winning points that actually make the difference and made choose maven:

Maven is declarative. Ant is imperative.

Here’s what an ant build file looks like for a simple java project:

<project name="MyProject" default="dist" basedir=".">
  <description>
    simple example build file
  </description>
  <!-- set global properties for this build -->
  <property name="src" location="src"/>
  <property name="build" location="build"/>
  <property name="dist"  location="dist"/>
 
  <target name="init">
    <!-- Create the time stamp -->
    <tstamp/>
    <!-- Create the build directory structure used by compile -->
    <mkdir dir="${build}"/>
  </target>
 
  <target name="compile" depends="init"
    description="compile the source " >
    <!-- Compile the java code from ${src} into ${build} -->
    <javac srcdir="${src}" destdir="${build}"/>
  </target>
 
  <target name="dist" depends="compile"
    description="generate the distribution" >
    <!-- Create the distribution directory -->
    <mkdir dir="${dist}/lib"/>
 
    <!-- Put everything in ${build} into the MyProject-${DSTAMP}.jar file -->
    <jar jarfile="${dist}/lib/MyProject-${DSTAMP}.jar" basedir="${build}"/>
  </target>
 
  <target name="clean"
    description="clean up" >
    <!-- Delete the ${build} and ${dist} directory trees -->
    <delete dir="${build}"/>
    <delete dir="${dist}"/>
  </target>
</project>

And here’s the maven one:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <artifactId>MyProject</artifactId>
  <name>MyProject</name>
  <description>simple example build file</description>
  <packaging>jar</packaging>
</project>

Ant line count: 22 (not including spaces, comments)

Maven line count: 7. (and they are real easy ones)

Short is good, especially in software (except perl ;-) ). But except for the fact that mvn has shorter build files, there is something more important hidden here – declarative v.s. imperative.

With ant you have to tell it HOW to build. You have to tell it that it first needs to collect all java sources, then run the javac compiler on them, then collect all classes, then run the jar tool on them to make them a jar. That’s tedious, especially if you have to do it 30 times, for each and every project. In outbrain we have many projects so when we used ant you’d see the exact same ant code patterns again and again (including the mistakes, which survived copy-paste horror). Ant is hard to maintain and is also hard to write. Did any of the readers ever write an ant build file? I doubt that. I’ve been using ant for more than 5 years and never have I written a file from scratch. It’s always used to be either copy-paste or using the IDE support for automatic generation. This is a bad sign of superfluous language.

Maven is declarative. You don’t have to tell it HOW to build, only WHAT to build, so conceptually it’s a higher level build tool. With mvn you only have to say “Look, this is how I call my project and I want you to make a jar from it” that’s all, mvn will figure out the rest. It knows where to find the sources (convention) and it knows what steps it needs to take in oder to create a jar. It will compile your source files, will package all resources for you in that jar, will run tests and create that jar for you. You can intervene with this process, but you don’t have to. You can make jars, wars, ears and more.

Declarative is in many cases preferred over imperative. Think HTML vs. Java. HTML is declarative, Java is imperative. In HTML you say <b>bold</b> which tells the browser you want the text to be bold. You don’t tell it how to make the text bold (e.g. how many pixels, what position etc) only that you want it bold and let the browser figure out how to handle it. In Java you’d have to tell it how to make the text bold, how to space the characters, how to space words around it, how to break lines etc. Declarative is in many cases a lot easier than imperative, you worry less.

Maven is declarative, you only have to say “this is my project, jar it”. With ant you have more control over what the build tool does, so you can go crazy with build scripts and… well… jar before compile, or clean after jar (instead of before it) or package the test code inside production code or whatever, you get the point, you have the freedom to err. 9 times out of 10 you don’t need the level of flexibility provided by ant and you’d be much safer using mvn.

Dependency management.

This is a big thing. That was actually the main reason I wanted to move out of ant. Maven has a wonderful dependency management system built in by default. Ant has nothing built in, although it has ivy as a plugin.

What is dependency management? There are external and internal dependencies. External dependencies are ones you download from the net, usually open source projects such as Lucene, ActvieMQ, and other open source projects. With maven you only have to declare your dependency on them and they get automatically downloaded. Example:

<dependency>
  <groupId>struts</groupId>
  <artifactId>struts-bean</artifactId>
  <version>1.2.8</version>
</dependency>
With ant you basically have two options. One is download the library yourself and throw it in some folder, call it 3rdParty and add it to the classpath (good luck with keeping track of versioning, who’s using what and your life) or use ivy, which is pretty decent, but as mentioned before not part of the default ant installation.
As for internal dependencies, which means your project which depends (uses) another one of your projects, mvn supports that as well. AFAIK ant does not. With ant, if you have more than one project in your company (and of course you do), you’d have to manually tweak the build scripts so they run in the correct order and dependencies are compiled before they are used. Although it’s possible, that’s sort of nightmarish as companies grows.
Dependency management is a killer feature for mvn and was actually the main reason that prompted me to pursue it. Although ant can have ivy, this was not zero-work, so I decided, heck it we’re going to put some work into it, let’s rebuild the whole thing and get a much better result. So we did.

Conventions vs. configuration

Conventions are good. They save a lot of time and prevent you from doing foolish mistakes (such as packaging test code into production).

By conventions I mean:

  • Where is the source code?
  • Where is the test code?
  • Where are the resources?
  • Where are the web files?
  • etc

With ant you had to create a directory for sources (call it src or Src or source or srce) and tell and where your sources are. Then you’d have to decide where to put your tests. You can push them in tst, test, tests, or even in the same source directory as production code is, maybe in a test package. Next you have to configure ant where to find test code, how to separate it from production code, and heck – how to run it (it really doesn’t know how to do it).

With mvn that’s much easier. Maven promotes conventions such as the standard directory layout which means all sources are at predefined location, all resources are as well etc. There are several advantages to that including that it’s easy to start a new project, you don’t have to think where everything goes, it’s hard to make mistakes by misplacing items, you don’t have to think about the build script and how to configure it and perhaps most important of all, you make all company employees conform to the same layout. That’s a huge gain for the company.

Built-in functionality out of the box

OK, there are plenty of other benefits to mvn but the post is already getting too long so let’s have the last one here.

With mvn you get tons of functionality out of the box. By creating a very simple build file with only the project definition in it you can:

  • compile all sources
  • compile test
  • run unit tests
  • run integration tests
  • package as a jar/war or something else
  • deploy
  • run in tomcat
  • …and much more

With ant what you had to do is for each one of the above listed goals, create an ant goal and configure ant by telling it how to run it. Some of them may be relatively trivial (but still require coding) and some of them aren’t easy at all… that kind of tells you why anters are very good with their CTRL+C and CTRL+V. And with copy-paste comes the pain of silly copy paste errors and difficult maintainability. Life with mvn is better ;-)

Other great and not covered features: Eclipse and other IDE integration (automatically generating projects), great testing and debugging tools, excellent build output, excellent versioning and more.

How did it go?

So, how did it go? You guys have converted your entire codebase build tool. Isn’t that like Netscape’s near death experience while rewriting their entire code base?

Well… no! The nice thing about mvn is that it’s easy to write and easy to learn. We did spend a couple of weeks on that task and had to resolve some unpredictable situations, but it had only a small impact on our schedule (and needless to say that I hope in the long term will have  the most positive impact on release schedule). Heck, we (at least I) even enjoyed it!

Conclusions

I’d definitely recommend mvn. If you’re starting a new project, choose mvn. If you have an existing codebase using ant and you’re thinking about moving to maven, know that it’s certainly feasible and in my opinion, well worth the effort. Expect some work, it’s not zero effort, but I promise you’ll enjoy it.