<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">

  <title><![CDATA[Code By Martin]]></title>
  <link href="http://martin.elwin.com/atom.xml" rel="self"/>
  <link href="http://martin.elwin.com/"/>
  <updated>2012-09-26T19:35:45+02:00</updated>
  <id>http://martin.elwin.com/</id>
  <author>
    <name><![CDATA[Martin Elwin]]></name>
    
  </author>
  <generator uri="http://octopress.org/">Octopress</generator>

  
  <entry>
    <title type="html"><![CDATA[Binary Search]]></title>
    <link href="http://martin.elwin.com/blog/2010/04/binary-search/"/>
    <updated>2010-04-21T00:00:00+02:00</updated>
    <id>http://martin.elwin.com/blog/2010/04/binary-search</id>
    <content type="html"><![CDATA[<p><a href="http://reprog.wordpress.com/2010/04/21/binary-search-redux-part-1/"/>Mike Taylor</a> noted in a blog post that in the book Programming Pearls it is mentioned that no more than 10% of developers can correctly implement a binary search. Appalling!</p>

<p>Let&#8217;s see if I am in that 10% or not&#8230;</p>

<p>As I&#8217;ve found myself using Ruby more and more lately, I thought I&#8217;d try to implement the binary search using that language.</p>

<p>Here&#8217;s my stab:</p>

<script src="http://gist.github.com/374222.js"></script>


<p>The script includes code to run the binary search through the test cases for the exercise created by <a href="http://www.tiac.net/~sw">Steve Witham</a>. And once the file reading worked - all tests actually passed (or the code incorrectly shows them as passed&#8230; ;).</p>

<p>Good training this!</p>

<p>/M</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Migrated To Octopress]]></title>
    <link href="http://martin.elwin.com/blog/2010/03/migrated-to-octopress/"/>
    <updated>2010-03-19T00:00:00+01:00</updated>
    <id>http://martin.elwin.com/blog/2010/03/migrated-to-octopress</id>
    <content type="html"><![CDATA[<p>Like <a href="http://jonasboner.com/2009/01/07/blogging-like-a-hacker-using-git-and-jekyll.html">all</a> <a href="http://tom.preston-werner.com/2008/11/17/blogging-like-a-hacker.html">cool</a> <a href="http://wiki.github.com/mojombo/jekyll/sites">kids</a> blogging nowadays, as part of the attempt to rejuvinate the blog, I&#8217;ve switched to <a href="http://github.com/mojombo/jekyll">Jekyll</a>. Or, rather, the extended fork <a href="http://github.com/imathis/octopress">Octopress</a>.</p>

<p>As part of the migration I wanted to extract all the old posts from Wordpress into the proper markdown format used by Jekyll.</p>

<p>Jekyll includes a migration script for Wordpress, but this used a direct database connection to the Wordpress MySQL server to extract a minimum amount of information for each blog post. To avoid missing information that I later might want after having shut down the Wordpress server, I wanted to base the migration on a full XML export from Wordpress. This way I could go back and extract more information from the old posts, if, and when, needed.</p>

<p>Seeing this as a chance to play with Ruby - a language I&#8217;ve only dabbled in previously - I set out to build a simple Wordpress XML->Jekyll converter. The converter reads the Wordpress export and converts all blog posts into separate files with a proper Yaml frontmatter. It also converts the syntax highlighting markup, code markup and headings into the corresponding markdown conventions. The rest of the HTML is left alone.</p>

<p>For the images I just copied the files in the old Wordpress structure into the new blog directory layout so that the URLs still match. Not the nicest way, but I was too lazy to do anything about it just yet.</p>

<p>Anywho - the source for the Wordpress XML converter is available in the <a href="http://github.com/melwin/octopress/blob/blog/source/_import/wordpress_xml_import.rb">blog branch of my fork of Octopress</a>. The source is also given below. To use, just run with the filename of the Wordpress XML export as the first argument.</p>

<p>It&#8217;s my first publicly available Ruby program - so be careful. Improvements welcome!</p>

<p>/M</p>

<script src="http://gist.github.com/374148.js"></script>

]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Nginx]]></title>
    <link href="http://martin.elwin.com/blog/2010/03/nginx/"/>
    <updated>2010-03-16T00:00:00+01:00</updated>
    <id>http://martin.elwin.com/blog/2010/03/nginx</id>
    <content type="html"><![CDATA[<p>For that fresh new feeling I switched this site from Apache2 to <a href="http://nginx.org">Nginx</a>. A quick compile of the source package and following the <a href="http://wiki.nginx.org/Wordpress">instructions</a> on hooking it up with Wordpress over fastcgi using php-cgi and we&#8217;re done!</p>

<p>Feels good with a server handling the <a href="http://en.wikipedia.org/wiki/C10k_problem">C10K</a> problem - and it has a fairly decent configuration language IMHO.</p>

<p>Also looking forward to use Nginx more in the days to come as a the web frontend for development tools server at work hosting, among some things:</p>

<ul>
    <li>Gitorious</li>
    <li>Redmine</li>
    <li>Hudson</li>
    <li>Nexus</li>
</ul>


<p>Will post more about this later!</p>

<p>/M</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[New Direction?]]></title>
    <link href="http://martin.elwin.com/blog/2010/03/new-direction/"/>
    <updated>2010-03-16T00:00:00+01:00</updated>
    <id>http://martin.elwin.com/blog/2010/03/new-direction</id>
    <content type="html"><![CDATA[<p>More than a full year since last post - this might not be working as well as I had hoped&#8230;!</p>

<p>Finding the time and inspiration to write between the day job and private commitments turns out to be a challenge. Instead of seeing this as a failure, however, I will try to learn from the experience and attempt to find a new way of relating to the blog. Perhaps by being less long winded (!) in each post I could get a few more out there. There are still a lot of things going on I would like to capture, but the previous form is clearly not working.</p>

<p>So - let&#8217;s try to shake things up and see how that works!</p>

<p>/M</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[The Hitchhiker's Guide to an Ioke Dev Env From Source (part 5: Ioke and the REPL)]]></title>
    <link href="http://martin.elwin.com/blog/2009/01/the-hitchhikers-guide-to-an-ioke-dev-env-from-source-part-5/"/>
    <updated>2009-01-23T00:00:00+01:00</updated>
    <id>http://martin.elwin.com/blog/2009/01/the-hitchhikers-guide-to-an-ioke-dev-env-from-source-part-5</id>
    <content type="html"><![CDATA[<p>This is the fifth part in a series of posts for non-experts about setting up an Ioke development environment on Linux. Please see the previous posts to start at the beginning:</p>

<ul>
    <li><a href="http://martin.elwin.com/blog/2009/01/the-hitchhikers-guide-to-an-ioke-dev-env-from-source-part-1/">Part 1: Git</a></li>
    <li><a href="http://martin.elwin.com/blog/2009/01/the-hitchhikers-guide-to-an-ioke-dev-env-from-source-part-2/">Part 2: Emacs</a></li>
    <li><a href="http://martin.elwin.com/blog/2009/01/the-hitchhikers-guide-to-an-ioke-dev-env-from-source-part-3/">Part 3: emacs-starter-kit</a></li>
    <li><a href="http://martin.elwin.com/blog/2009/01/the-hitchhikers-guide-to-an-ioke-dev-env-from-source-part-4/">Part 4: Java and Ant</a></li>
</ul>


<p>This time we will finally get the Ioke source code, build it, and test the Ioke <a href="http://en.wikipedia.org/wiki/REPL">REPL</a>!</p>

<h3>Ioke</h3>

<p>Ioke uses <a href="http://git-scm.com">Git</a> as the source code versioning tool, with a <a href="http://github.com/olabini/ioke">public repository</a> set up on <a href="http://github.com/">GitHub</a> (soon I&#8217;ll be linking like Jeff Atwood).</p>

<p>So - let&#8217;s get Ioke using Git by cloning Ola&#8217;s repository:</p>

<div>
  <pre><code class='sh'>~/bin$ cd ~/work
~/work$ git clone git://github.com/olabini/ioke
Initialized empty Git repository in /home/melwin/work/ioke/.git/
remote: Counting objects: 9221, done.
remote: Compressing objects: 100% (2941/2941), done.
remote: Total 9221 (delta 5782), reused 8656 (delta 5351)
Receiving objects: 100% (9221/9221), 45.95 MiB | 399 KiB/s, done.
Resolving deltas: 100% (5782/5782), done.</code></pre>
</div>


<p>Great - let&#8217;s quickly move on to the build step:</p>

<div>
  <pre><code class='sh'>~/work$ cd ioke
~/work/ioke$ ant
...
     [java] 2606 examples, 0 failures
jar:
      [jar] Building jar: /home/melwin/work/ioke/lib/ioke.jar

BUILD SUCCESSFUL
Total time: 22 seconds</code></pre>
</div>


<p>Running just <code>ant</code> will execute the default target in the <code>build.xml</code> file. This target will make sure Ioke is compiled and the test suite is run.</p>

<p>At the end is a summary of the test results - if these are not all successful you might have a problem with the environment or you might have checked out a broken build from the repository.</p>

<h3>The Ioke REPL</h3>

<p>Now all is installed and Ioke is compiled, so let&#8217;s fire up the REPL. This is done by just running the main Ioke binary:</p>

<div>
  <pre><code class='sh'>~/work/ioke/$ bin/ioke
iik&gt;</code></pre>
</div>


<p>When doing this we get the <code>iik&gt;</code> REPL prompt. From here we can execute most Ioke code. Let&#8217;s try to print a string:</p>

<div>
  <pre><code class='ioke'>iik&gt; &quot;Hello World!&quot; println
Hello World!
+&gt; nil

iik&gt;</code></pre>
</div>


<p>Here we create a Text (Ioke&#8217;s string type) literal and send it the message <code>println</code>, which will cause the text to be printed to the console. The return type of <code>println</code> is <code>nil</code> (similar to null), which is printed by the REPL itself. After that we get the prompt back and can execute another line.</p>

<p>Let&#8217;s try a little more complex example - the factorial:</p>

<div>
  <pre><code class='ioke'>iik&gt; fact = method(n, if(n &gt; 1, n * fact(n pred), 1))
+&gt; fact:method(n, if(n &gt;(1), n *(fact(n pred)), 1))</code></pre>
</div>


<p>Note how the REPL prints the method definition in a canonical form - it makes it obvious how Ioke parses the code, what are messages and what are arguments.</p>

<p>Let&#8217;s run our new factorial function:</p>

<div>
  <pre><code class='ioke'>iik&gt; fact(3)
+&gt; 6

iik&gt; fact(10)
+&gt; 3628800

iik&gt; fact(50)
+&gt; 30414093201713378043612608166064768844377641568960512000000000000</code></pre>
</div>


<p>Ioke handles arbitrarily big numbers, so we don&#8217;t need to think about what fits in a certain number of bits.</p>

<p>The Iik REPL also comes with a simple debugger, which helps with handling conditions. For instance, let&#8217;s try to run the fact method, passing a message which doesn&#8217;t mean anything (yet):</p>

<div>
  <pre><code class='ioke'>iik&gt; fact(f)
*** - couldn't find cell 'f' on 'Ground_0xC360E7' (Condition Error NoSuchCell)
 f                                                [&lt;init&gt;:1:5]
The following restarts are available:
 0: storeValue           (Store value for: f)
 1: useValue             (Use value for: f)
 2: abort                (restart: abort)
 3: quit                 (restart: quit)

 dbg:1&gt; 1
  dbg:1:newValue&gt; 5
  +&gt; 5

+&gt; 120</code></pre>
</div>


<p>The above output shows that when we try to reference something that doesn&#8217;t exist we get a chance to provide that value. Here I decided to provide a value using the useValue restart and entered the value 5. This let the method continue executing and the result was printed.</p>

<p>To exit the REPL, just type: <code>exit</code></p>

<p>Next up are the Emacs modes for Ioke - stay tuned!</p>

<p>/M</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[The Hitchhiker's Guide to an Ioke Dev Env From Source (part 4: Java+Ant)]]></title>
    <link href="http://martin.elwin.com/blog/2009/01/the-hitchhikers-guide-to-an-ioke-dev-env-from-source-part-4/"/>
    <updated>2009-01-22T00:00:00+01:00</updated>
    <id>http://martin.elwin.com/blog/2009/01/the-hitchhikers-guide-to-an-ioke-dev-env-from-source-part-4</id>
    <content type="html"><![CDATA[<p>This is the fourth part in a series of posts for non-experts about setting up an Ioke development environment on Linux. Please see the previous posts to start at the beginning:</p>

<ul>
    <li><a href="http://martin.elwin.com/blog/2009/01/the-hitchhikers-guide-to-an-ioke-dev-env-from-source-part-1/">Part 1: Git</a></li>
    <li><a href="http://martin.elwin.com/blog/2009/01/the-hitchhikers-guide-to-an-ioke-dev-env-from-source-part-2/">Part 2: Emacs</a></li>
    <li><a href="http://martin.elwin.com/blog/2009/01/the-hitchhikers-guide-to-an-ioke-dev-env-from-source-part-3/">Part 3: emacs-starter-kit</a></li>
</ul>


<p>It took a bit longer than anticipated to get to this point, as I got side tracked with the <a href="http://martin.elwin.com/blog/2009/01/type-checking-in-ioke-java-methods/">Ioke type checking activities</a>. But now when <a href="http://ioke.org">Ioke S</a> is out we can continue with the series. So! We&#8217;re getting closer&#8230; Only a few more things to go.</p>

<h3>Installing Java</h3>

<p>As the current version of Ioke is implemented to run on a Java Virtual Machine, we need to get hold of one of those to be able to continue. The JVM brand we will install here is the latest stable one  produced by Sun.</p>

<p>What we need is Java SE Development Kit 6u11 for Linux, Multi-language, and the the filename for this is <code>jdk-6u11-linux-i586.bin</code>. Note that this is <em>not</em> the <code>.rpm.bin</code>, which is also available.</p>

<p>Download the file from <a href="http://java.sun.com/javase/downloads/index.jsp">http://java.sun.com/javase/downloads/index.jsp</a> (I&#8217;m sure you can find it) and put it in the <code>~/work</code> directory.</p>

<p>To unpack the file, let&#8217;s make it executable and then run it:</p>

<div>
  <pre><code class='sh'>~$ cd ~/work
~/work$ cd ~/work                   
~/work$ chmod a+x jdk-6u11-linux-i586.bin 
~/work$ ./jdk-6u11-linux-i586.bin         
... lots of legalese here...</code></pre>
</div>


<p>Once the license agreement is accepted, the JVM will unpack itself into the directory <code>~/work/jdk1.6.0_11</code>. Let&#8217;s move it to where we want it and add <code>java</code> and <code>javac</code> to the <code>~/bin</code> directory as before:</p>

<div>
  <pre><code class='sh'>~/work$ mv jdk1.6.0_11 ../opt
~/work$ cd ~/bin
~/bin$ ln -s ../opt/jdk1.6.0_11/bin/java
~/bin$ ln -s ../opt/jdk1.6.0_11/bin/javac</code></pre>
</div>


<p>And test it:</p>

<div>
  <pre><code class='sh'>~/bin$ java -version
java version &quot;1.6.0_11&quot;
Java(TM) SE Runtime Environment (build 1.6.0_11-b03)
Java HotSpot(TM) Client VM (build 11.0-b16, mixed mode, sharing)</code></pre>
</div>


<p>That done - let&#8217;s move on to Ant.</p>

<h3>Ant</h3>

<p>Ioke uses <a href="http://ant.apache.org">Apache Ant</a> to handle the build process, so to build Ioke we need to get Ant installed.</p>

<p>Let&#8217;s download the Ant distributable package and unpack it in one go - as we did with Git:</p>

<div>
  <pre><code class='sh'>~/bin$ cd ~/opt
~/opt$ wget -O - http://www.apache.org/dist/ant/binaries/apache-ant-1.7.1-bin.tar.bz2 | tar xjv
&lt;/lang&gt;

And add it to the ~/bin directory again so it's on the path:

&lt;pre lang=&quot;sh&quot;&gt;
~/opt$ cd ~/bin
~/bin$ ln -s ../opt/apache-ant-1.7.1/bin/ant</code></pre>
</div>


<p>Let&#8217;s try it out:</p>

<div>
  <pre><code class='sh'>~/bin$ ant -version
Apache Ant version 1.7.1 compiled on June 27 2008</code></pre>
</div>


<p>Looking good!</p>

<p>Soon to come: How to get the Ioke source and build it.</p>

<p>/M</p>

<p><strong>Update:</strong> <a href="http://martin.elwin.com/blog/2009/01/the-hitchhikers-guide-to-an-ioke-dev-env-from-source-part-5/">Part 5: Ioke and the REPL</a></p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Type Checking in Ioke Java Methods]]></title>
    <link href="http://martin.elwin.com/blog/2009/01/type-checking-in-ioke-java-methods/"/>
    <updated>2009-01-19T00:00:00+01:00</updated>
    <id>http://martin.elwin.com/blog/2009/01/type-checking-in-ioke-java-methods</id>
    <content type="html"><![CDATA[<p>Ola Bini recently issued <a href="http://kenai.com/projects/ioke/lists/dev/archive/2009-01/message/21">a call to arms</a> to help with the receiver and argument validation for Java methods in Ioke. These are the Ioke methods that are implemented in Java, instead of in Ioke itself.</p>

<p>The Java methods usually operate on the specific data contained within Ioke objects. This data corresponds to different Java classes, depending on what the Ioke object should hold. For instance, an Ioke List contains inside the data area a Java List. To operate on this List the Java code needs to get hold of the List reference - and it does this in a lot of cases by assuming the data object is of a certain type and casts to this type. If the data object is of a different type then a Java <code>ClassCastException</code> is thrown, which makes the interpreter quit.</p>

<p>Since Ola mailed the call to arms a number of things have happened. A few people (including myself) have volunteered to help out with adding the validation code. Additionally, a few supporting methods and additions have been added to the Ioke code base to simplify adding type checks to the existing code. And it&#8217;s these additions that I will talk about here.</p>

<h3>Current Code</h3>

<p>As an example what the new type validations can look like I will use the <code>List +</code> method that Ola also mentioned in the example.</p>

<p>This is the previous code from <a href="http://github.com/olabini/ioke/blob/e3018142943253f0fd13a967ffb68d39087d9600/src/main/ioke/lang/IokeList.java">IokeList.java</a>:</p>

<div>
  <pre><code class='java'>obj.registerMethod(runtime.newJavaMethod(&quot;returns a new list that contains the receivers elements and the elements of the list sent in as the argument.&quot;, new JavaMethod(&quot;+&quot;) {
        private final DefaultArgumentsDefinition ARGUMENTS = DefaultArgumentsDefinition
            .builder()
            .withRequiredPositional(&quot;otherList&quot;)
            .getArguments();
        
        @Override
        public DefaultArgumentsDefinition getArguments() {
            return ARGUMENTS;
        }
        
        @Override
        public Object activate(IokeObject method, IokeObject context, IokeObject message, Object on) throws ControlFlow {
            List&lt;Object&gt; args = new ArrayList&lt;Object&gt;();
            getArguments().getEvaluatedArguments(context, message, on, args, new HashMap&lt;String, Object&gt;());
            List&lt;Object&gt; newList = new ArrayList&lt;Object&gt;();
            newList.addAll(((IokeList)IokeObject.data(on)).getList());
            newList.addAll(((IokeList)IokeObject.data(args.get(0))).getList());
            return context.runtime.newList(newList, IokeObject.as(on));
        }
    }));</code></pre>
</div>


<h3>New Type Checks</h3>

<p>The key to the new validation are two new classes, which extend the functionality of the normal <code>JavaMethod</code> class with type checking functionality. These are:</p>

<ul>
    <li><a href="http://github.com/olabini/ioke/blob/0e20b492b8e057e9d2c006698deca02ebf8f45f7/src/main/ioke/lang/TypeCheckingArgumentsDefinition.java">TypeCheckingArgumentsDefinition</a></li>
    <li><a href="http://github.com/olabini/ioke/blob/0e20b492b8e057e9d2c006698deca02ebf8f45f7/src/main/ioke/lang/TypeCheckingJavaMethod.java">TypeCheckingJavaMethod</a></li>
</ul>


<p>When using these to define the Java method we can &#8220;annotate&#8221; the arguments definition with types for both the arguments and the receiver. By then implementing the appropriate <code>activate(...)</code> the super class takes care of evaluating and validating (converting as appropriate) the receiver and arguments.</p>

<p>For instance, for the <code>List +</code> example, the above code gets changed to the following:</p>

<div>
  <pre><code class='java'>obj.registerMethod(runtime.newJavaMethod(&quot;returns a new list that contains the receivers elements and the elements of the list sent in as the argument.&quot;, new TypeCheckingJavaMethod(&quot;+&quot;) {
        private final TypeCheckingArgumentsDefinition ARGUMENTS = TypeCheckingArgumentsDefinition
            .builder()
            .receiverMustMimic(runtime.list)
            .withRequiredPositional(&quot;otherList&quot;).whichMustMimic(runtime.list)
            .getArguments();
        
        @Override
        public TypeCheckingArgumentsDefinition getArguments() {
            return ARGUMENTS;
        }
        
        @Override
        public Object activate(IokeObject self, Object on, List&lt;Object&gt; args, Map&lt;String, Object&gt; keywords, IokeObject context, IokeObject message) throws ControlFlow {
            List&lt;Object&gt; newList = new ArrayList&lt;Object&gt;();
            newList.addAll(((IokeList)IokeObject.data(on)).getList());
            newList.addAll(((IokeList)IokeObject.data(args.get(0))).getList());
            return context.runtime.newList(newList, IokeObject.as(on));
        }
    }));</code></pre>
</div>


<p>Note that most of the boiler plate code for arguments handling (which most JavaMethods do) is removed, leaving a clean implementation of the necessary logic - to concatenate two lists in this case.</p>

<p>A few things are done:</p>

<ol>
    <li>The JavaMethod is changed to TypeCheckingJavaMethod</li>
    <li>The arguments definition is changed to a TypeCheckingArgumentsDefinition</li>
    <li>The appropriate types are added to the arguments definition</li>
    <li>Return type of getArguments is changed to TypeCheckingArgumentsDefinition</li>
    <li>The active method is changed to the one which gets the arguments list and keywords</li>
    <li>The manual call to getArguments().getEvaluatedArguments() is removed as we now get the arguments passed</li>
</ol>


<p>The relevant tests for this, which should be added to the <code>list_spec.ik</code> test file, could look like:</p>

<div>
  <pre><code class='ioke'>describe(List,
  describe(&quot;+&quot;, 
    it(&quot;should validate type of receiver&quot;,
      x = Origin mimic
      x cell(&quot;+&quot;) = List cell(&quot;+&quot;)
      fn(x + [3]) should signal(Condition Error Type IncorrectType)
    )

    it(&quot;should validate type of argument&quot;,
      fn([1,2,3] + 3) should signal(Condition Error Type IncorrectType)
    )
  )
)</code></pre>
</div>


<p>So for you to do:</p>

<ol>
    <li>Fork Ioke</li>
    <li>Pick a `IokeData` subclass which no one has started on yet (check with Ola/naeu/me in the IRC channel #ioke on FreeNode)</li>
        <li>Identify a method which makes faulty assumptions on receiver or arguments</li>
    <li>Add a test as per the above to validate the arguments and receiver</li>
    <li>Change `JavaMethod` implementation as per the above to fix the test</li>
    <li>Commit test and fix in togther to your fork</li>
    <li>Rinse and repeat until the whole file is done</li>
    <li>Convince Ola to pull your fork</li>
</ol>


<p>Let&#8217;s get crackin&#8217;!</p>

<p>(but first - back to normal work&#8230; :)</p>

<p>/M</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[The Hitchhiker's Guide to an Ioke Dev Env From Source (part 3: emacs-starter-kit)]]></title>
    <link href="http://martin.elwin.com/blog/2009/01/the-hitchhikers-guide-to-an-ioke-dev-env-from-source-part-3/"/>
    <updated>2009-01-13T00:00:00+01:00</updated>
    <id>http://martin.elwin.com/blog/2009/01/the-hitchhikers-guide-to-an-ioke-dev-env-from-source-part-3</id>
    <content type="html"><![CDATA[<p>This is the third part in a series of posts for non-experts about setting up an Ioke development environment on Linux. Please see the previous posts to start at the beginning:</p>

<ul>
    <li><a href="http://martin.elwin.com/blog/2009/01/the-hitchhikers-guide-to-an-ioke-dev-env-from-source-part-1/">Part 1: Git</a></li>
    <li><a href="http://martin.elwin.com/blog/2009/01/the-hitchhikers-guide-to-an-ioke-dev-env-from-source-part-2/">Part 2: Emacs</a></li>
</ul>


<p>The <a href="http://github.com/technomancy/emacs-starter-kit/tree/master">emacs-starter-kit</a> is a set of base configuration for Emacs. It contains a number of useful elisp libraries, with a slight focus on dynamic languages.</p>

<p>To install it, perform the following steps (note that we move any existing Emacs configuration out of the way first to avoid stomping what you currently have):</p>

<div>
  <pre><code class='sh'>~/work/emacs$ cd
~$ mv .emacs.d .emacs.d.old
~$ mv .emacsrc .emacsrc.old
~$ git clone git://github.com/technomancy/emacs-starter-kit.git .emacs.d</code></pre>
</div>


<p>If you now start Emacs again you&#8217;ll see that the menu bar and the toolbar is gone. This is the default in emacs-starter-kit as most Emacs users don&#8217;t find them useful. For new users the menu bar can sometimes come in handy, to get it back temporarily, just press <code>F1</code>.</p>

<h3>Configuring Emacs</h3>

<p>If you want to add your own customizations to Emacs when using emacs-starter-kit, just add an Emacs LISP file called <em><code>username.el</code></em>, or <em><code>hostname.el</code></em>, in the <code>~/.emacs.d</code> directory. For instance, to make the menu bar always visible:</p>

<ol>
<li>Open Emacs, if it&#8217;s not open already.</li>
<li>Press <code>C-x C-f</code> and type in: <code>~/.emacs.d/username.el</code><br>Where <em>username</em> is the name you log in with (for instance, in my case the complete filename is <code>melwin.el</code>).</li>
<li>Type in the following in the file:

<pre><code> (menu-bar-mode 1)
</code></pre>

<p>And save the file with <code>C-x s</code>.</p></li>
<li>Now quit (<code>C-x c</code>) and restart and you&#8217;ll see that the menu bar is shown.</li>
</ol>


<h3>Working with Magit</h3>

<p>emacs-starter-kit includes, among many other things, the very nice <a href="http://zagadka.vm.bytemark.co.uk/magit/magit.html">Magit Git mode for Emacs</a>, which gives you a nice interface for working with a Git repository.</p>

<p>Let&#8217;s use this mode to commit our recent changes to the configuration file to our local clone of the <code>emacs-starter-kit</code> repository. This helps us track changes we make and also makes a backup of the file in case we screw (sorry, mess) something up.</p>

<p><strong>Note 1:</strong> To move easily between Emacs windows using the keyboard, just press <code>Shift</code> and the arrow key pointing in the direction you want to move.
<strong>Note 2:</strong> To only show the current Emacs window - press: <code>C-x 1</code></p>

<ol>
    <li>Inside Emacs, press `C-x g` to run `magit-status` and enter the directory (note that `Tab` auto-completes): `~/.emacs.d`<br>
        <img src="http://martin.elwin.com/blog/wp-content/uploads/2009/01/emacs-magit-status.png" alt="Emacs magit-status" title="Emacs magit-status" width="694" height="353" class="alignnone size-full wp-image-114" />
        </li>
    <li>Put the cursor over the `<em>username</em>.el` in the list of `Untracked files`.</li>
    <li>Press `s` to Stage the new file - this adds the file to the Git staging area, from which all files are committed.<br>
<img src="http://martin.elwin.com/blog/wp-content/uploads/2009/01/emacs-magit-status-staged.png" alt="Emacs magit-status staged" title="Emacs magit-status staged" width="694" height="353" class="alignnone size-full wp-image-115" />
</li>
    <li>Press `d` and then accept to diff against HEAD - this will show you a diff view of the changes we have staged - just the add of a single file.<br>
<img src="http://martin.elwin.com/blog/wp-content/uploads/2009/01/emacs-magit-status-diff.png" alt="Emacs magit-status diff" title="Emacs magit-status diff" width="757" height="429" class="alignnone size-full wp-image-116" />
</li>
    <li>Press `c` to perform the commit. This opens a new buffer into which a commit message can be added.</li>
    <li>Write something like: `Add personal configuration file.`</li>
        <li>Now press `C-c C-c` to commit the file.</li>
</ol>


<p>That&#8217;s it - now the change has been committed to the local clone of the emacs-starter-kit Git repository.</p>

<p>To see the log of all commits, press <code>l</code> (lowercase L) in the <code>magit-status</code> buffer:<br>
<img src="http://martin.elwin.com/blog/wp-content/uploads/2009/01/emacs-magit-status-log.png" alt="Emacs magit-status log" title="Emacs magit-status log" width="757" height="429" class="alignnone size-full wp-image-121" /></p>

<p>To look at a certain commit - just press <code>Enter</code> on it and a view of the diff will be shown. This makes it quite easy to browse through commits in a repository. At the top of the log is the most recent commit, which in this case is the file we just added.</p>

<p>To update emacs-starter-kit with the latest changes in the GitHub repository, just press <code>F</code> in the <code>magit-status</code> buffer or run <code>git pull</code> in the <code>~/.emacs.d</code> directory.</p>

<h3>Summary</h3>

<p>Now that we have Git and Emacs set up we can finally move to Ioke. In the next post we&#8217;ll go through installing the latest Java JDK and getting and compiling the Ioke source code.</p>

<p>Join me then!</p>

<p>/M</p>

<p><strong>Update:</strong> <a href="http://martin.elwin.com/blog/2009/01/the-hitchhikers-guide-to-an-ioke-dev-env-from-source-part-4/">Part 4: Java and Ant</a></p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[The Hitchhiker's Guide to an Ioke Dev Env From Source (part 2: Emacs)]]></title>
    <link href="http://martin.elwin.com/blog/2009/01/the-hitchhikers-guide-to-an-ioke-dev-env-from-source-part-2/"/>
    <updated>2009-01-13T00:00:00+01:00</updated>
    <id>http://martin.elwin.com/blog/2009/01/the-hitchhikers-guide-to-an-ioke-dev-env-from-source-part-2</id>
    <content type="html"><![CDATA[<p>This is the second part in a series of posts for non-experts about setting up an Ioke development environment on Linux. Please see the previous post to start at the beginning:</p>

<ul>
    <li><a href="http://martin.elwin.com/blog/2009/01/the-hitchhikers-guide-to-an-ioke-dev-env-from-source-part-1/">Part 1: Git</a></li>
</ul>


<p>In this post we will install GNU Emacs from source and also get a basic configuration set up using the <a href="http://github.com/technomancy/emacs-starter-kit/tree/master">emacs-starter-kit</a>.</p>

<p>If you already have Emacs installed and have an old configuration laying around you probably want to make a backup of this before following the below instructions. This post assumes that there is no Emacs installed and that the user doesn&#8217;t have any Emacs configuration in the home directory.</p>

<h3>Installing Emacs</h3>

<p>Git is an efficient Distributed Version Control System. Although the primary VCS for Emacs is still CVS - and it looks like they are moving towards Bazaar - we&#8217;ll get the Emacs sources from the <a href="Emacs Git mirror">Emacs Git mirror</a>. We want to be <a href="http://www.unethicalblogger.com/posts/2009/01/im_using_git_because_it_makes_me_feel_cool">cool</a>, right?</p>

<div>
  <pre><code class='sh'>~$ cd work
~/work$ git clone --depth 1 git://git.sv.gnu.org/emacs.git
Initialized empty Git repository in /home/melwin/work/emacs/.git/
remote: Counting objects: 46400, done.
remote: Compressing objects: 100% (24410/24410), done.
remote: Total 46400 (delta 41204), reused 25501 (delta 21836)
Receiving objects: 100% (46400/46400), 74.38 MiB | 213 KiB/s, done.
Resolving deltas: 100% (41204/41204), done.
Checking out files: 100% (2837/2837), done.</code></pre>
</div>


<p>With the <code>--depth 1</code> parameter we limit the history so that we only get the latest version of the files - in this case we&#8217;re not interested in the full history.</p>

<p><strong>Note:</strong> As we&#8217;re getting the bleeding edge source code of Emacs, it could happen that the build is broken. I&#8217;ve never had this happen on me, but in case you get strange errors when building Emacs, this might be the reason. Usually such problems are fixed quickly, so try to do a <code>git pull</code> a bit later to update the downloaded source.</p>

<p>Previously, to get fun things like <a href="http://www.emacswiki.org/emacs/MultiTTYSupport">multi-tty support</a> and <a href="http://www.emacswiki.org/emacs/XftGnuEmacs">smooth fonts</a>, we had to get specific feature branches of Emacs. Nowadays, however, all the things we want are merged into the Emacs master branch. Before building, the only thing we need to do is to make sure the necessary development libraries are installed. In case you wonder how I came up with this list: the good ol&#8217; method of trial and error. I simply ran the <code>configure</code> command and checked the error messages. This helped me identify the needed libraries. Now you can reap the benefits by just doing the following:</p>

<div>
  <pre><code class='sh'>~/work$ sudo apt-get install libgtk2.0-dev libxpm-dev libjpeg-dev libgif-dev libtiff-dev
...</code></pre>
</div>


<p>&#8230; and then run the classical <code>configure</code>, <code>make</code> and <code>make install</code>:</p>

<div>
  <pre><code class='sh'>~/work$ cd emacs
~/work/emacs$ ./configure --prefix=$HOME/opt/emacs-23.0.60
...
~/work/emacs$ make
...
~/work/emacs$ make install
...</code></pre>
</div>


<p>Phew. That burned som CPU cycles&#8230;! Once done - let&#8217;s add it to our <code>bin</code> directory, just as we did with Git.</p>

<div>
  <pre><code class='sh'>~/work/emacs$ cd ~/bin
~/bin$ ln -s ../opt/emacs-23.0.60/bin/emacs
~/bin$ ln -s ../opt/emacs-23.0.60/bin/emacsclient
~/bin$ ls
emacs  emacsclient  git</code></pre>
</div>


<p>Time to test. Just run emacs:</p>

<div>
  <pre><code class='sh'>~/bin% emacs</code></pre>
</div>


<p>This should show you an Emacs window with a pretty(?) GNU.</p>

<p><img src="http://martin.elwin.com/blog/wp-content/uploads/2009/01/emacs-window.png" alt="Emacs Window" title="Emacs Window" width="694" height="671" class="alignnone size-full wp-image-89" /></p>

<p>If you&#8217;re completely new to Emacs, this might be a good opportunity to run the Emacs tutorial. Emacs is a self-documenting editor, which means that most things that you might want to learn about Emacs can be found inside the editor itself - including information about internal functions and libraries.</p>

<p>To run the tutorial, just press <code>Ctrl+h t</code> (that is, <code>control</code> and <code>h</code>, release control, then press <code>t</code>), or, in Emacs lingo, <code>C-h t</code> (which is the convention I&#8217;ll use from now on).</p>

<p>Once you&#8217;ve learned enough (you did complete the whole thing, right?), just quit using <code>C-x c</code>.</p>

<p><strong>Note:</strong> To update the source code and rebuild, do a <code>git pull</code> in the <code>emacs</code> directory, then <code>make distclean</code> (in case some build files changed) and then perform the compile and installation as per the above again.</p>

<p>Next up is <code>emacs-starter-kit</code> to get more functionality in Emacs and a decent default configuration to help us get going - stay tuned!</p>

<p>/M</p>

<p><strong>Update:</strong> <a href="http://martin.elwin.com/blog/2009/01/the-hitchhikers-guide-to-an-ioke-dev-env-from-source-part-3/">Part 3: emacs-starter-kit</a></p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[The Hitchhiker's Guide to an Ioke Dev Env From Source (part 1: Git)]]></title>
    <link href="http://martin.elwin.com/blog/2009/01/the-hitchhikers-guide-to-an-ioke-dev-env-from-source-part-1/"/>
    <updated>2009-01-12T00:00:00+01:00</updated>
    <id>http://martin.elwin.com/blog/2009/01/the-hitchhikers-guide-to-an-ioke-dev-env-from-source-part-1</id>
    <content type="html"><![CDATA[<p>In this series of posts I will guide you, the humble reader, through the install procedure to get a development environment for <a href="http://ioke.org/">Ioke</a> up and running. All the cool kids want to develop in Ioke nowadays, so let&#8217;s make you can as well!</p>

<p>The components we will be installing are:</p>

<ul>
    <li><a href="http://git-scm.com/">Git 1.6.1</a></li>
    <li><a href="http://www.gnu.org/software/emacs/">Emacs (latest snapshot)</a> with <a href="http://github.com/technomancy/emacs-starter-kit/tree/master">emacs-starter-kit</a></li>
    <li><a href="http://java.sun.com/">Java JDK 1.6</a></li>
    <li><a href="http://ioke.org/">Ioke (latest snapshot)</a></li>
</ul>


<p>These instructions are written for a non-expert who might not have too much experience with compiling things, using Git or Emacs. If you&#8217;re an expert you will find nothing new or exciting here! The environment I use is a freshly installed <a href="http://www.kubuntu.org/">Kubuntu Intrepid Ibex</a> box, although most of it should be similar, if not identical, to other Ubuntu/Debian based distributions.</p>

<p>The components listed above will all be installed manually - not using the package system. This is to allow us to get the freshest versions of what we need without depending on the packages in the distribution to be updated (or hunted down in alternative repositories). The only thing we will install from the distribution are the compilers, tools and development libraries used to compile the software.</p>

<p>Why do we not use the package system? Well, that&#8217;s a valid question. Most of the above can be installed from packages in custom repositories. It&#8217;s simple and convenient. However here we will not use if for two reasons:</p>

<ol>
    <li>If packages are used we will depend on the repositories to be updated to use the latest version of some software, which can be annoying if we want to develop on the bleeding edge.</li>
    <li>It&#8217;s good to know how to compile things yourself - so by not using prepared packages we might learn something!</li>
</ol>


<p>To keep control over our custom built software we&#8217;ll install it in dedicated directories under <code>$HOME/opt</code> instead of in the normal locations like <code>/usr/bin</code>. This allows us to get everything installed without needing root access (except to install the compilers etc from the distribution).</p>

<h3>First Step</h3>

<h1>Don&#8217;t Panic!</h1>

<p>Always sound advice to start with - especially if you are hitchhiking. I&#8217;m going to try to cover each step in detail, but if you think something is unclear - just leave a comment and I&#8217;ll try to clarify. So - grab your towel and let&#8217;s get going!</p>

<h3>Install Git</h3>

<p>For Emacs, emacs-starter-kit and Ioke we will use Git to retrieve the sources. Therefore the first thing we need to install is Git.</p>

<p>In the command line instructions below, all lines prefixed by the prompt <code>&amp;lt;dir&amp;gt;$</code> are commands to be typed in. The rest are output or my comments.</p>

<p>Open a terminal window and create a new work directory under your home using the following instructions. In this directory we will work with downloaded source files and build the software.</p>

<div>
  <pre><code class='sh'>~$ mkdir ~/work
~/work$ cd ~/work
~/work$ wget -O - http://kernel.org/pub/software/scm/git/git-1.6.1.tar.bz2 | tar xjv
... many lines...</code></pre>
</div>


<p>The last command downloads the git source package and expands it in one go by piping it directly from <code>wget</code> to <code>tar</code>, which is told to expand it using bz2 with the <code>j</code> parameter. This is a convenient way to get packages off the net and unpacked, especially when there is no need to keep the package itself around.</p>

<p>The result is that we now have a <code>git-1.6.1</code> directory in the work directory. Let&#8217;s see how we compile it:</p>

<div>
  <pre><code class='sh'>~/work$ cd git-1.6.1/
~/work/git-1.6.1$ head INSTALL

                Git installation

Normally you can just do &quot;make&quot; followed by &quot;make install&quot;, and that
will install the git programs in your own ~/bin/ directory.  If you want
to do a global install, you can do

        $ make prefix=/usr all doc info ;# as yourself
        # make prefix=/usr install install-doc install-html install-info ;# as root

~/work/git-1.6.1$</code></pre>
</div>


<p>So - two commands. Simple enough! However, before we compile - we need to make sure all the relevant packages are installed:</p>

<div>
  <pre><code class='sh'>~/work/git-1.6.1$ sudo apt-get install libcurl4-openssl-dev zlib1g-dev libexpat-dev tk8.5 asciidoc docbook2x</code></pre>
</div>


<p>Depending on your internet connection, this could take quite a while, as we need to download the <code>texlive</code> distribution, among other things, to build all of the Git documentation. This is not strictly necessary, but here we&#8217;ll just do it for completeness&#8217; sake.</p>

<p>Let&#8217;s build git and make sure it&#8217;s installed under our <code>$HOME/opt</code> directory as we said in the beginning:</p>

<div>
  <pre><code class='sh'>~/work/git-1.6.1$ make prefix=~/opt/git-1.6.1 all doc info
... lots of lines...</code></pre>
</div>


<p>Compiling Git will take some time as well. Go get a coffee (or perhaps a <a href="http://en.wikibooks.org/wiki/Bartending/Cocktails/Pan_Galactic_Gargle_Blaster">Pan Galactic Gargle Blaster</a> - sweet like nectar).</p>

<p>Once the compile is done - install it. Note that we don&#8217;t need to do this as <code>root</code> as we&#8217;re installing under the user home directory:</p>

<div>
  <pre><code class='sh'>~/work/git-1.6.1$ make prefix=~/opt/git-1.6.1 install install-doc install-html install-info</code></pre>
</div>


<p>Let&#8217;s add it to the user&#8217;s path by linking it into the private <code>bin</code> directory. This depends on the standard Ubuntu <code>bash</code> shell profile script which adds <code>~/bin</code> to the <code>PATH</code> variable. If a different shell is used you need to perform the appropriate steps yourself.</p>

<div>
  <pre><code class='sh'>~/work/git-1.6.1$ mkdir ~/bin
~/work/git-1.6.1$ cd !$
~/bin$ ln -s ../opt/git-1.6.1/bin/git</code></pre>
</div>


<p>Now close the shell/terminal, open a new one - and try the <code>git</code> command:</p>

<div>
  <pre><code class='sh'>~$ git --version
git version 1.6.1</code></pre>
</div>


<p>If you get the above output - great! You&#8217;re don! Sit back and relax for a bit before moving on to the next section.</p>

<p>However, if you don&#8217;t get the version output, but instead see the following message, review the previous instructions and make sure it works ok before continuing.</p>

<div>
  <pre><code class='sh'>#INCORRECT OUTPUT - SOMETHING WAS MISSED!
#GO BACK AND REVIEW
~$ git                                                                                                                                                                                        
The program 'git' is currently not installed.  You can install it by typing:                                                                                                                  
sudo apt-get install git-core                                                                                                                                                                 
-bash: git: command not found</code></pre>
</div>


<p>If you still can&#8217;t get it to work - drop me a comment!</p>

<h3>Git in 30 Seconds</h3>

<p>There are loads of good Git tutorials and information. You can find several on the <a href="http://git-scm.com/documentation">official Git page</a> and at <a href="http://github.com/guides/home">GitHub</a> (go sign up if you haven&#8217;t already, and <a href="http://github.com/melwin">fork me</a>!).</p>

<p>Here is a quick run through of a few common Git commands you could try out with your freshly brewed cup of Git:</p>

<div>
  <pre><code class='sh'>~$ cd
~$ mkdir gittest
~$ cd gittest/
~/gittest$ git init
Initialized empty Git repository in /home/melwin/gittest/.git/
~/gittest$ echo Test file! &gt; test.txt
~/gittest$ git add test.txt
~/gittest$ git commit -m &quot;Initial import.&quot;
[master (root-commit)]: created 79c091d: &quot;Initial import.&quot;
 1 files changed, 1 insertions(+), 0 deletions(-)
 create mode 100644 test.txt
~/gittest$ echo Add line. &gt;&gt; test.txt
~/gittest$ git diff test.txt
diff --git a/test.txt b/test.txt
index 1cbaf90..3746f9e 100644
--- a/test.txt
+++ b/test.txt
@@ -1 +1,2 @@
 Test file!
+Add line.
~/gittest$ git commit -a -m &quot;Add new line.&quot;
[master]: created b20f9a4: &quot;Add new line.&quot;
 1 files changed, 1 insertions(+), 0 deletions(-)</code></pre>
</div>


<p>If you can follow the above - great! First part finished. Next up is to install GNU Emacs from source and the emacs-starter-kit, which provides a decent default a set of configuration for Emacs.</p>

<p>Stay tuned!</p>

<p>/M</p>

<p><strong>Update:</strong> <a href="http://martin.elwin.com/blog/2009/01/the-hitchhikers-guide-to-an-ioke-dev-env-from-source-part-2/">Part 2: Emacs</a></p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Simple JSON Parser in Ioke]]></title>
    <link href="http://martin.elwin.com/blog/2009/01/simple-json-parser-in-ioke/"/>
    <updated>2009-01-10T00:00:00+01:00</updated>
    <id>http://martin.elwin.com/blog/2009/01/simple-json-parser-in-ioke</id>
    <content type="html"><![CDATA[<p>After having enjoyed most of the days off over Christmas my fingers started itching - time to do some programming. Luckily around the same time I stumbled across <a href="http://olabini.com/blog/category/ioke/">Ola Bini&#8217;s posts on the Ioke language</a>. As the <a href="http://ioke.org/guide.html">Ioke guide</a> begins:</p>

<blockquote>
Ioke is a general purpose language. It is a strongly typed, extremely dynamic, prototype object oriented language. It is homoiconic and it&#8217;s closest ancestors is Io, Smalltalk, Ruby and Lisp - but it&#8217;s quite a distance from all of them.
</blockquote>


<p>So what does this all mean? It means it&#8217;s fun! The language syntax is very regular (although not quite as regular as lisp) - code is data, data is code and everything is a message. It&#8217;s also one of relatively few languages that provide macros similar to those in lisp. In Ioke this means that a message stream can be operated on (modified, transformed, etc) before it&#8217;s evaluated, using normal Ioke methods. Anyone who groks lisp should be familiar with the power this gives.</p>

<p>In Ioke, a chain of messages is separated by space, with the first message being sent to the current receiver and subsequent messages are sent to the result of the previous one. For instance, in the code</p>

<div>
  <pre><code class='ioke'>&quot;ioke rocks&quot; upper println</code></pre>
</div>


<p>the text literal &#8220;ioke rocks&#8221; results in an internal message which creates a Text object. To this object the <code>upper</code> messages is sent, which results in an upper case copy of the Text object is created. To this object the <code>println</code> message is sent, which prints the upper case text to the console.</p>

<p>As the Ioke reader handles space separated tokens, it&#8217;s quite easy to create macros to process non Ioke code. As a learning exercise I decided to try to implement a <a href="http://www.json.org/">JSON</a> parser. Nothing too fancy - and doesn&#8217;t even have to be secure - just enough to parse simple JSON into Ioke objects.</p>

<p>JSON is usually parsed in one of two ways - into custom objects/classes or into collections like dictionaries and arrays. For this exercise I decided to create Ioke dictionaries and arrays and I want the result to work like this:</p>

<div>
  <pre><code class='ioke'>json({
  &quot;string&quot; : &quot;string1&quot;,
  &quot;int&quot; : 1234,
  &quot;arr&quot; : [&quot;item1&quot;, &quot;item2&quot;],
  &quot;dict&quot; : {&quot;key1&quot;:&quot;value1&quot;}
}) println  ;; =&gt; {dict={key1=value1}, arr=[item1, item2], int=1234, string=string1}

json([&quot;string&quot;,
  1234,
  [&quot;item1&quot;, &quot;item2&quot;],
  {&quot;key1&quot;: &quot;val1&quot;}
]) println ;; =&gt; [string, 1234, [item1, item2], {key1=val1}]</code></pre>
</div>


<p>Now, looking at JSON, it&#8217;s suspiciously similar to Ioke - [] is used for arrays, {} is used for &#8220;dictionaries&#8221;, comma separates entries, &#8221; quotes strings, etc. The main problem is the colon &#8220;:&#8221; used for separating keys and values in a dictionary. As Ioke is a dynamic language we can redefine how messages are handled. Instead of using colon to define symbols, we can redefine it to instead create pairs suitable for a dict:</p>

<div>
  <pre><code class='ioke'>Text cell(&quot;:&quot;) = macro(call resendToMethod(&quot;=&gt;&quot;))</code></pre>
</div>


<p>&#8221;:&#8221; is originally defined on DefaultBehavior Literals, but in the JSON the &#8220;:&#8221; message is always sent to Text, so it&#8217;s enough to redefine it there.</p>

<p>This single redefinition allows us to parse JSON directly with the Ioke reader - very nice.</p>

<p>But&#8230; Redefining &#8220;:&#8221; for all Text objects is not really good (especially not when Ola adds concurrency constructs!). Another alternative would be to redefine how the text objects are created and create a new &#8220;:&#8221; cell just for our JSON text objects - but I never got this to work, as the internal:createText message works with a raw Java string, which I couldn&#8217;t work with in a macro/method&#8230;</p>

<p><strong>Update:</strong> With <a href="http://github.com/olabini/ioke/commit/8af3954df7961b3f594c73db5059310469e45df5">Ola&#8217;s recent commit</a>, the previously described workaround can now be simplified to the following code.</p>

<p>Now the above redefinition of the &#8220;:&#8221; message can be used, but is visible only in the scope of a <code>let</code>:</p>

<div>
  <pre><code class='ioke'>json = macro(let(Text cell(&quot;:&quot;), DefaultBehavior cell(&quot;=&gt;&quot;),
    call argAt(0)
))

;; Used as:

json({
  &quot;string&quot; : &quot;string1&quot;,
  &quot;int&quot; : 1234,
  &quot;arr&quot; : [&quot;item1&quot;, &quot;item2&quot;],
  &quot;dict&quot; : {&quot;key1&quot;:&quot;value1&quot;}
  }) println

json([&quot;string&quot;,
  1234,
  [&quot;item1&quot;, &quot;item2&quot;],
  {&quot;key1&quot;: &quot;val1&quot;}
  ]) println</code></pre>
</div>


<p>As can be seen, the Ioke macro functionality gives us nice control over how messages are handled, and the environment can be changed before the arguments are evaluated. I&#8217;m looking forward to the day when we have full Java interop and can use these powerful constructs to control Java code!</p>

<p>Source code to the above example is committed to my Ioke fork at: <a href="git://github.com/melwin/ioke.git">git://github.com/melwin/ioke.git</a></p>

<p>/M</p>

<p>PS: The thing that confuses me the most: how the heck are you supposed to pronounce Ioke?</p>

<p><strong>Update:</strong> Sam Aaron shared the fact that Ola pronounces it eye-oh-key in the following interview: <a href="http://www.akitaonrails.com/2008/11/22/rails-podcast-brasil-qcon-special-ola-bini-jruby-ioke">http://www.akitaonrails.com/2008/11/22/rails-podcast-brasil-qcon-special-ola-bini-jruby-ioke</a></p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Ioke Syntax Highlighter for GeSHi]]></title>
    <link href="http://martin.elwin.com/blog/2009/01/ioke-syntax-highlighter-for-geshi/"/>
    <updated>2009-01-10T00:00:00+01:00</updated>
    <id>http://martin.elwin.com/blog/2009/01/ioke-syntax-highlighter-for-geshi</id>
    <content type="html"><![CDATA[<p>Speaking of Ioke - just added a syntax highlighter definition for GeSHi in my Ioke fork repository. The commit can be found here:</p>

<p><a href="http://github.com/melwin/ioke/commit/54cfd7e54de0be910385c6ec805693fd3ed4e294">http://github.com/melwin/ioke/commit/54cfd7e54de0be910385c6ec805693fd3ed4e294</a></p>

<p>The keyword definitions I borrowed (read stole) from <a href="http://sam.aaron.name/">Sam Aaron</a>&#8217;s TextMate bundle (also in the Ioke repository). As Sam just said in the #ioke on freenode: &#8220;what goes around comes around&#8221;. :)</p>

<p>Highlighting test:</p>

<div>
  <pre><code class='ioke'>m = #/({areaCode}\d{3})-({localNumber}\d{5})/ =~ number

    describe(&quot;start&quot;,
      it(&quot;should return the start index of group zero, which is the whole group&quot;,
        (#/foo/ =~ &quot;foobar&quot;) start should == 0
        (#/foo/ =~ &quot;abcfoobar&quot;) start should == 3

        (#/foo/ =~ &quot;foobar&quot;) start(0) should == 0
        (#/foo/ =~ &quot;abcfoobar&quot;) start(0) should == 3
      )

      it(&quot;should return the start index of another group&quot;,
        (#/(..) (..) (..)/ =~ &quot;fooab cd efbar&quot;) start(2) should == 6
      )

      it(&quot;should return the start index from the name of a named group&quot;,
        (#/({one}..) ({two}..) ({three}..)/ =~ &quot;fooab cd efbar&quot;) start(:two) should == 6
      )

      it(&quot;should return -1 for a group that wasn't matched&quot;,
        (#/(..)((..))?/ =~ &quot;ab&quot;) start(2) should == -1
        (#/({no}..)(({way}..))?/ =~ &quot;ab&quot;) start(:way) should == -1

        (#/(..)((..))?/ =~ &quot;ab&quot;) start(10) should == -1
        (#/({no}..)(({way}..))?/ =~ &quot;ab&quot;) start(:blarg) should == -1
      )

      it(&quot;should validate type of receiver&quot;,
        Regexp Match should checkReceiverTypeOn(:start)
      )
    )
    
    x = #/bla #{&quot;foo&quot;} bar/</code></pre>
</div>


<p>/M</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Caching Filter Queries with Coherence]]></title>
    <link href="http://martin.elwin.com/blog/2008/09/caching-filter-queries-with-coherence/"/>
    <updated>2008-09-21T00:00:00+02:00</updated>
    <id>http://martin.elwin.com/blog/2008/09/caching-filter-queries-with-coherence</id>
    <content type="html"><![CDATA[<p>A pretty nice thing that I recently tried with a customer was storing a query result in a query cache.</p>

<p>For instance, consider the following method:</p>

<div>
  <pre><code class='java'>public Collection getByFilter1(String cacheName, Filter f) {
    NamedCache c = CacheFactory.getCache(cacheName);
    return c.entrySet(f);
}</code></pre>
</div>


<p>A query is executed across all nodes containing cache data in a cluster. The filter acts on the <em>values</em> in the cache, not the keys. And as all values are usually not available locally on every node the query needs to execute on the separate nodes.</p>

<p>The query above is correct, but not very efficient. In the above case we query and retrieve the data as well from the separate nodes. A more efficient way would be to only get the keys for the matching values from the nodes and then retrieve the values from the local near cache:</p>

<div>
  <pre><code class='java'>public Collection getByFilter2(String cacheName, Filter f) {
    NamedCache c = CacheFactory.getCache(cacheName);
    Set keys = c.keySet(f);
    return c.getAll(keys).values();
}</code></pre>
</div>


<p>However, in this case we still perform the query every time.</p>

<p>Now - the clever part. Not so much on my side, but the Coherence engineers have thought things through and made the Filter implementations have good hashCode and equals implementations. This together with the fact that they are serializable makes them possible to use as keys in a cache! Sweet! Without changing our method&#8217;s interface we can add a query cache so that each query only is performed once.</p>

<div>
  <pre><code class='java'>public Collection getByFilter3(String cacheName, Filter f) {
    NamedCache c = CacheFactory.getCache(cacheName);

    NamedCache queryC = CacheFactory.getCache(cacheName + &quot;.querycache&quot;);
    Set keys = (Set)queryC.get(f);

    if(keys == null) {
        keys = c.keySet(f);
        queryC.put(f, keys);
    }

    return c.getAll(keys).values();
}</code></pre>
</div>


<p>Note that we only save the keys in the query cache. This to avoid having several caches with the same data. When near caching is used, getting the data for the keys can still be a local only operation. Compared to getting the data from the separate nodes it&#8217;s several orders of magnitude faster - depending on the usage patterns.</p>

<p>Of course if queries are different every time, the query cache will not help much. But in most high load applications the same data tends to be needed several times.</p>

<p>Additionally, the properties queried on should in most cases be indexed. This is important to avoid too much overhead when searching for an entry in a cache.</p>

<p>One thing to think about when adding query caches is: how is data updated?</p>

<p>As part of updating the value caches the query caches should preferably be emptied of the outdated cached queries. This could be done programmatically &#8220;manually&#8221; when the data is updated, or by hooking in code to clean the entries from the query cache using the map listener mechanism. The relevant code could do a query using the ContainsFilter.</p>

<p>To summarize: a little code can go a long way to improve performance without affecting the interface used by an application. Good when query heavy applications are adapted to use a distributed cache like Coherence.</p>

<p>/M</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Scala Syntax Highlighting for WP]]></title>
    <link href="http://martin.elwin.com/blog/2008/06/scala-syntax-highlighting-for-wp/"/>
    <updated>2008-06-30T00:00:00+02:00</updated>
    <id>http://martin.elwin.com/blog/2008/06/scala-syntax-highlighting-for-wp</id>
    <content type="html"><![CDATA[<p>Writing the previous post I realized that the Wordpress plugin for syntax highligting I was using (Highlight Source Pro) didn&#8217;t support Scala.</p>

<p>Instead I tried the WP-Syntax plugin, but this didn&#8217;t support Symbol literals:</p>

<div>
  <pre><code class='scala'>val sym = 'foobar
println(&quot;Symbol is: &quot; + sym)
val other = 'barfoo</code></pre>
</div>


<p>This seems to be because of single quote being interpreted as a quotation character. A fix seems to be removing the single quote from the Geshi language definition file <code>scala.php</code> in the <code>wp-syntax/geshi/geshi</code> directory. While there one can also specify a regex for symbols and give them their own color:</p>

<div>
  <pre><code class='scala'>val sym = 'foobar
println(&quot;Symbol is: &quot; + sym)
val other = 'barfoo</code></pre>
</div>


<p>Also check out the <a href="https://lampsvn.epfl.ch/trac/scala/browser/scala-tool-support/trunk/src/geshi/scala.php"><code>scala.php</code> in the LAMP repository</a> - it seems to add some additional keywords and other colors. I used this and made the changes described above.</p>

<p>Full new <code>scala.php</code> for Geshi after the break.</p>

<!--more-->




<div>
  <pre><code class='php'>&lt;?php
/*************************************************************************************
 * scala.php
 * --------
 * Author: Geoffrey Washburn (washburn@acm.ogr)
 * Copyright: (c) 2004 Nigel McNie (http://qbnz.com/highlighter/)
 * Release Version: ???
 * Date Started: 2008/01/03
 *
 * Scala language file for GeSHi.
 *
 * CHANGES
 * -------
 * 2007/01/03
 *   -  Created by copying the Java highlighter
 *
 * TODO
 * -------------------------
 * * Finish
 *
 *************************************************************************************
 *
 *     This file is part of GeSHi.
 *
 *   GeSHi is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *
 *   GeSHi is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with GeSHi; if not, write to the Free Software
 *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 ************************************************************************************/

$language_data = array (
        'LANG_NAME' =&gt; 'Scala',
        'COMMENT_SINGLE' =&gt; array(1 =&gt; '//'),   /* import statements are not comments! */
        'COMMENT_MULTI' =&gt; array('/*' =&gt; '*/'),
        'CASE_KEYWORDS' =&gt; GESHI_CAPS_NO_CHANGE,
        'QUOTEMARKS' =&gt; array('&quot;', '&quot;&quot;&quot;'),
        'ESCAPE_CHAR' =&gt; '\\',
        'KEYWORDS' =&gt; array(
                1 =&gt; array(
                        /* Scala keywords, part 1: control flow */
                        'case', 'default', 'do', 'else', 'for',
                        'if', 'match', 'while'
                        ),
                2 =&gt; array(
                        /* Scala keywords, part 2 */
                        'return', 'throw',
                        'try', 'catch', 'finally',
                        'abstract', 'class', 'def', 'extends',
                        'final', 'forSome', 'implicit', 'import',
                        'lazy', 'new', 'object', 'override', 'package',
                        'private', 'protected',
                        'requires', 'sealed', 'super', 'this', 'trait', 'type',
                        'val', 'var', 'with', 'yield'
                        ),
                3 =&gt; array(
                        /* Scala keywords, part 3: standard value types */
                        'unit', 'Unit', 'boolean', 'Boolean', 'int', 'Int', 'Any', 'AnyVal', 'Nothing',
                        ),
                4 =&gt; array(
                        /* other reserved words in Scala: literals */
                        /* should be styled to look similar to numbers and Strings */
                        'false', 'null', 'true'
                        ),
                5 =&gt; array(
                        /* Scala reference types */
                        'AnyRef', 'Null', 'List', 'String', 'Integer', 'Option', 'Array'
                        )

                ),
        'SYMBOLS' =&gt; array(
                ':', '*', '&amp;', '%', '!', ';', '&lt;', '&gt;', '?', '_', '=', '=&gt;',
                '&lt;-', '&lt;:', '&lt;%', '&gt;:', '#', '@'
                ),
        'CASE_SENSITIVE' =&gt; array(
                GESHI_COMMENTS =&gt; true,
                /* all Scala keywords are case sensitive */
                1 =&gt; true, 2 =&gt; true, 3 =&gt; true, 4 =&gt; true, 5 =&gt; true ),
        'STYLES' =&gt; array(
                'KEYWORDS' =&gt; array(
                        1 =&gt; 'color: #b1b100;',
                        2 =&gt; 'color: #000000; font-weight: bold;',
                        3 =&gt; 'color: #993333;',
                        4 =&gt; 'color: #b13366;',
                        5 =&gt; 'color: #aaaadd;'
                        ),
                'SYMBOLS' =&gt; array(
                        0 =&gt; 'color: #FFAA00;'
                        ),
                'COMMENTS' =&gt; array(
                        1 =&gt; 'color: #808080; font-style: italic;',
                        'MULTI' =&gt; 'color: #808080; font-style: italic;'
                        ),
                'ESCAPE_CHAR' =&gt; array(
                        0 =&gt; 'color: #000099; font-weight: bold;'
                        ),
                'BRACKETS' =&gt; array(
                        0 =&gt; 'color: #66cc66;'
                        ),
                'STRINGS' =&gt; array(
                        0 =&gt; 'color: #ff0000;'
                        ),
                'NUMBERS' =&gt; array(
                        0 =&gt; 'color: #cc66cc;'
                        ),
                'METHODS' =&gt; array(
                        1 =&gt; 'color: #006600;',
                        2 =&gt; 'color: #006600;'
                        ),
                'SCRIPT' =&gt; array(
                        ),
                'REGEXPS' =&gt; array(
                        0 =&gt; 'color: #008000;'
                        )
                ),
        'URLS' =&gt; array(
                1 =&gt; '',
                2 =&gt; '',
                3 =&gt; '',
                4 =&gt; ''
                ),
        'OOLANG' =&gt; true,
        'OBJECT_SPLITTERS' =&gt; array(
                1 =&gt; '.'
                ),
        'REGEXPS' =&gt; array(
               0 =&gt; &quot;'[a-zA-Z_][a-zA-Z0-9_]*&quot;
                ),
        'STRICT_MODE_APPLIES' =&gt; GESHI_NEVER,
        'SCRIPT_DELIMITERS' =&gt; array(
                ),
        'HIGHLIGHT_STRICT_BLOCK' =&gt; array(
                )
);

?&gt;</code></pre>
</div>



]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Clustering Scala Actors with Oracle Coherence for Fun and Profit]]></title>
    <link href="http://martin.elwin.com/blog/2008/06/clustering-scala-actors-with-oracle-coherence/"/>
    <updated>2008-06-30T00:00:00+02:00</updated>
    <id>http://martin.elwin.com/blog/2008/06/clustering-scala-actors-with-oracle-coherence</id>
    <content type="html"><![CDATA[<p>[Disclaimer: I work for Oracle.]</p>

<p>Although I haven&#8217;t used it too much yet, Scala is definitely one of the languages I find most interesting right now. Many customers I work with are heavily Java focused, and getting a more flexible and powerful language with superb Java interoperability to use on the JVM feels very liberating. Now I just need to convince the customers that Scala is the future&#8230; :] But if <a href="http://www.adam-bien.com/roller/abien/entry/java_net_javaone_which_programming">Gosling likes it</a> it must be good, right?</p>

<p>A few months ago Jonas Bonér wrote about how <a href="http://jonasboner.com/2008/01/25/clustering-scala-actors-with-terracotta/">Scala actors can be clustered with Terracotta</a>. I really enjoyed the article and I think the idea of distributed, redundant actors is very appealing. The actor paradigm is a nice way of developing concurrent applications (see the intro in Jonas&#8217; blog entry for more info) and if we can liberate the actors from the confines of a single JVM and easily distribute them over multiple hosts - all the better.</p>

<h3>Clustering with Coherence</h3>

<p>I&#8217;m not going to compare Coherence and Terracotta here. In short, <a href="http://www.oracle.com/technology/products/coherence/index.html">Coherence</a> provides, among other things, a distributed caching and code execution mechanism without single points of failure. Coherence can be downloaded for evaluation purposes from the Oracle web site.</p>

<p>The idea I wanted to try was to have Scala actors that store their state in the distributed Coherence cache and run as normal Scala actors on a single node in the cluster at a time. The node the actor runs on should be allocated by Coherence and if the node fails, the actor should be automatically started on another node with maintained state and without any lost messages.</p>

<p>Also, I wanted this to work as similarly to normal Scala actors as possible with compatibility between the two.</p>

<h3>The Result</h3>

<p>Before investigating the proof of concept solution, let&#8217;s look at the result and what it gives us.</p>

<p>Here&#8217;s a simple test application with a normal Scala actor. It uses the recommended way of creating actors with <code>actor { ... }</code>:</p>

<div>
  <pre><code class='scala'>package coherencetest1

import java.util.Date

import scala.actors.Actor._

object ActorTest {
  def main(args : Array[String]) : Unit = {

    actor {
      var pings : Int = 0
      
      println(&quot;Actor started.&quot;)
      
      self ! ('ping, 1)
      
      loop {
        react {
        case ('ping, i : Int) =&gt;
          pings = pings + 1
          println(new Date + &quot; - Got ping: &quot; + i + &quot; Total pings: &quot; + pings)
          
          Thread.sleep(1000)

          self ! ('ping, i+1)
        }
      }
    }

  }
}</code></pre>
</div>


<p>When this code is run, a simple actor that sends a message to itself is created and started. It sleeps for 1 second to pace the execution and to simulate a task that takes time to perform (of course, normally you shouldn&#8217;t sleep in real actors as you tie up the thread).</p>

<p>When the code is run, the following is displayed:</p>

<div>
  <pre><code class='text'>Actor started.
Sun Jun 29 15:57:16 CEST 2008 - Got ping: 1 Total pings: 1
Sun Jun 29 15:57:17 CEST 2008 - Got ping: 2 Total pings: 2
Sun Jun 29 15:57:18 CEST 2008 - Got ping: 3 Total pings: 3
Sun Jun 29 15:57:19 CEST 2008 - Got ping: 4 Total pings: 4
Sun Jun 29 15:57:20 CEST 2008 - Got ping: 5 Total pings: 5
Sun Jun 29 15:57:21 CEST 2008 - Got ping: 6 Total pings: 6
...</code></pre>
</div>


<p>Nothing too fancy, but a decent test case for our actor distribution. An important aspect of this actor is that it defines a local variable <code>pings</code> and prints a message in the initialization part, before the <code>loop</code> and <code>react</code>. The value of the local var must be maintained and the initialization code must only be run once, and not when an actor is started on a new node after a failure.</p>

<p>Let&#8217;s make it a distributed Actor:</p>

<div>
  <pre><code class='scala'>package coherencetest1

import java.util.Date

import scala.actors.coherence.CoActor._

@serializable
object DactorTest {
  def main(args : Array[String]) : Unit = {

    dactor {
      var pings : Int = 0
      
      println(&quot;Actor started.&quot;)
      
      self ! ('ping, 1)
      
      loop {
        react {
        case ('ping, i : Int) =&gt;
          pings = pings + 1
          println(new Date + &quot; - Got ping: &quot; + i + &quot; Total pings: &quot; + pings)
          
          Thread.sleep(1000)

          self ! ('ping, i+1)
        }
      }
    }

  }
}</code></pre>
</div>


<p>What have we done here? Three things:</p>

<ol>
    <li>Import `scala.actors.coherence.CoActor._` instead of `scala.actors.Actor._`</li>
    <li>Made the <em>application object</em> serializable</li>
    <li>Create the actor using `dactor { &#8230; }` instead of `actor { &#8230; }`</li>
</ol>


<p>The first point is simple - we need access to the new functionality, so we import the new CoActor object instead of the standard Actor object.</p>

<p>For number two - this is slightly nasty. If I interpret things correctly; as the code block created as a parameter to <code>react</code> needs to be serializable (so that the actor can be distributed over the network), all enclosing types needs to be serializable. I struggled with this for a while and the only option seems to be creating a proper named serializable type&#8230; But since I want to be able to create an actor in-line, we need to do it this way.</p>

<p>For the last point - <code>dactor { ... }</code> is simply the function used to create a distributed actor instead of a normal actor.</p>

<p>Let&#8217;s run it:</p>

<div>
  <pre><code class='text'>2008-06-29 16:11:18.779 Oracle Coherence 3.3.1/389 &lt;Info&gt; (thread=main, member=n/a): Loaded operational configuration from resource &quot;jar:file:/opt/coherence-3.3.1/lib/coherence.jar!/tangosol-coherence.xml&quot;
2008-06-29 16:11:18.785 Oracle Coherence 3.3.1/389 &lt;Info&gt; (thread=main, member=n/a): Loaded operational overrides from resource &quot;jar:file:/opt/coherence-3.3.1/lib/coherence.jar!/tangosol-coherence-override-dev.xml&quot;
2008-06-29 16:11:18.786 Oracle Coherence 3.3.1/389 &lt;D5&gt; (thread=main, member=n/a): Optional configuration override &quot;/tangosol-coherence-override.xml&quot; is not specified

Oracle Coherence Version 3.3.1/389
 Grid Edition: Development mode
Copyright (c) 2000-2007 Oracle. All rights reserved.

2008-06-29 16:11:19.042 Oracle Coherence GE 3.3.1/389 &lt;Info&gt; (thread=main, member=n/a): Loaded cache configuration from resource &quot;file:/crypt/dev/scala/CoherenceTest1/config/scalacoherence.xml&quot;
2008-06-29 16:11:19.331 Oracle Coherence GE 3.3.1/389 &lt;Warning&gt; (thread=main, member=n/a): UnicastUdpSocket failed to set receive buffer size to 1428 packets (2096304 bytes); actual size is 714 packets (1048576 bytes). Consult your OS documentation regarding increasing the maximum socket buffer size. Proceeding with the actual value may cause sub-optimal performance.
2008-06-29 16:11:19.459 Oracle Coherence GE 3.3.1/389 &lt;D5&gt; (thread=Cluster, member=n/a): Service Cluster joined the cluster with senior service member n/a
2008-06-29 16:11:22.662 Oracle Coherence GE 3.3.1/389 &lt;Info&gt; (thread=Cluster, member=n/a): Created a new cluster with Member(Id=1, Timestamp=2008-06-29 16:11:19.343, Address=192.168.54.1:8088, MachineId=24065, Location=process:31397@dellicious, Edition=Grid Edition, Mode=Development, CpuCount=2, SocketCount=1) UID=0xC0A836010000011AD4A9DCAF5E011F98
2008-06-29 16:11:22.834 Oracle Coherence GE 3.3.1/389 &lt;D5&gt; (thread=DistributedCache, member=1): Service DistributedCache joined the cluster with senior service member 1
Actor started.
Sun Jun 29 16:11:23 CEST 2008 - Got ping: 1 Total pings: 1
Sun Jun 29 16:11:24 CEST 2008 - Got ping: 2 Total pings: 2
Sun Jun 29 16:11:25 CEST 2008 - Got ping: 3 Total pings: 3
Sun Jun 29 16:11:26 CEST 2008 - Got ping: 4 Total pings: 4
Sun Jun 29 16:11:27 CEST 2008 - Got ping: 5 Total pings: 5
Sun Jun 29 16:11:28 CEST 2008 - Got ping: 6 Total pings: 6
...</code></pre>
</div>


<p>After the Coherence initialization (which happens automatically and which I&#8217;ve disabled in the outputs below) the actor starts up as expected. However, if we start this on two nodes - there will be two actors created, and no way for a new JVM to get hold of a reference to a specific existing actor. To handle this, let&#8217;s specify a name for the actor that we create using the <code>dactor(name : Symbol) { ... }</code> function:</p>

<div>
  <pre><code class='scala'>...
object DactorTest {
  def main(args : Array[String]) : Unit = {

    dactor('pingActor) {
      var pings : Int = 0
...</code></pre>
</div>


<p>This simply means: Give me a reference to <code>pingActor</code>, but if it doesn&#8217;t exist - create it with the following body. This mechanism makes it easy to have a single instance of an actor even if the same application is running on multiple nodes, without having to explicitly check if an actor has already been created or not.</p>

<p>Now we can run the program on two different nodes. After the actor has started and is running on one node, I&#8217;ll kill that node:</p>

<table>
<tr valign="top">
<td>Node 1</td><td>Node 2</td></tr>
<tr valign="top">
<td><div>
  <pre><code class='text'>Actor started.
Sun Jun 29 16:30:41 CEST 2008 - Got ping: 1 Total pings: 1
Sun Jun 29 16:30:42 CEST 2008 - Got ping: 2 Total pings: 2
Sun Jun 29 16:30:43 CEST 2008 - Got ping: 3 Total pings: 3
Sun Jun 29 16:30:44 CEST 2008 - Got ping: 4 Total pings: 4
Sun Jun 29 16:30:45 CEST 2008 - Got ping: 5 Total pings: 5
Sun Jun 29 16:30:46 CEST 2008 - Got ping: 6 Total pings: 6
Sun Jun 29 16:31:02 CEST 2008 - Got ping: 19 Total pings: 19
Sun Jun 29 16:31:03 CEST 2008 - Got ping: 20 Total pings: 20
Sun Jun 29 16:31:04 CEST 2008 - Got ping: 21 Total pings: 21
Sun Jun 29 16:31:05 CEST 2008 - Got ping: 22 Total pings: 22
Sun Jun 29 16:31:06 CEST 2008 - Got ping: 23 Total pings: 23
Sun Jun 29 16:31:07 CEST 2008 - Got ping: 24 Total pings: 24
Sun Jun 29 16:31:08 CEST 2008 - Got ping: 25 Total pings: 25
Sun Jun 29 16:31:09 CEST 2008 - Got ping: 26 Total pings: 26
Sun Jun 29 16:31:10 CEST 2008 - Got ping: 27 Total pings: 27
Sun Jun 29 16:31:11 CEST 2008 - Got ping: 28 Total pings: 28
...</code></pre>
</div>
</td>
<td><div>
  <pre><code class='text'>Sun Jun 29 16:30:47 CEST 2008 - Got ping: 6 Total pings: 6
Sun Jun 29 16:30:48 CEST 2008 - Got ping: 7 Total pings: 7
Sun Jun 29 16:30:49 CEST 2008 - Got ping: 8 Total pings: 8
Sun Jun 29 16:30:50 CEST 2008 - Got ping: 9 Total pings: 9
Sun Jun 29 16:30:51 CEST 2008 - Got ping: 10 Total pings: 10
Sun Jun 29 16:30:53 CEST 2008 - Got ping: 11 Total pings: 11
Sun Jun 29 16:30:54 CEST 2008 - Got ping: 12 Total pings: 12
Sun Jun 29 16:30:55 CEST 2008 - Got ping: 13 Total pings: 13
Sun Jun 29 16:30:56 CEST 2008 - Got ping: 14 Total pings: 14
Sun Jun 29 16:30:57 CEST 2008 - Got ping: 15 Total pings: 15
Sun Jun 29 16:30:58 CEST 2008 - Got ping: 16 Total pings: 16
Sun Jun 29 16:30:59 CEST 2008 - Got ping: 17 Total pings: 17
Sun Jun 29 16:31:00 CEST 2008 - Got ping: 18 Total pings: 18
Sun Jun 29 16:31:01 CEST 2008 - Got ping: 19 Total pings: 19^C</code></pre>
</div>
</td>
</tr></table>


<p>First Node 1 started up and ran the actor until Node 2 started. At this point the actor was distributed to Node 2 (determined by the automatic cache partitioning done by Coherence) and started there. As can be seen, the local state (the total pings) was persisted and transferred over. When Node 2 was killed the actor was migrated back and started on Node 1. Note that the state of the actor is persisted for each message, so a sudden shutdown of a JVM is not a problem.</p>

<p>One might wonder why the message for ping number 6 and 19 can be seen in both outputs - this happens as the actor was migrated while the actor thread was sleeping - before the react body was complete. This causes the new node to rerun the message (since the processing of the message didn&#8217;t complete on the old node) and the support code in the old node makes sure all messages sent by the old actor are discarded as it&#8217;s been terminated. It&#8217;s a bit tricky coding actors to be fully idempotent as not everything is handled in a transaction, but limiting side effects to sending messages at the end of the processing makes it fairly reliable.</p>

<p>Here&#8217;s a slightly more complex example:</p>

<div>
  <pre><code class='scala'>package coherencetest1

import java.util.Date

import scala.actors.coherence.CoActor._

@serializable
object DactorTest2 {
  def main(args : Array[String]) : Unit = {
    init
    
    readLine
    
    val numActors = 80

    val actors = for(id &lt;- 1 to numActors)
      yield dactor {
        loop {
          react {
          case 'ping =&gt;
            println(new Date + &quot; - Actor &quot; + id + &quot; got ping.&quot;)
            reply(('pong, id))
          }
        }
      }
    
    actors.map(_ ! 'ping).force
    
    var pongs = 0
    
    while(pongs &lt; numActors) {
      receive {
      case ('pong, x : Int) =&gt;
        pongs = pongs + 1
      }
    }
    
    println(&quot;Got &quot; + pongs + &quot; pongs.&quot;)
    
    readLine
  }
}</code></pre>
</div>


<p>In this example 80 distributed actors are created and sent a ping message. After that the main thread receives all the pong replies. The output of this, when run on 4 nodes look like so:</p>

<table>
<tr valign="top">
<td>Node 1</td><td>Node 2</td></tr>
<tr valign="top">
<td><div>
  <pre><code class='text'>Sun Jun 29 09:19:34 CEST 2008 - Actor 1 got ping.
Sun Jun 29 15:19:34 CEST 2008 - Actor 12 got ping.
Sun Jun 29 15:19:34 CEST 2008 - Actor 15 got ping.
Sun Jun 29 15:19:34 CEST 2008 - Actor 18 got ping.
Sun Jun 29 15:19:35 CEST 2008 - Actor 22 got ping.
Sun Jun 29 15:19:35 CEST 2008 - Actor 25 got ping.
Sun Jun 29 15:19:35 CEST 2008 - Actor 27 got ping.
Sun Jun 29 15:19:35 CEST 2008 - Actor 29 got ping.
Sun Jun 29 15:19:35 CEST 2008 - Actor 41 got ping.
Sun Jun 29 15:19:35 CEST 2008 - Actor 42 got ping.
Sun Jun 29 15:19:35 CEST 2008 - Actor 47 got ping.
Sun Jun 29 15:19:35 CEST 2008 - Actor 50 got ping.
Sun Jun 29 15:19:35 CEST 2008 - Actor 54 got ping.
Sun Jun 29 15:19:35 CEST 2008 - Actor 56 got ping.
Sun Jun 29 15:19:35 CEST 2008 - Actor 61 got ping.
Sun Jun 29 15:19:36 CEST 2008 - Actor 75 got ping.
Sun Jun 29 15:19:36 CEST 2008 - Actor 79 got ping.
Sun Jun 29 15:19:36 CEST 2008 - Actor 80 got ping.
Got 80 pongs.</code></pre>
</div>
</td>
<td><div>
  <pre><code class='text'>Sun Jun 29 15:19:34 CEST 2008 - Actor 9 got ping.
Sun Jun 29 15:19:34 CEST 2008 - Actor 13 got ping.
Sun Jun 29 15:19:34 CEST 2008 - Actor 19 got ping.
Sun Jun 29 15:19:34 CEST 2008 - Actor 20 got ping.
Sun Jun 29 15:19:34 CEST 2008 - Actor 21 got ping.
Sun Jun 29 15:19:35 CEST 2008 - Actor 23 got ping.
Sun Jun 29 15:19:35 CEST 2008 - Actor 24 got ping.
Sun Jun 29 15:19:35 CEST 2008 - Actor 28 got ping.
Sun Jun 29 15:19:35 CEST 2008 - Actor 33 got ping.
Sun Jun 29 15:19:35 CEST 2008 - Actor 36 got ping.
Sun Jun 29 15:19:35 CEST 2008 - Actor 46 got ping.
Sun Jun 29 15:19:35 CEST 2008 - Actor 52 got ping.
Sun Jun 29 15:19:35 CEST 2008 - Actor 57 got ping.
Sun Jun 29 15:19:35 CEST 2008 - Actor 58 got ping.
Sun Jun 29 15:19:35 CEST 2008 - Actor 62 got ping.
Sun Jun 29 15:19:36 CEST 2008 - Actor 67 got ping.
Sun Jun 29 15:19:36 CEST 2008 - Actor 68 got ping.
Sun Jun 29 15:19:36 CEST 2008 - Actor 71 got ping.
Sun Jun 29 15:19:36 CEST 2008 - Actor 77 got ping.</code></pre>
</div>
</td>
</tr>
<tr valign="top">
<td>Node 3</td><td>Node 4</td></tr>
<tr valign="top">
<td><div>
  <pre><code class='text'>Sun Jun 29 15:19:34 CEST 2008 - Actor 2 got ping.
Sun Jun 29 15:19:34 CEST 2008 - Actor 4 got ping.
Sun Jun 29 15:19:34 CEST 2008 - Actor 5 got ping.
Sun Jun 29 15:19:34 CEST 2008 - Actor 6 got ping.
Sun Jun 29 15:19:34 CEST 2008 - Actor 7 got ping.
Sun Jun 29 15:19:34 CEST 2008 - Actor 8 got ping.
Sun Jun 29 15:19:34 CEST 2008 - Actor 10 got ping.
Sun Jun 29 15:19:34 CEST 2008 - Actor 11 got ping.
Sun Jun 29 15:19:35 CEST 2008 - Actor 30 got ping.
Sun Jun 29 15:19:35 CEST 2008 - Actor 31 got ping.
Sun Jun 29 15:19:35 CEST 2008 - Actor 32 got ping.
Sun Jun 29 15:19:35 CEST 2008 - Actor 34 got ping.
Sun Jun 29 15:19:35 CEST 2008 - Actor 35 got ping.
Sun Jun 29 15:19:35 CEST 2008 - Actor 37 got ping.
Sun Jun 29 15:19:35 CEST 2008 - Actor 39 got ping.
Sun Jun 29 15:19:35 CEST 2008 - Actor 40 got ping.
Sun Jun 29 15:19:35 CEST 2008 - Actor 43 got ping.
Sun Jun 29 15:19:35 CEST 2008 - Actor 44 got ping.
Sun Jun 29 15:19:35 CEST 2008 - Actor 45 got ping.
Sun Jun 29 15:19:35 CEST 2008 - Actor 53 got ping.
Sun Jun 29 15:19:35 CEST 2008 - Actor 59 got ping.
Sun Jun 29 15:19:35 CEST 2008 - Actor 60 got ping.
Sun Jun 29 15:19:35 CEST 2008 - Actor 63 got ping.
Sun Jun 29 15:19:35 CEST 2008 - Actor 64 got ping.
Sun Jun 29 15:19:35 CEST 2008 - Actor 66 got ping.
Sun Jun 29 15:19:36 CEST 2008 - Actor 69 got ping.
Sun Jun 29 15:19:36 CEST 2008 - Actor 70 got ping.
Sun Jun 29 15:19:36 CEST 2008 - Actor 72 got ping.
Sun Jun 29 15:19:36 CEST 2008 - Actor 74 got ping.</code></pre>
</div>
</td>
<td><div>
  <pre><code class='text'>Sun Jun 29 15:19:34 CEST 2008 - Actor 3 got ping.
Sun Jun 29 15:19:34 CEST 2008 - Actor 14 got ping.
Sun Jun 29 15:19:34 CEST 2008 - Actor 16 got ping.
Sun Jun 29 15:19:34 CEST 2008 - Actor 17 got ping.
Sun Jun 29 15:19:35 CEST 2008 - Actor 26 got ping.
Sun Jun 29 15:19:35 CEST 2008 - Actor 38 got ping.
Sun Jun 29 15:19:35 CEST 2008 - Actor 48 got ping.
Sun Jun 29 15:19:35 CEST 2008 - Actor 49 got ping.
Sun Jun 29 15:19:35 CEST 2008 - Actor 51 got ping.
Sun Jun 29 15:19:35 CEST 2008 - Actor 55 got ping.
Sun Jun 29 15:19:35 CEST 2008 - Actor 65 got ping.
Sun Jun 29 15:19:36 CEST 2008 - Actor 73 got ping.
Sun Jun 29 15:19:36 CEST 2008 - Actor 76 got ping.
Sun Jun 29 15:19:36 CEST 2008 - Actor 78 got ping.</code></pre>
</div>
</td>
</tr>
</table>


<p>The program was started on all 4 nodes, but only the first node passes the first readLine. The other nodes just init the distributed actor framework and wait. As can be seen, the actors were distributed over the running nodes as expected - however, with small numbers like this the distribution can be a bit uneven (compare Node 3 and Node 4).</p>

<h3>The Solution</h3>

<p>The solution to allow the distribution of serializable actors is based on the Coherence backing map listeners. These can be used to get notifications of which specific node is the master for a certain object. As there only is one master for an object at any point, and a new master is allocated automatically if a master fails, we can use this to determine where the actor should run.</p>

<p>The object returned from <code>dactor { ... }</code> is a Proxy object - very similar to the Proxy used in the standard Scala remote actors. In fact, this whole thing is built in a way similar to the standard Scala remote actors, with Proxy objects acting on behalf of the sender on the receiver side and receiver on the sender side.</p>

<p>Additionally, the Coherence grid invocation mechanism allows us to deliver messages to running actors directly to the node where it is running.</p>

<p>When a new dactor is created, the following happens:</p>

<ol>
    <li>`dactor { &#8230; }` creates a new anonymous `CoActor` class with the dactor body set as the `init` method.</li>
    <li>The CoActor.distribute method is called which in turn saves the anonymous class instance to the Coherence cache. The object gets serialized when this happens. The key to the object in the cache is either the passed in symbol name, or a name created from a `java.util.UUID`</li>
    <li>The `dactor` function returns a Proxy object with the name of the newly created distributed actor.</li>
    <li>Meanwhile, in the node which Coherence designates the master of the object, the backing map listener gets an insert event and starts the actor.</li>
    <li>The default `act()` method is called, which in a CoActor calls the `init` method first.</li>
    <li>The `init` method contains the `dactor { &#8230; }` body, which gets executed.</li>
    <li>The body executes as normally up until the `loop` block. `loop` in the CoActor first saves the body of the loop into a variable in CoActor so that it can continue executing just this body after it&#8217;s started in a new node, without running the initialization code again. After this the loop body is run as normal.</li>
    <li>When `react` is hit, the thread breaks and the actor waits for incoming message using the normal actor scheduling mechanism.</li>
</ol>


<p>When a message is sent to a distributed actor using a Proxy object the following happens:</p>

<ol>
    <li>The message is sent using the Coherence invocation mechanism which transports the message to the master node where the cached actor runs.</li>
    <li>In the master node, a Proxy actor representing the sender (which does not need to be a distributed actor) is created - this is because the actor framework always needs a sending actor which the receiver can reply to.</li>
    <li>The sender Proxy is asked to send the actual message to the real distributed actor receiver.</li>
    <li>The normal Scala actor framework handles the passing of the message and scheduling of the actors.</li>
    <li>An overriden `send` in CoActor locks the actor and stores the message and a Save message in the mailbox.</li>
    <li>The Save message gets the actor to first persist itself to the Coherence cache with the real message still in the mailbox. This is to ensure the message isn&#8217;t lost in case of a node failure.</li>
    <li>After this the real message is processed by the actor and an overridden `react` saves the actor again after the message has been processed. This to update the cache with the new state of the actor.</li>
</ol>


<p>If the distributed actor does a <code>reply</code> or sends a message to the <code>sender</code>, the <code>Proxy</code> which represents the non-distributed actor gets called as follows:</p>

<ol>
    <li>As the recevier (the original sender) isn&#8217;t a distributed actor handled by Coherence we cannot use the invocation mechanism. Instead the message is just put into a message cache.</li>
    <li>A `MapListener` on every node checks to see if the newly inserted message in the message cache is intended for an actor running on that specific node.</li>
    <li>If so, the message is deleted from the cache and delivered to the local actor through a Proxy representing the sender - just as in the previous case.</li>
</ol>


<h3>The Limitations</h3>

<p>The distributed actors are a bit limited in what they can do, as they always needs to be serializable and I didn&#8217;t want to change any of the standard Scala code. For instance - when a synchronous invocation is made the return channel is stored in the Scala actor. The return channel implementation used in Scala isn&#8217;t serializable, so I decided to not implement this feature for now.</p>

<p>Basically, only message sending (!), reply, sender, loop and react are allowed in the distributed actors. However, they can interoperate with normal actors as can be seen in this example:</p>

<div>
  <pre><code class='scala'>val distActor = dactor('distActor) {
      loop {
        react {
        case ('ping) =&gt;
          reply('pong)
        }
      }
    }
    
    actor {
      distActor ! 'ping
      loop {
        react {
        case x =&gt;
          println(&quot;Actor got message: &quot; + x)
        }
      }
    }</code></pre>
</div>


<p>The Proxy objects can be used by actors as they serialize correctly.</p>

<h3>The Conclusion</h3>

<p>Distributing (or GridEnabling(tm) or whatever the word <em>du jour</em> is) actors to easily use the processing power and resilience multiple computers give but at the same time hiding the complexity from the developer is a nice way to fairly easily scale up an actors based application. To add more processing power or redundancy - just fire up new nodes.</p>

<p>The proof of concept I made here just scratches the surface, but it&#8217;s interesting to see that it can be done with Coherence while maintaining the syntax and behavior expected by Scala developers.</p>

<h3>The Source</h3>

<p>The highly experimental and hackish source code for the proof of concept is available in the git repository at:</p>

<pre>
http://martin.elwin.com/git/scala-coherence.git
</pre>


<p>Dependencies are Scala (2.7.1 recommended) and Oracle Coherence. There are some scripts for Linux which are trivial to adapt to other operating environments.</p>

<p>/M</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[DCOP and xmobar]]></title>
    <link href="http://martin.elwin.com/blog/2008/05/dcop-and-xmobar/"/>
    <updated>2008-05-22T00:00:00+02:00</updated>
    <id>http://martin.elwin.com/blog/2008/05/dcop-and-xmobar</id>
    <content type="html"><![CDATA[<p>For me, the computer is a work tool that should get out of the way as much as possible to allow me to perform the task at hand. I spend many hours every day working with, primarily, my laptop, and seemingly insignificant improvements to the desktop environment and development tools add up over time to improve my overall efficiency. Because of this I like to spend time looking into how the tools I use can be tuned to better help in what I need to do.</p>

<p>One of the fairly recent chances I&#8217;ve made is to switch to a <a href="http://en.wikipedia.org/wiki/Tiling_window_manager">tiling window manager</a>. For those too lazy to read the Wikipedia entry: A tiling window manager automatically arranges the open windows to fill the available space of the screen - saving you the job of arranging the windows yourself. That sounds simple, but can be quite complex in practice.</p>

<p>I started out using <a href="http://modeemi.fi/~tuomov/ion/">Ion3</a> in mid 2007. Ion3 is nice and smooth and worked great and really got me hooked on tiled window managers. However, as a big fan of open source, I was a bit concerned by the author&#8217;s approach to controlling the development of Ion (see <a href="http://womble.decadent.org.uk/blog/renaming-of-ion3">this</a> or <a href="http://forums.gentoo.org/viewtopic-t-559010-start-0-postdays-0-postorder-asc-highlight-.html">this</a> for instance) so I switched to <a href="http://www.suckless.org/wiki/">wmii</a>. wmii was also quite nice, but I never got into it as well as Ion, for some reason.</p>

<p>That&#8217;s when I found <a href="http://xmonad.org/">xmonad</a> - a very nice window manager written in <a href="http://www.haskell.org/">Haskell</a>. Haskell is also used as the configuration language, which makes the configuration possibilities close to endless (actually, they probably are endless, as Haskell is Turing equivalent (although there are <a href="http://en.wikipedia.org/wiki/Talk:Type_polymorphism#Why_Haskell.3F">people who doubt it</a>!) :).</p>

<p>Today, some 6 months later, I use xmonad 0.7 together with KDE 3.5.9 (similar to the <a href="http://www.haskell.org/haskellwiki/Xmonad/Using_xmonad_in_KDE">setup described on the Haskell wiki</a>) on Kubuntu 8.04 and am very happy with it.</p>

<h3>Status Bar</h3>

<p>However, xmonad is just a tiling window manager, but I also want a status bar to allow me to see chosen pieces of information at a glance. I use KDE3 and have the KDE3 panel <code>kicker</code> running, but it&#8217;s hidden unless I put the mouse in the bottom left corner. I don&#8217;t use it normally and only keep it around to access the system tray (which I almost never need). Instead of the ugly and bulky <code>kicker</code> I want a smaller, slimmer alternative&#8230;</p>

<p>Enter <a href="http://code.haskell.org/~arossato/xmobar/">xmobar</a> - a text based status bar, also written in Haskell. xmobar comes with a number of plugins to show different aspects of the system on the status bar - date, cpu, memory, network activity, etc. A few things it doesn&#8217;t do out of the box, which I want to see, are number of new mails, current keyboard layout (I use US mainly, but switch to Swedish for the national chars) and speaker mute state. Luckily, xmobar provides a plugin to execute shell commands, and using this mechanism we can put anything on the status bar, as long as we can figure out a command to run to produce the wanted text.</p>

<h3>New Mails</h3>

<p>I use a <a href="http://en.wikipedia.org/wiki/Maildir">Maildir</a> mail storage (together with <a href="http://www.dovecot.org/">dovecot</a> to provide an IMAP interface to my mail), and since I don&#8217;t automatically split mails into groups/folders it&#8217;s enough to just check the number of mails in my Maildir&#8217;s <code>new</code> folder. The xmobar command for this ends up as:</p>

<div>
  <pre><code class='haskell'>Run Com &quot;sh&quot; [&quot;-c&quot;, &quot;\&quot;ls ~/Maildir/new | wc -l\&quot;&quot;] &quot;mailcount&quot; 600</code></pre>
</div>


<p>This command invokes the <code>sh</code> shell and passes a <em>command string</em> using the <code>-c</code> switch. The command string contains the actual shell command we want to execute: <code>ls ~/Maildir/new | wc -l</code></p>

<p>Executing <code>sh</code> and passing a command string allows us to use the pipe to pass the output of the <code>ls</code> to the <code>wc</code> to get the actual file count back.</p>

<p>The command is mapped to the <code>mailcount</code> alias, and the interval is set to 600 tenths of a second = 60 seconds.</p>

<h3>Keyboard Layout</h3>

<p>Since I use KDE3 the keyboard layout switching is handled by the <code>kxkb</code> application (shows up as a flag in the tray if multiple layouts are configured). KDE3 uses <a href="http://en.wikipedia.org/wiki/DCOP">DCOP</a> (unlike KDE4 which uses <a href="http://en.wikipedia.org/wiki/D-Bus">D-Bus</a>) for IPC. Available DCOP services can easily be interogated from the command line using the&#8230; you guessed it&#8230; <code>dcop</code> command.</p>

<p>Running <code>dcop</code> without parameters shows a list of available applications. On my system it shows:</p>

<div>
  <pre><code class='bash'>% dcop
konsole-9099
kdebluetooth
kicker
kxkb
guidance-6223
kded
adept_notifier
kmix
knotify
kio_uiserver
klauncher
khotkeys
kwalletmanager
digikam-6484
klipper
ksmserver
knetworkmanager</code></pre>
</div>


<p>Woohoo! kxkb is there, so let&#8217;s dig deeper. By a bit of trial and error we can probe the internals of the dcop-exposed application:</p>

<div>
  <pre><code class='bash'>% dcop kxkb
qt
MainApplication-Interface
kxkb
% dcop kxkb kxkb
QCStringList interfaces()
QCStringList functions()
bool setLayout(QString layoutPair)
QString getCurrentLayout()
QStringList getLayoutsList()
void forceSetXKBMap(bool set)
% dcop kxkb kxkb getCurrentLayout
us</code></pre>
</div>


<p>Sweet! Now we have the dcop &#8220;path&#8221; to find the current keyboard layout. Let&#8217;s add it to the xmobar configuration:</p>

<div>
  <pre><code class='haskell'>Run Com &quot;dcop&quot; [&quot;kxkb&quot;, &quot;kxkb&quot;, &quot;getCurrentLayout&quot;] &quot;kbd&quot; 20</code></pre>
</div>


<h3>Speaker Mute State</h3>

<p>Using <code>dcop</code> again we can find the mute state:</p>

<div>
  <pre><code class='bash'>% dcop kmix
qt
MainApplication-Interface
Mixer0
kmix
kmix-mainwindow#1
% dcop kmix Mixer0
QCStringList interfaces()
QCStringList functions()
void setVolume(int deviceidx,int percentage)
void setMasterVolume(int percentage)
void increaseVolume(int deviceidx)
void decreaseVolume(int deviceidx)
int volume(int deviceidx)
int masterVolume()
void setAbsoluteVolume(int deviceidx,long int absoluteVolume)
long int absoluteVolume(int deviceidx)
long int absoluteVolumeMin(int deviceidx)
long int absoluteVolumeMax(int deviceidx)
void setMute(int deviceidx,bool on)
void setMasterMute(bool on)
void toggleMute(int deviceidx)
void toggleMasterMute()
bool mute(int deviceidx)
bool masterMute()
int masterDeviceIndex()
void setRecordSource(int deviceidx,bool on)
bool isRecordSource(int deviceidx)
void setBalance(int balance)
bool isAvailableDevice(int deviceidx)
QString mixerName()
int open()
int close()
% dcop kmix Mixer0 masterMute
true</code></pre>
</div>


<p>Perfect - now we can create the last xmobar run command:</p>

<div>
  <pre><code class='haskell'>Run Com &quot;dcop&quot; [&quot;kmix&quot;, &quot;Mixer0&quot;, &quot;masterMute&quot;] &quot;mute&quot; 20</code></pre>
</div>


<h3>Final Configuration</h3>

<p>So, here&#8217;s the final <code>.xmobarrc</code>:</p>

<div>
  <pre><code class='haskell'>Config { font = &quot;xft:Consolas-8&quot;
       , bgColor = &quot;black&quot;
       , fgColor = &quot;grey&quot;
       , position = Bottom
       , commands = [ Run Network &quot;eth0&quot; [&quot;-L&quot;,&quot;0&quot;,&quot;-H&quot;,&quot;32&quot;,&quot;--normal&quot;,&quot;green&quot;,&quot;--high&quot;,&quot;red&quot;] 50
                    , Run Network &quot;wlan0&quot; [&quot;-L&quot;,&quot;0&quot;,&quot;-H&quot;,&quot;32&quot;,&quot;--normal&quot;,&quot;green&quot;,&quot;--high&quot;,&quot;red&quot;] 51
                    , Run Cpu [&quot;-L&quot;,&quot;3&quot;,&quot;-H&quot;,&quot;50&quot;,&quot;--normal&quot;,&quot;green&quot;,&quot;--high&quot;,&quot;red&quot;] 52
                    , Run Memory [&quot;-t&quot;,&quot;Mem: &lt;usedratio&gt;%&quot;] 54
                    , Run Date &quot;%a %b %_d %H:%M:%S&quot; &quot;date&quot; 10
                    , Run StdinReader
                    , Run Com &quot;dcop&quot; [&quot;kxkb&quot;, &quot;kxkb&quot;, &quot;getCurrentLayout&quot;] &quot;kbd&quot; 20
                    , Run Com &quot;sh&quot; [&quot;-c&quot;, &quot;\&quot;ls ~/Maildir/new | wc -l\&quot;&quot;] &quot;mailcount&quot; 600
                    , Run Com &quot;dcop&quot; [&quot;kmix&quot;, &quot;Mixer0&quot;, &quot;masterMute&quot;] &quot;mute&quot; 20
                    ]
       , sepChar = &quot;%&quot;
       , alignSep = &quot;}{&quot;
       , template = &quot;&lt;fc=#ee9a00&gt;%date%&lt;/fc&gt; | %cpu% | %memory% | %eth0% - %wlan0% } %StdinReader% { Mail: %mailcount% | Kbd: %kbd% | Mute: %mute%&quot;
       }</code></pre>
</div>


<p>And a small screenshot for your viewing pleasure:</p>

<p><a href='http://martin.elwin.com/blog/wp-content/uploads/2008/05/xmonad.png'><img src="http://martin.elwin.com/blog/wp-content/uploads/2008/05/xmonad.png" alt="" title="xmonad" width="300" height="187" class="alignnone size-medium wp-image-23" /></a>
(Yes, my laptop&#8217;s hostname is <em>dellicious</em>&#8230; ;)</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Scala XML and Java DOM]]></title>
    <link href="http://martin.elwin.com/blog/2008/05/scala-xml-and-java-dom/"/>
    <updated>2008-05-15T00:00:00+02:00</updated>
    <id>http://martin.elwin.com/blog/2008/05/scala-xml-and-java-dom</id>
    <content type="html"><![CDATA[<p>How do we go from and DOM to Scala XML the most efficiently? Well&#8230; That&#8217;s what I asked myself the other day. The Scala API <a href="http://www.scala-lang.org/docu/files/api/scala/xml/XML$object.html"><code>scala.xml.XML</code></a> object has helper functions to create Scala XML structures from the usual suspects: Strings, InputStream, Reader, File, etc. But DOM Document or Element is missing.</p>

<p>Going via a Byte array, Char array or String is simple. For instance, the following outputs the DOM to a char array, which is then used as the source of the Scala XML creation:</p>

<div>
  <pre><code class='java'>Using Char array
//dom is the DOM Element
val charWriter = new CharArrayWriter()
TransformerFactory.newInstance.newTransformer.transform(new DOMSource(dom), new StreamResult(charWriter))
val xml = XML.load(new CharArrayReader(charWriter.toCharArray))</code></pre>
</div>


<p>This works fine, and is reasonably fast. However, it does allocate some unnecessary memory (the char array) and performs some unnecessary parsing (of the char array) - both of which we&#8217;d really like to avoid.</p>

<p>How do we do this? Well, here&#8217;s one option that I came up with:</p>

<div>
  <pre><code class='java'>Using SAX
val saxHandler = new NoBindingFactoryAdapter()
saxHandler.scopeStack.push(TopScope)
TransformerFactory.newInstance.newTransformer.transform(new DOMSource(dom), new SAXResult(saxHandler))
saxHandler.scopeStack.pop
val xml = saxHandler.rootElem</code></pre>
</div>


<p>What&#8217;s going on here? Well, the Scala XML library uses SAX to parse XML and create the XML structure. One way of generating SAX events is to walk a DOM tree, which is handled by the <code>javax.xml.transform.Transformer</code> with a <code>DOMSource</code> as input and a <code>SAXResult</code> as output. The extension of the <code>DefaultHandler</code> needed for handling the SAX events is implemented by the <code>scala.xml.parsing.FactoryAdapter</code>, which is extended by the <code>NoBindingFactoryAdapter</code> used to construct the XML structure. Because of this, we can do violence on the API and use the <code>NoBindingFactoryAdapter</code> directly as a SAX <code>DefaultHandler</code> - nice! The <code>scopeStack</code> calls are done to maintain the scope information, which I stole from the <code>loadXML</code> method in the <code>AdapterFactory</code> class.</p>

<p>However, let&#8217;s take a moment to reflect on this. Using the Scala XML library in this way is not really good. Even if it&#8217;s possible to do it this way, I&#8217;ve not seen it described as a supported way of using it and therefore it should be done only after considering that the next release of Scala might remove this possibility.</p>

<p>[<strong>Update 2008-07-02:</strong> <a href="http://burak.emir.googlepages.com/">Burak Emir</a> kindly added a comment; &#8220;Don&#8217;t worry, the SAX factory adapter is not going to go away.&#8221; - good to know!]</p>

<p>That said - let&#8217;s consider this an exploration of possibilities which could potentially lead to an update of the Scala XML API to allow a DOM to be used as a source instead&#8230;!</p>

<p>A quick test gives the following result.</p>

<p>Test data is a 6897 bytes XML file containing 118 elements with some 4 different namespaces.</p>

<p>I ran each test in 1000 iterations, with a full garbage collection before the first iteration. For every 100 iterations I printed the delta of the free memory and then timed the time for the complete 1000 iterations.</p>

<p>Char array: 100 iterations use around 28 MB, full test: 1414 ms
SAX: 100 iterations use around 18 MB, full test: 970 ms</p>

<p>So, in conclusion, not overwhelming difference, but around 1/3 faster and 1/3 less memory consumed. Can we do better? I&#8217;m not sure. :)</p>

<p>The next step is to do Scala XML to DOM&#8230; This could be more interesting. I see two options:</p>

<ol>
    <li>Implement the DOM API wrapping Scala XML</li>
    <li>Generate SAX events based on the Scala XML and use that to build a DOM</li>
</ol>


<p>Option 1 would be more efficient - but the DOM API isn&#8217;t fun implementing. Option 2 would be much simpler, but probably would be less efficient and require more allocations. Gotta think about this one&#8230;</p>

<p>/M</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[UML Use Case Diagrams & Graphviz]]></title>
    <link href="http://martin.elwin.com/blog/2008/05/uml-use-case-diagrams-graphviz/"/>
    <updated>2008-05-11T00:00:00+02:00</updated>
    <id>http://martin.elwin.com/blog/2008/05/uml-use-case-diagrams-graphviz</id>
    <content type="html"><![CDATA[<p>First post!</p>

<p>Oh, right, this isn&#8217;t Slashdot&#8230;</p>

<p>Anywho, here goes:</p>

<p>While at a customer, a few colleagues and I were joking about <a href="http://en.wikipedia.org/wiki/Use_case_diagram">Use Case diagrams</a>, which in their most basic form tend to be somewhat meaningless. However, in more complex requirements definitions, they certainly can help define actors and sections of functionality to go into certain releases, for instance.</p>

<p>As I at the time was pondering how to best visualize the customer&#8217;s SOA architecture and service dependencies by generating <a href="http://www.graphviz.org">Graphviz</a> diagrams, I thought - hey, why not use Graphviz to quickly produce some snazzy Use Case Diagrams?</p>

<p>Well&#8230; the snazziness is debatable, and I didn&#8217;t manage it as quickly as I had hoped. But all considered, I think they turned out quite well.</p>

<p>To begin with, I have to figure out how to render a stick figure for a node. When using the postscript output, you can <a href="http://www.graphviz.org/Documentation/html/shapehowto.html">create custom shapes</a>, but since I want to create just a PNG image, I need to use an image as the custom shape file.</p>

<p>With <a href="http://www.inkscape.org/">Inkscape</a> I managed to produce the following:</p>

<p><a href='http://martin.elwin.com/blog/wp-content/uploads/2008/05/stick.png'><img src="http://martin.elwin.com/blog/wp-content/uploads/2008/05/stick.png" alt="Use Case Stick Figure" title="Use Case Stick Figure" class="size-full wp-image-13" /></a></p>

<p>Very nice.</p>

<p>Saving this as <code>stick.png</code>, we can create a simple diagram:</p>

<div>
  <pre><code class='dot'>1.dot
digraph G {
    &quot;User&quot; [shapefile=&quot;stick.png&quot;];
    &quot;Log In&quot; [shape=ellipse];
    &quot;User&quot;-&gt;&quot;Log In&quot; [arrowhead=none]
}</code></pre>
</div>


<p>This can be run through the Graphviz <code>dot</code> program thus:</p>

<div>
  <pre><code class='sh'>cat 1.dot | dot -Tpng &gt; 1.png</code></pre>
</div>


<p>Which produces:</p>

<p><a href='http://martin.elwin.com/blog/wp-content/uploads/2008/05/1.png'><img src="http://martin.elwin.com/blog/wp-content/uploads/2008/05/1.png" alt="Use Case 1" title="1.png" class="size-medium wp-image-16" /></a></p>

<p>Hmmm&#8230; Not quite what we wanted. Let&#8217;s make a few changes:</p>

<ul>
    <li>Make the graph left-right.</li>
    <li>Get rid of the box.</li>
    <li>Move the actor label to below the stick figure.</li>
</ul>


<p>The most difficult of this is moving the label. This seems to require creating a cluster subgraph containing a label and the node with the custom shape. An example of this can be seen in <a href="http://www.karakas-online.de/forum/viewtopic.php?t=2647">this Graphviz tutorial</a>. Another alternative is using HTML in the label - but this looks ugly. So, doing this, and refactoring a bit to create nodes explicitly, we get:</p>

<div>
  <pre><code class='dot'>2.dot
digraph G {
   rankdir=LR;

    subgraph clusterUser {label=&quot;User&quot;; labelloc=&quot;b&quot;; peripheries=0; user};
    user [shapefile=&quot;stick.png&quot;, peripheries=0, style=invis];

    login [label=&quot;Log In&quot;, shape=ellipse];

    user-&gt;login [arrowhead=none];
}</code></pre>
</div>


<p>&#8230; which gives us:</p>

<p><a href='http://martin.elwin.com/blog/wp-content/uploads/2008/05/2.png'><img src="http://martin.elwin.com/blog/wp-content/uploads/2008/05/2.png" alt="Use Case 2" title="2.png"  class="size-full wp-image-17" /></a></p>

<p>Not too bad. Let&#8217;s add some more use cases:</p>

<div>
  <pre><code class='dot'>3.dot
digraph G {
    rankdir=LR;
    labelloc=&quot;b&quot;;
    peripheries=0;

    /* Actor Nodes */

    node [shape=plaintext, style=invis];

    subgraph clusterUser {label=&quot;User&quot;; user};
    user [shapefile=&quot;stick.png&quot;];

    subgraph clusterAdmin {label=&quot;Administrator&quot;; admin};
    admin [shapefile=&quot;stick.png&quot;];


    /* Use Case Nodes */

    node [shape=ellipse, style=solid];

    log_in [label=&quot;Log In&quot;];

    log_in_pwd [label=&quot;Log In Password&quot;];
    log_in_cert [label=&quot;Log In Certificate&quot;];

    manage_user [label=&quot;Manage User&quot;];
    change_email [label=&quot;Change Email&quot;];
    change_pwd [label=&quot;Change Password&quot;];
    

    /* Edges */

    edge  [arrowhead=&quot;oarrow&quot;];

    admin-&gt;user;

    edge [arrowhead=none];
    
    user-&gt;log_in;
    admin-&gt;manage_user;

    edge [arrowtail=&quot;vee&quot;, label=&quot;&lt;&lt;extend&gt;&gt;&quot;, style=dashed];

    log_in-&gt;manage_user;
    log_in-&gt;log_in_pwd;
    log_in-&gt;log_in_cert;

    manage_user-&gt;change_email;
    manage_user-&gt;change_pwd;
}</code></pre>
</div>


<p>Run through <code>dot</code> this produces the following image:</p>

<p><a href='http://martin.elwin.com/blog/wp-content/uploads/2008/05/3.png'><img src="http://martin.elwin.com/blog/wp-content/uploads/2008/05/3.png" alt="Use Case 3" title="3.png" class="size-full wp-image-18" /></a></p>

<p>The obvious problem with this is that the nodes aren&#8217;t placed were we really want them to be. Automatic node placement in a directed graph is one the strong points of dot, but the default placement doesn&#8217;t really correspond to how we want our Use Case to look. So, let&#8217;s add some hints to help dot place the nodes in the way we like it:</p>

<div>
  <pre><code class='dot'>4.dot
digraph G {
    rankdir=LR;
    labelloc=&quot;b&quot;;
    peripheries=0;

    /* Actor Nodes */

    node [shape=plaintext, style=invis];

    subgraph clusterUser {label=&quot;User&quot;; user};
    subgraph clusterAdmin {label=&quot;Administrator&quot;; admin};

    {
        rank=min;

        user [shapefile=&quot;stick.png&quot;];
        admin [shapefile=&quot;stick.png&quot;];
    }


    /* Use Case Nodes */

    node [shape=ellipse, style=solid];

    {
        rank=same;

        log_in [label=&quot;Log In&quot;];
        manage_user [label=&quot;Manage User&quot;];
    }

    log_in_pwd [label=&quot;Log In Password&quot;];
    log_in_cert [label=&quot;Log In Certificate&quot;];

    change_email [label=&quot;Change Email&quot;];
    change_pwd [label=&quot;Change Password&quot;];
    

    /* Edges */

    edge  [arrowhead=&quot;oarrow&quot;];

    admin-&gt;user;

    edge [arrowhead=none];
    
    user-&gt;log_in;
    admin-&gt;manage_user;

    edge [arrowtail=&quot;vee&quot;, label=&quot;&lt;&lt;extend&gt;&gt;&quot;, style=dashed];

    log_in-&gt;manage_user;
    log_in-&gt;log_in_pwd;
    log_in-&gt;log_in_cert;

    manage_user-&gt;change_email;
    manage_user-&gt;change_pwd;
}</code></pre>
</div>


<p>Which produces:</p>

<p><a href='http://martin.elwin.com/blog/wp-content/uploads/2008/05/4.png'><img src="http://martin.elwin.com/blog/wp-content/uploads/2008/05/4.png" alt="Use Case 4" title="4.png"  class="size-full wp-image-19" /></a>
Sweet!</p>

<p>Now, I don&#8217;t see most people working with requirements modeling getting too excited by this. The ones I&#8217;ve worked with tend to prefer graphical tools. But Graphviz is an excellent option when one wants to visualize data sets by automatically generating diagrams - and the more that can be done automatically, the better!</p>

<p>/M</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Compressed and Encrypted Backup with SquashFS and LUKS]]></title>
    <link href="http://martin.elwin.com/blog/2008/05/backups-with-squashfs-and-luks/"/>
    <updated>2008-05-11T00:00:00+02:00</updated>
    <id>http://martin.elwin.com/blog/2008/05/backups-with-squashfs-and-luks</id>
    <content type="html"><![CDATA[<p><a href="http://kubuntu.org">Hardy Heron (KDE flavor)</a> has been out for a while now and this weekend I finally decided to upgrade my (sweet sweet Dell M90) laptop from Gutsy. I used this as justification to get a new Hitachi SATA 200GB 7200RPM disk to replace the old 250GB 5200RPM in an effort to boost performance a little. Getting a new disk also makes the upgrade a lot less risky - I can keep the old disk as it is while setting up the new system.</p>

<p>This time around I decided to get rid of the Windows partition previously used for dual booting (haven&#8217;t booted into Windows in 6 months). I also wanted to switch from the extremely useful and amazing <a href="http://www.truecrypt.org/">Truecrypt</a> to using Linux native <a href="http://luks.endorphin.org/">LUKS</a> encryption for my work and private data. I originally used Truecrypt on Linux with an NTFS file system to make the encrypted drive compatible with both Windows and Linux, but since then I&#8217;ve switched to an ext3 file system and don&#8217;t need the capability to mount it both under Linux and Windows. If you do, make sure to try - nay, use! - Truecrypt. It&#8217;s very very nice.</p>

<p>So, the 200GB disk ended up being partitioned like so:</p>

<pre>
$sudo fdisk -l /dev/sda

Disk /dev/sda: 200.0 GB, 200049647616 bytes
255 heads, 63 sectors/track, 24321 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Disk identifier: 0x000cbcfd

   Device Boot      Start         End      Blocks   Id  System
/dev/sda1   *           1        3647    29294496   83  Linux
/dev/sda2            3648        7294    29294527+  83  Linux
/dev/sda3            7295       23707   131837422+  83  Linux
/dev/sda4           23708       24321     4931955   82  Linux swap
</pre>


<p>That is, 30GB for root, 30GB to be encrypted, 135GB for data and the rest for swap.</p>

<p>Of course, with Hardy you can <a href="http://learninginlinux.wordpress.com/2008/04/23/installing-ubuntu-804-with-full-disk-encryption/">encrypt the root file system</a> just by selecting to do so in the alternate installer, but I don&#8217;t feel a need to go that way right now - maybe later.</p>

<h3>Backups</h3>

<p>Now, slowly approaching the main topic of this post, while playing around with the new disk and the old data I was thinking about putting in place a new backup strategy. At the same time (I can do anything while simultaneously going through my subscriptions in Google Reader:) I happened upon the <a href="http://jwz.livejournal.com/801607.html">JWZ post about backups</a>. JWZ, who obviously is a smart guy, is onto something. I&#8217;m already doing backups (of part of my data) using <code>rsync</code> to my server at home - not full disk image, admittedly, which was JWZ&#8217;s prescription. However, I wanted to try something different and achieve a few other things:</p>

<ul>
    <li>Retain multiple snapshots of data at a time</li>
    <li>Compress the data</li>
    <li>Encrypt the data</li>
</ul>


<p>For a while I was considering ZFS (which I in a moment of temporary megalomania started porting to a native Linux kernel module, strictly for private use! - maybe something for another post) with its nice snapshot and compression support, but this idea was quickly discarded for being a bit too unnatural for most Linux setups. I added the additional requirement that the solution should work without having too many non-standard dependencies.</p>

<p><a href="http://bisqwit.iki.fi/source/cromfs.html">CromFS</a> has a nice feature set, but it&#8217;s a FUSE file system and it&#8217;s not available in Hardy. The comparison chart on the CromFS page however led me to <a href="http://squashfs.sourceforge.net/">SquashFS</a>. SquashFS is available out-of-the-box in Hardy and by <code>apt-get</code>ting the<code>squashfs-tools</code> package, everything needed is installed. The nice <a href="http://tldp.org/HOWTO/SquashFS-HOWTO/">HowTo</a> gives a good introduction to the commands required to use it. Note - SquashFS, as most compressed file systems, is read-only. This suites me perfectly as I want to make a snapshot for backup purposes, but it might not be what you want.</p>

<p>The idea I got was to use SquashFS as the compressed snapshot file system and wrap it in LUKS for encryption. By doing this I get a single compressed file which I can mount on a modern Linux distribution to access the data. It&#8217;s securely and (somewhat) efficiently stored.</p>

<p>Luckily, what I wanted to do is very similar to what the <a href="http://gentoo-wiki.com/HOWTO_Burn_Encrypted_Optical_Media_With_Luks">Gentoo guide for how to burn and encrypted CD image</a> describes - namely wrapping an already existing file system image in a LUKS encrypted container. Most of the following is based on the Gentoo guide.</p>

<p>There are a few steps to the process:</p>

<ol>
    <li>Create SquashFS image from source data</li>
    <li>Create LUKS container</li>
    <li>Put SquashFS image inside LUKS container</li>
</ol>


<p>The trickiest (which isn&#8217;t really that tricky) part is figuring out how large to make the LUKS container. As we don&#8217;t know beforehand how large the SquashFS image is, we need to create it and then calculate how large the LUKS container should be.</p>

<h3>Step 1: SquashFS</h3>

<p>Let&#8217;s start with creating the SquashFS image:</p>

<div>
  <pre><code class='sh'>$sudo mksquashfs /crypt /tmp/cryptbackup.sqsh -e /crypt/stuff
Parallel mksquashfs: Using 2 processors
Creating little endian 3.1 filesystem on /tmp/cryptbackup.sqsh, block size 131072.
[==========================================================================] 2297/2297 100%
Exportable Little endian filesystem, data block size 131072, compressed data, compressed metadata, compressed fragments, duplicates are removed
Filesystem size 13606.69 Kbytes (13.29 Mbytes)
        21.57% of uncompressed filesystem size (63077.89 Kbytes)
Inode table size 38419 bytes (37.52 Kbytes)
        32.62% of uncompressed inode table size (117780 bytes)
Directory table size 33629 bytes (32.84 Kbytes)
        58.10% of uncompressed directory table size (57880 bytes)
Number of duplicate files found 115
Number of inodes 3176
Number of files 1877
Number of fragments 45
Number of symbolic links  945
Number of device nodes 0
Number of fifo nodes 0
Number of socket nodes 0
Number of directories 354
Number of uids 5
        ....
Number of gids 12
        ....</code></pre>
</div>


<p>This creates a new compressed SquashFS image from the data in the <code>/crypt</code> directory (the contents of this directory becomes the contents of the image root). The <code>-e</code> flag excludes all files in the given directories - here, everything in <code>/crypt/stuff</code>. Note that it might be more efficient to store this image on a separate disk, if available. Even an external USB 2.0 mounted disk might be faster to write to while reading the data from the main disk.</p>

<p>The SquashFS image was compressed by about 50% in my case - 10GB of data stored in a 5GB image. Of course, the compression ratio achieved depends on the type data stored.</p>

<h3>Step 2: LUKS Container</h3>

<p>Step 1 done, we now need to create a LUKS container to store the SquashFS image in. How big should it be? Well&#8230; The Gentoo guide linked to above calculates the size of the LUKS overhead by checking the difference between a LUKS container and the mapped block device. It turns out that this overhead is 1032 blocks (each block being 512 bytes), no matter what the block size is. Googling this seems to confirm it, so for now I&#8217;m assuming that LUKS always adds 1032 blocks of overhead.</p>

<p>The size in 512 byte blocks of the SquashFS image can be found by doing:</p>

<div>
  <pre><code class='sh'>$ls -l --block-size=512 /tmp/cryptbackup.sqsh
-rwx------ 1 root root 27216 2008-05-11 20:55 /data/cryptbackup.sqsh</code></pre>
</div>


<p>Which in the above case indicates that the file is 27216 512 byte blocks large (this is a test file&#8230;).</p>

<p>Adding 1032 blocks gives us the size needed for the LUKS container - 28248 blocks - let&#8217;s create it (while letting the shell handle the calculation for us):</p>

<div>
  <pre><code class='sh'>$sudo dd if=/dev/zero of=/tmp/cryptbackupluks.img bs=512 count=1 seek=$((27216+1032))</code></pre>
</div>


<p>Note that this creates a sparse file on most modern file systems, so it&#8217;s quite quick. We don&#8217;t need to fill it with random numbers or anything as the whole container will be updated when we write the SquashFS image to it.</p>

<p>Now, let&#8217;s map it. First locate an available loop device:</p>

<div>
  <pre><code class='sh'>$sudo losetup -f
/dev/loop0</code></pre>
</div>


<p><code>loop0</code> is available - no loops on this system.</p>

<p>Set up the container file as a loop device:</p>

<div>
  <pre><code class='sh'>$sudo losetup /dev/loop0 /tmp/cryptbackupluks.img</code></pre>
</div>


<p>Then make it a LUKS volume:</p>

<div>
  <pre><code class='sh'>$sudo cryptsetup luksFormat /dev/loop0

WARNING!
========
This will overwrite data on /dev/loop0 irrevocably.

Are you sure? (Type uppercase yes): YES
Enter LUKS passphrase:
Verify passphrase:
Command successful.</code></pre>
</div>


<p>Make sure you remember the password&#8230; ;P</p>

<p>And open the device:</p>

<div>
  <pre><code class='sh'>$sudo cryptsetup luksOpen /dev/loop0 cryptbackup
Enter LUKS passphrase:
key slot 0 unlocked.
Command successful.</code></pre>
</div>


<p>Now the device is available as <code>/dev/mapper/cryptbackup</code>, ready to accept our SquashFS image.</p>

<h3>Step 3: Put SquashFS Image into LUKS Container</h3>

<p>Let&#8217;s validate the overhead of LUKS:</p>

<div>
  <pre><code class='sh'>$echo $((`sudo blockdev --getsize /dev/loop0`-`sudo blockdev --getsize /dev/mapper/cryptbackup`))
1032</code></pre>
</div>


<p>Sweet! So, the size of the mapped device should be the same as our SquashFS image:</p>

<div>
  <pre><code class='sh'>$sudo blockdev --getsize /dev/mapper/cryptbackup
27217</code></pre>
</div>


<p>Hmmm&#8230; Close enough&#8230; ;P Perhaps there is some rounding to a full KB or something like that going on. Anywho, at least it is big enough for our 27216 block image. Let&#8217;s transfer it:</p>

<div>
  <pre><code class='sh'>$sudo dd if=/tmp/cryptbackup.sqsh of=/dev/mapper/cryptbackup bs=512
27216+0 records in
27216+0 records out
13934592 bytes (14 MB) copied, 0.0544451 s, 256 MB/s</code></pre>
</div>


<p>Done and done. To verify that it works we can mount the file system:</p>

<div>
  <pre><code class='sh'>$sudo mkdir /mnt/cryptbackup
$sudo mount /dev/mapper/cryptbackup /mnt/cryptbackup</code></pre>
</div>


<p>If all went well, <code>ls /mnt/cryptbackup</code> should now give the contents of the original directory.</p>

<p>To unmount, do:</p>

<div>
  <pre><code class='sh'>$sudo umount /mnt/cryptbackup
$sudo cryptsetup luksClose cryptbackup
$sudo losetup -d /dev/loop0</code></pre>
</div>


<p>Now remove the old SquashFS image <code>/tmp/cryptbackup.sqsh</code> and store the LUKS container <code>/tmp/cryptbackupluks.img</code> in a safe location. I use a portable external hard disk and the server at home to save the backup images. To mount later, just run a few of the, slightly modified, above commands again:</p>

<div>
  <pre><code class='sh'>$LOOP=`sudo losetup -s -f /tmp/cryptbackupluks.img`
$sudo cryptsetup luksOpen $LOOP cryptbackup
Enter LUKS passphrase:
key slot 0 unlocked.
Command successful.
$sudo mount /dev/mapper/cryptbackup /mnt/cryptbackup</code></pre>
</div>


<p>Now, all that remains is to create some helper scripts to avoid having to write all this every time I want to make a backup&#8230;</p>

<p>A drawback of this method is that it takes quite a while to perform the backups. It&#8217;s not incremental either, so the backups will presumably take longer and longer to make each time (as more data is accumulated). Next thing might be to try to create a base image with SquashFS and then do incremental backups with UnionFS or something&#8230; Hmmm&#8230;&#8230;</p>

<p>/M</p>
]]></content>
  </entry>
  
</feed>
