Tuesday, 18 July 2023

Ubuntu 22.04 on older devices with no, or bad UEFI

 Recently I had to install Ubuntu 22.04 server onto 3 laptops, which did not have any support for UEFI, or the UEFI support was broken. 


It was indicated when, after successful ubuntu install, the first boot, fails with no disk found. 


* BootDevice not found 

etc. 

the fix is simple enough. 

1. disable the UEFI support in the BIOS

2. Beging the ubuntu (booting off the USB stick) install

    but when you get to the first menu, choosing the keyboard layout, switch to a new console (ALT f2) and prepare the disk manually. 

This will vary for some devices (which is the boot disk, partitiion layout etc) but the basics are

sudo fdisk /dev/sda

# change the partition type to DOS (m for menu, look at the bottom)

# delete any old partitions

# create a new primary partition  (2G in size for /boot)

# create a second parition (remainder) for /

# set partition one to be bootable ('a')

# write the changes.

 

3. now go back to console 1 (alt F1) and when you get to disk choice, 

choose custom and select, and allocation the new parittions you created as 

primary 1 - /boot

primary 2 - /

and then proceed. The installer will do the right thing and it will boot.

 


Wednesday, 16 April 2014

SBT not ready for the Corporate World

I have been using SBT now for about two years and I really like it's features. I very much grok it.

It is definitely growing up, in terms of new features and stability. However, of course there is an however, "I can't give this to my friends".

It is just not ready for the corporate world. The likes of Gradle, and yes even Maven make it so much easier to explain the build process. Actually, I can explain the build process with gradle and maven. But SBT is SUCH a massive barrier. We really can do better folks.!

I think I can base my gripes down to two areas: Syntax, and then a higher level, the complexity of creating a build setup.

Syntax
In short, SBT has confusing and ugly syntax. (shocking really) Watching Martin Odersky's key note at the Scala 2013 days, he discussed the notion that we should be very careful with Symbolic vs alphabetic Method names.

http://parleys.com/play/51c1994ae4b0d38b54f4621b/chapter35/about (see from 59:10)

Here Martin discusses Alphabetic vs Symbolic method names. Can we have some normal reading config please ? Looked at a gradle build file lately ? I can explain that to a junior developer of 3 months very easy - but sbt. not a chance (I have tried). It just represents - "forget it - what do you know about node.js ?"

Build and Customisation Complexity

What Ruby on Rails and Maven and (some other stuff I am sure) have in common is the Convention over Configuration. Gradle does this well, where to extend a plugins execution, just define "more stuff for it to do".

The way settings are applied in  a .scala definition is almost appalling. It really needs a rethink as when I show people the various methods, you get blank stares or squizzed up faces.

With SBT, I find I have to write some very complex logic if I want to move files, or process config files etc etc. I feel this comes from SBT lacking a "customer API". It has an Engineers API at the moment but ease of extending it's activities really requires some serious depth knowledge of Scala AND SBT.

My issue

SBT is shaped as the defacto build too for Scala; yes Maven and Gradle can do it. But SBT does it better. Because it is defacto, and because we want new users to learn the languages, and because we want the new users to have good projects (for longevity of maintenance) we want them to use a build tool. But our option .. sticking them in front of SBT ?? oh dear.

Scala is a fantastic language, simply my favourite and I know a LOT of languages and environments. Ant was a brilliant help, and Maven improved that massively (yes yes, ant v maven). So when I train new users (ok / so so developers) in a project, I don't want to confuse them with "take up", I just want to get them on the road to exploring. Training Java, it might be Spring, or Drools or JAX-RS or something else. With Maven (and now with Gradle as that is my preferred Java build tool) I can simply setup a build script, easily (and I mean easy), explain the script to someone, and get them on their way.

The new-ish developer does not need to know much about Java to understand Maven and even less knowledge to understand Gradle as it reads better.

But if I wanted to get someone up and running with Scala, giving them a default Build tool, I can show them an SBT build setup. Oops. that doesn't work.

Parallel this poor experience with how Scala compares to Java, I can show them a case class and how simple that is, so at the high level, Scala as a language is easy, but SBT is just killing take up for the less experienced.

I have read that sbt is like vi, once you grok it, you get it.. and yes I am definitely there. (vi is my favourite editor) - but please can we work on a new build definition language - and I really mean something that it's GOAL is user friendliness, to overlay on top of the vi-ness ?

If we get that right, because SBT is a defacto build tool, we might get even more developers!

Is there something in the works that will help SBT be a tool for the masses ? Because at the moment you need a degree and a year on Scala to understand how to do more complex things (and sometimes something basic).

Every so often I do consider switching a project to Gradle but, of course, SBT just does work better with Scala and I like it, but I can't share a build setup with a new junior developer. I have tried and it just confuses to the point on non-productiveness

So I have an itch, I may scratch it.. .. but I haven't yet

There, I can have a coffee now.

<rant-off/>

Saturday, 15 March 2014

akka-persistence and DDD

I have been working for some years now on a few projects. In many respects just code to exercise the brain.

About 3 years back I picked up event sourcing from a Scala Days conference and I am sold. now more than ever.

So I have released the core components of my scala - akka-persistence - DDD (CQRS-esq) implementation over on github for all to peruse.

In the coming weeks I will add a "Petstore" ala, sample application to the implementation (and it will be a case of eat your own dog food).

https://github.com/rbuckland/io-straight-fw

This ties together the very odd Uuid generator I blogged about about a year a go and Event Sourcing of objects.

I am using AngularJS as my front library which works really well because with spray.io and the Jackson Marshalling, I get the Scala Case classess coming back to the browser as JSON with next to no effort at all.

And because it is all in memory, the speed is just blindingly quick! Very very impressed.

Thanks have to go to
- Martin Krasser for eventsourced - and akka-persistence (it's successor)
- Mathias Doentiz and the spray.io team
- All the Typesafe Akka guys. Seriously brilliant stuff
- The whole AngularJS team - job really well done.
- Jackson JSON Marshalling. Truely the best JSON marshaller there is.
(is that it ? ) .. for now yep.


Monday, 4 November 2013

Ramon's Rough Guide to Akka - Top Tips 1

Ramon's Rough Guide to Akka - Top Tips 1

And someone please tell me if the tips are wrong :-)

Over the past 2 years in my spare down time, I have been using Akka for the core of my application. There is so much to grok, but it is also very simple.

This will be a really short post, of things which I wish I had read somewhere, before diving into Akka.

1. Don't pass ActorRef's around :-)

The ActorRef (as I read tonight) is a handle to a specific instance of an Actor. So when that Actor dies an another takes it's place (or in my case during event sourcing replay) - The ActorRef will become stale.

Instead, get the ActorRef (or an ActorSelection) from

   system.actorSelection("name")
   context.actorSelection("/orPath/name")

(and I uncovered this due to the deprecation of actorFor).
This will give you the Actor you need.

I guess I passed the ActorRef in to places because I am not using any DI (like I used to always with Spring). So instead .. now system or the context can be always used.


2. Read this new Post of Actor paths and Actor addressing!

This explains (1) better than I can.

http://doc.akka.io/docs/akka/snapshot/general/addressing.html

That's it for today.

Friday, 11 October 2013

Embedding a Primary Key in a UUID / GUID for CQRS / ES

For some time now I have been working on an Event Sourced system. Today I am going to describe my UUID/GUID primary key approach that I devised. Ignoring much about the event sourced technology and the merits thereof; primary key's are common and critical and their usage in an Event Sourced system is very critical.

The usual route for a primary key in a system is an increasing number (Person ID = 102).

With Event Sourcing and CQRS, the UUID or GUID is often identified as a good implementation choice for your primary key

If you are interested in the topic, then these two resources are a good read. (nothing to do with Event Sourcing)

But I have a few issues with the UUID. For one, it's not very client friendly, nor is it easily memorable. I want a system wide unique reference for all my objects ; a UUID is great for that; and I want it to also function as a friendly and memorable primary key.. how ? Well here below is my solution.

A little about Event Sourcing

With event sourcing, the primary route to storage is not through the "Domain Object".

Most developers are familiar with an Object-Relational Mapping system (Hibernate, NHibernate etc). (Object persisted to a table). This usual approach is that a Domain object is persisted (from a class or class heirarchy structure) to a database table. Event Sourcing instead stores the "event" that creates or modifies the Domain Object, and not the Object itself. A rebuild or some other query is a replay of the Events stream that was persisted.

I explain all that to say that an Event Sourced (CQRS) system can be designed without "tradtional primary keys".

Each event has a key, and the objects created can have keys, but what is common is to use UUIDs across all domain objects.

My Design Goal

I wanted some traditional primary keys; and I wanted the UUID. In short, the system should be simple to use; being both client friendly and a memorable primary key for use.

When you have a UUID as the primary key and it is used in API's and get's passed around the office as "Look up client 3422" you need this API to be simple.

An example: /person/fbe645f0-3031-41e3-aa6e-0800200c9a66 is just not a nice URI

However,

/person/2078

or

/person/5f9

They are simple.

What I have embarked on is to segment my UUID (my primary keys) so that I utilise the entire UUID space - a part for randomness, a part for the Group (or table ID if you like) and a part for the object; in this example case, the person.

The make up of my Custom UUID

The UUID is a 128 bit number, represented as 32 hex characters (with some dashes for legibility)

The UUID specification reserves some bits for version and variant.

With much (actually 30 minutes) thought, I have decided to use Version 6. (it doesn't exist in the IETF RFC 4122, they just went 1, 2, 3, 4 and 5)

and just make the Variant 'a'.

but ignoring all that, what is special about my UUID is that I embed a primary key and a "group" ID into the UUID.

So, my UUID's look like

pppppppp-pppp-6ggg-arrr-rrrrrrrrrrrr

where p is the Primary key (sequential incremementing)

where 6 is the Version (always 6)

where g is the Group ID, (akin to an identifier of the table)

where a is the variant (always a)

where r is the random part

This is my working notes: 

00000000-0000-6000-a000-000000000000
                    -----------------
                    60 bits Random bits (time or other)
                   -
                   x == a, b, 8 or 9
               ---
               group ID - of 12 bits value is (0 to 4095)
              
              6 == always 6 - (Version 4, Random UUID)
-------- ----
Primary key ID of 48 bits  (max 281,474,976,710,656)

So I have enough bits for a primary ID (halfway between Int *32 bits and Long *64 bits)

The Version

I decided to use 6 as the Version, 1 - 3 are other uses, 4 is Random or Psuedo random, which is almost mine, but not quite and Version 5 is a SHA-1 Hash; the RFC 4122 stipulates the following

Process of identifier assignment:

Generating a UUID does not require that a registration authority
be contacted. One algorithm requires a unique value over space
for each generator. This value is typically an IEEE 802 MAC
address, usually already available on network-connected hosts.
The address can be assigned from an address block obtained from
the IEEE registration authority. If no such address is available,
or privacy concerns make its use undesirable, Section 4.5
specifies two alternatives. Another approach is to use version 3
or version 4 UUIDs as defined below.

The sentence I want to draw attention to is - "Generating a UUID does not require that a registration authority be contacted"

But then again, because I am using Version 6, it's probably not a UUID.

My reasoning to a Version 6 are:

  • My UUID is not a Version 4, because it is only partially random ( a part of it )
  • It is not any other Version (1-3, or 5)
  • Version 6 wasn't used
  • If someone has an issue with my use, then I'll call it instead a LUUID, a Local UUID

Moving on.

The Group ID

I wanted to have a unique key that represents all objects across the space. In this way I can now have a REST URI that looks like

/any/<uuid>

and the system can appropriately redirect to the correct resource, by looking at the group ID. (pattern matching the -6xxx- )

For example, if we have the UUID

000000231-22e-6aa1-a789-28ef27ab7c62

This is

  • aa1 for the Group ID for 'person'
  • 23122e for the primary key

/any/000000231-22e-6aa1-a789-28ef27ab7c62

and with a match we can redirect the request to

/person/000000231-22e-6aa1-a789-28ef27ab7c62

Clashes in the Primary Key with a Distributed System

CQRS guru Greg Young says of the UUID (and Event Sourced systems)

Having the client originate Ids normally in the form of UUIDs is extremely valuable in distributed systems.

And this is true, but I don't want to give the client that honour, I want to allocate them a UUID (for many reasons) - but that comes with a drawback of needing to cater for clashes. (there is always a tradeoff with IT)

For my UUIDs, the primary key is sequential, at point of allocation. (231-22e, 231-22f, 231-230 etc). Having the end of the "UUID" random (e.g.: -a789-28ef27ab7c62)means I can cluster (multiple systems) and allow for "duplicates" even in the primary key space, (where two servers generate the same ID and Group ID).

Leaving the UUID as it is (with a duplicate in the PK ID space) is ok but not ideal. So we will need to cater for that. (and of course for the lottery day when two systems generate the same UUID even down to the random part!)

Let me explain that : Assume that I have a web application with two servers that generate "people",

   www.myco.com  

  • server1-myco; and
  • server2-myco
 
If server1-repo and server2-repo BOTH generate a UUID but the random part differs, e.g.
 
server1 - 000000231-a32-6aa1-a789-28ef27ab7c62   (Jim)
server2 - 000000231-a32-6aa1-a25e-6ac5c6ef127c   (Mary)

then, technically I have two unique ID's, but the initial shorter ID's clash. This is not exactly ideal - because I want my friendly PK ID's to be unique also. If I want to minimise that "duplicate", then here are some options.

  1. Single ID generation node (creates a single point of failure)
  2. Regular re-assignment in case of a clash
  3. Generate and check with peers
  4. Block reserving

Options 2, 3 and 4 will be my preferred. With a distributed system, I have that PK ID issue anyways, so it's not different because I am playing with UUID's.

But what I really like is how I can use the primary key all by itself, outside of the /UUID

for example. 


Dear Mr Client,

Welcome as a supplier to Company X. For future reference, your client ID is 23122e.

...


or

/person/23122e

I don't have to use the full UUID everywhere, but rather just where I need it (in the event sourced messages), and as a unique global ID on the system.

Debugging a system will be easier too, looking at logs, someone with a little knowledge will recognise 'people' UUID's vs 'building', or 'schedule' UUID's (because they will distinguish the group ID after '-6xxx-' as the unique group identifier); in effect people will learn those 3 characters and identify what the group Id is.

UUID generation

So now I hear you wonder, how do I generate these mythical UUID's ?

Simply really.

This is the call for the generating the UUID (reusing the java.util.UUID class, just giving two lower and upper longs (64 bits each)

  /**

   * Create a new UUID given some ID as the groupID and an already sequenced ID

   */

  def createUuid(groupId: Int, id: Long): Uuid = {

 

    val randomBytes = new Array[Byte](8)

    secureRandom.nextBytes(randomBytes)

    val randomLong = java.nio.ByteBuffer.wrap(randomBytes).getLong()

 

    // groupID has to be 12bits as the 4L is going in over the top.

    return Uuid(new java.util.UUID(groupId | (6L << 12) | (id << 16), (10L << 60) | (randomLong >>> 4)).toString())

 

  }

 

The Primary Key is an incremental sequence on the code that creates a new person, or group, or employee (etc)

In Scala, it is simply a matter of adding in a Trait for the "class" you want ID's sequenced for/ UUID's generated for. e.g:  I add with UuidGenerator[Person] and this gives a newUuid() method 

class PersonProcessor(val repository: Repository[Uuid, Person]) extends AbstractProcessor[Person]

with UuidGenerator[Person] 

{ this: Emitter =>

  

  def klass = classOf[Person]

 

...

      createPerson(newUuid, cmd )

 

The implementation of that newUuid() method looks as follows:


trait UuidGenerator[D] {

  

  implicit def klass: Class[_]

  

  private val ids = Map.empty[String, Long]

  

  private[this]def className = klass.getClass().getCanonicalName()

 

  /**

   * return the next ID

   */

  def newUuid:Uuid = {

    val idKey = className

    val currentId = ids.getOrElseUpdate(idKey, 0L)

    ids += (idKey -> (currentId + 1))

    return Uuid.createUuid(klass, currentId + 1)

  }

...


And Uuid.createUuid looks like : 


 

  def createUuid(klass: Class[_], id: Long): Uuid = createUuid(groupId(klass), id)

 

The Group ID is simply CRC-12, or 12 bit CRC over the classname. This is because I had 12 bits to spare where I placed the groupId -6aa1 So given that all 'Person' domain objects extend from com.soqqo.system.domain.Person my groupId's are consistent there.

 

On bootstrapping my system, I make sure that all "in use" groupId's are not clashing on CRC12-ing them - could happen - and if it does I'll deal with that then. (just System.halt bootstrap .. and change code to suit)

 

This is the crc12 implementation in Scala. I haven't tested that brutally, but it DOES generate unique < 4096 ID's for random byte's passed in, so it is working the way I need it to.

  def crc12(toHash: String) = {

 

    /**

     * ************************************************************************

     *  Using direct calculation

     * ************************************************************************

     */

 

    varcrc:Int = 0xFFF; // initial contents of LFBSR

    varpoly: Int = 0xF01; // reverse polynomial

    var bytes = toHash.getBytes()

 

    for (b: Byte <- bytes) {

      var temp = (crc ^ b) & 0xff;

 

      // read 8 bits one at a time

      for (i <- 0 to 7) {

        if ((temp & 1) == 1) temp = (temp >>> 1) ^ poly;

        else temp = (temp >>> 1);

      }

      crc = (crc >>> 8) ^ temp;

    }

 

    // flip bits

    crc = crc ^ 0xfff;

 

    crc;

 

  }

 

Summary

I hope this helps someone on any of the weird topics I have covered here. I will share the Uuid and UuidGenerator classes happily for anyone that wants them. They are anything special, but rather a lot of thinking about how I wanted my Uuid's to be utilised in the system.

My system entails:

1. spray.io - Web router on top of Spray Can
2. Event Sourced (now also known as akka-persistence)
3. AngularJS

Enjoy!

Tuesday, 2 July 2013

Heroku and Gradle - and jetty-runner Configuration

I recently worked on a project where we used Heroku as the deploment engine.

For speed of the project I chose Maven (simply because I know it well and it is VERY good).

Knowing also that Gradle is now becoming the "next build kid" on the block and, for me, recognising that Gradle is easier to configure, I set about the task today of switching the build to Gradle.

This was very simple, and the last "part of the puzzle" after replicating all the functionality was to setup the Heroku parts. By default, we were using the Maven (jetty-runner) boot strapping. Arguably it is easier and lighter to run Jetty Embedded (as per https://github.com/heroku/devcenter-gradle) but I wanted to see what is required to use "jetty-runner"). This was more an excercise in build comparison, that it was "get it onto Heroku".

Heroku will detect a Maven pom.xml, and by default will run

This creates a war. Heroku then runs your app using "whatever" is in the Procfile. The Procfile they suggest looks like this:

The jetty-runner.jar gets in the "target/dependency/" folder due to this Maven Magic.

When Heroku detects a Gradle project, it runs

instead of "gradle package".

So to replicate the same with Gradle I had to write a copy task to get jetty-runner in there, and generate the war and attach that all to a "stage" task.

It is very easy when you look at it, the trick is in the knowing of the API that slows it down. But I resolved it in about 30 minutes.

In short, the changes for Gradle are as follows.

1. Change your Procfile (we will get the jetty-runner.jar in "build/libs") (the war goes there by default)

2. Add a "new" configurations for the depenency of jetty-runner

3. Add a new dependency for Jetty Runner (note I also use newrelic so it goes in there too!)

4. Create a new task which copies the jars from the dependencies "runtimeOnly" We also replicate the Maven method of renaming the jar to have no Version(s).

5. Add a "stage" task, because that is what Heroku will run.

And that is it. When stage is run, it will create a war, and copy jetty-runner.jar into the build/libs folder.

Happy days.

Wednesday, 29 May 2013

The hierarchy of the type X is inconsistent - A Classpath Issue

Often the simple things will slow you down when developing.
Today I had one such moment. It occurred a few days back where my Eclipse project was reporting the following error:

The hierarchy of the type LoggingFilter is inconsistent

The LoggingFilter was simply a class extending the Spring AbstractRequestLoggingFilter



Nothing really special was going on. I was kind of hoping it would be obvious but it wasn't.

In short, my classpath was wrong where I had an import that did not (was older perhaps) match to a library that, somewhere in the stack, AbstractRequestLoggingFilter was depending on.

I frequently used mvn dependency:tree to assess what this list was .. and nothing stood out. I checked the javax.servlet-api (yes I was using 3.0.1, and so was Spring). I checked my exclusion of commons logging (I use SLF4J), but that was okay.

Eventually I looked inside the .classpath and to my mild horror I saw Spring 3.0.6 was included.
Looking back at the dependency:tree for Maven, it didn't show in the list.

Which meant one of two things:
1. mvn dependency:tree was wrong
2. mvn eclipse:eclipse was wrong

I looked first at dependency:tree, and then figured that perhaps Maven needed an update (I was using 3.0.4) and that took me to check release notes, of which I found : https://cwiki.apache.org/MAVEN/maven-3x-compatibility-notes.html#Maven3.xCompatibilityNotes-DependencyResolution

and a magic note that , dependency:tree does not work according to maven's resolution.
So no worries, I ran debug and I saw that .. yes Maven was "seeing" 3.0.6 but it was also excluding it.
So that meant that eclipse:eclipse was wrong.. a quick pom change and (2.9 eclipse plugin) and it was all good.

mvn eclipse:eclipse excluded 3.0.6 as expected and included 3.2.3 as needed.

Jetty however is still bootstrapping with 3.0.6 .. so I may have to specifically find which of the depenedencies is trying to include it, exclude it and then forcibly include spring-context.. rather than rely on the transitive.

Moral to the post .. check everything .. and assume nothing! 

Friday, 8 March 2013

Scala - Event Sourcing and Spray

Scala + NoSQL

Over the past 24 months I have been diving a bit deeper into Scala by way of using a new architecture. My dabbling started 4 years ago. I haven't touched Java for about 2.

I have been sick of, over the past 10 years, building the typical DB/App stack. If you track back about 5-6 years in my posts you'll notice I shifted to researching and investigating NoSQL enterprises. (db4o etc). The "ick" centred around the simple yet fundamental issue of the ORM Impedance Mismatch. Every man and dog has blogged and written about it and it is very prevalent.

One thing led to another and I found myself loving Scala and it's fresh way of code development. But never really landed on a great NoSQL solution. Being a Java hack I immersed myself in its ways (Scala that is) and attended ScalaDays 2012 to sure up my skills; There I met and chatted with a lot of people and found the 3 days brilliant.

At Scaladays I was researching my next "stack" and honed in on spray.io. After the talk Matthias Doenitz gave at ScalaDays, I caught up with him in the hallways asking a general question of

"I am an old GWT hack and want less complexity; what interfaces do you see being plugged into Spray,.."

to which he and a friend gave some tips to various JS libraries for me to check out (of which I have settled on Twitter Bootstrap). Matthias and / or the other (I don't recall who) made reference, if I wanted to walk on a new area, to check out the work in the Event Sourcing arena.

I read and could see it's benefits. So I figured I would read some more. I ended up watching the threads on the DDD/CQRS. That got me hooked - I have to say though that the CQRS is a simple yet massive theory and I wanted some good practical; it was to come.

About the same time, Martin Krasser posted some info on JAXB Scala Marshalling - I wanted some of that in my Spray application. Scala has excellent JSON marshalling using lift-json; alternatively you can use a built in library spray-json. Both of these worked well, however I wanted a "single" API definition class that I could expose as JSON or XML without me needing to code it twice. My sample application at the time was still bound to a Scala/Spring JPA and Hypersonic DB stack. 

Seeing the "sample" project that Martin Krasser had built, and his excellent blog posts on it, took me right into the eventsourced package where the JAXB marshalling was used. Martin Krasser together with colleagues released the early draft of this Event Sourcing package and after a few iterations it was fully embedded into the Akka way .. and since Spray was too, I have joined the two together ever so simply - and now have the base framework for my perfect "stack".

The Scala ES Spray Stack

So what does it look like ? At the front end, though I have some ways to go there, I have
  • Twitter - Bootstrap, which talks to a
  • JSON REST API; into
  • spray.io routing; which delegates the "commands"; to
  • eventsourced
The commands and the events that are journaled are Scala Case Classes, Annotated with JAXB annotations to support the Un/Marshalling in spray.

Akka Camel will come next, though because I am an old Apache Camel Hack - random contributions and use throughout time, I know what it does and well, so will slot it in later.

A Weak Schema on Historic Events

Event sourcing is great - in essence - keep everything you ever did. Everything. It is very BigData-esq, and actually beneficial for audit tracking. If I keep every Command/Event that the system responds and reacts with. I have a full "audit" trail of how it operates. CQRS gives me a benefit of no Database (can stick one on the "read" view if I want). However;

My last "piece" to the framework puzzle is the concept of supporting a weak schema. After you read all about Event Sourcing, you will quickly realise that "Cross Version" software support needs to be managed well. The typical "DB" stack doesn't have this challenge as much, simply because, unless coded for, all history is "thrown" away - and thus the problem is smaller - and DB upgrade scripts decide at "run" what is kept .. or what goes.. and the "change is usually irrevocable".

With Event Sourcing, the "history" is with you, and that is it's benefit. So to retain that benefit through future upgrades of your application, you need to support the older events, in what ever form they have. A few ways to achieve this are:

1. Retain, in code, the "V1, V2 and V3" objects that the event messages relate to;

Needless to say, this is quite complex. The amount of code you may have to manage over a long life span of the software could become messy. * discounted *

2. Upgrade the older Events, when you "upgrade" the Application.

This may work - but it feels wrong. Upgrading events to something they never were breaks the model. Adding a field to an event .. what should be the default of the value that was never supplied 4 years ago ? Needless to say, you will recognise this is often the DB way. That is okay. It does work.. there is another way. * discounted *

3. Translate the older events on the fly as they are read in..

My idea was to build a shim in the "serialisation layer" that translates older events V1, V2 up to V3 equivalent .. but again it kind of smells.. so that is not it. * discounted * .. kind of..  

4. A Weak Schema.. 

Greg Young, on the eventsourced mailing list pointed me (in two words .. "Weak Schema") to  look at this model .. quickly I ended looking at Google's protobuf. I had read it before but had not the need, until now.

Protobuf is all about "version" management across messages between systems. This is exactly what Google built it for. Between their index servers that may be running different versions of software. And as it turns out, it might be a brilliant fit. I have some "tests" to do, which for now I am going to park as the theory seems okay, and when the need warrants I will utilise it's power. 

I googled in earnest about working with a "weak schema" but there was not a lot to read, but it didn't take too long to work it out.

Let me give you an example: 

if we have a "Command" object that we will serialise to disk. It could look like this: 

"CorrectTheBirthDate(uuid,newBirthDate)"

In my fictitious application, imagine we serialise this to JSON. It may look like this.

Now imagine 3 years later we figure it is a good idea to record the "reason" why the Birth date had to change; to support this we add a new field for "reason". Simple enough, our Command object changes to CorrectTheBirthDate(uuid,newBirthDate,reason) and the newer JSON is serialised as you would expect.
Ok. So what happens when the system "replays" all the Commands. Well with protobuf, it just sees that the field is not supplied, so it doesn't deserialise "nothing" into the object. Instead (using ScalaBuff) the case class is marked with "Option[] fields, so that the value in that instance becomes "None".

If it were the other case where a field is dropped; then the Case Class will just never have the value "loaded in".

I am sure there are horrid edge cases lurking, but it feels right to let the serialisation layer deal with the problem .. how it knows .. and so long as the developers know the rules (when things are dropped, or what is added when) then coding can continue. The trick or benefit is that the "protobuf" default should be enough.

Serialising in this way means that regardless of the changes in my API's, Commands and Events. I will always have the History. Therefore I will always have the ability to scour the depths for stats and reports. Exactly my reasons for Event Sourcing it. (amongst so many others).

So, stay tuned. I will post a real sample application once I tidy up the mess and make a real UI to play with.



Monday, 9 April 2012

GWT SDK Not Installed - Eclipse

From time to time, I have seen the simple but annoying message.
GWT SDK Not Installed
the error message is annoying because I "have" it installed, which means, not so much "not installed", but more "not detected" by the Google Eclipse Plugin.

As I am busy working on many things I forgot what the resolution was and again, spent 1/2 an hour resolving the issue.

You may find this error when using Maven and GWT. Essentially, the GWT SDK Library shows up as a Classpath Container. "GWT SDK [2.4.0]" or similar.


The cause is because Eclipse locates the "gwt-*" libraries in your "Referenced Libraries" set, before it sees the actual Eclipse "GWT SDK [...]" reference.

The error message occurs when theses other GWT libraries are in your classpath, in this case the "referenced" libraries section; especially before the GWT one.

There are two fixes for this

1. Move the GWT SDK to the top

Move the GWT SDK "Classpath" Entry Container above your "Libraries" where GWT is found. The Google Eclipse Plugin finds the SDK based GWT Library first and all is well. To move it, manually edit the .classpath file and move the classpathentry line to the top.

2. Exclude the other GWT Libraries from your classpath.

If you are using maven, you'll know that the Maven Eclipse Plugin can't specify the order of classpath references in the .classpath file.

The trick then is to "exclude" the gwt-dev, gwt-user jars from the generated .classpath file, which you can do in the pom.xml. This way, ONLY the GWT libaries in the Eclipse GWT Container are the ones seen by the Google Eclipse Plugin and it all works well. Note also I have the GWT ClasspathContainer for GWT in there, so when I DO regenerate the .classpath and .project files, I don't have to regenerate things.

The example pom.xml is as follows:


I hope that helps you.

Crashplan Active Bandwidth Control #2

In a previous post on crashplan - Crashplan Active Bandwidth Control - I setup a sophisticated "control" mechanism. I have now simplified my approach down to understanding my family patterns and I think it works as a guaranteed performance "setup".

Essentially, between the hours of 23:45 and 06:30, my backup is using ALL the available bandwidth. But I go a little more than that.

Crashplan only has an "on, off" approach regarding times. I wanted a "Fast", "Slow" approach around times. I am using UNIX cron and a script I wrote in the previous version which logs into Crashplan and adjusts the bandwidth.

My /etc/crontab looks like this .. finely tuned over the past 2 months.


So this seems to work real well, I have been able to increase my Backups to now pushing out 90G per week. Pretty good going.

Tuesday, 10 January 2012

Sakis3g Control Script

I have found that my USB Modems, two of them, did not work out of the box with Ubuntu 11.10.
Not to worry, there is a great script that contains all the pieces for Ubuntu.


sakis3g
You can read all about it here - www.sakis3g.org and what it does. In essence, you use it in replace of your Network Manager or ppp/wvdial. Now I would prefer to use the built in method that the distribution has, however it plain does not work! Instead sakis3g and I have work to do.

I wanted a better way to control it, I created a command line control script for it for my modem. (Didn't like the GUI)
#!/bin/sh

BASE_CMD="/usr/local/bin/sakis3g"
OPTIONS="--term"
MODEMETC="OTHER='USBMODEM' USBMODEM='19d2:1003' USBINTERFACE='1' APN='3internet'"
COMMAND="$1"
shift

case $COMMAND in
status)
    $BASE_CMD $OPTIONS status
    ;;
connect)
    sudo $BASE_CMD $OPTIONS $MODEMETC connect 
    ;;
disconnect)
    sudo $BASE_CMD $OPTIONS disconnect 
    ;;
*)
    echo This is a wrapper to Sakis3g
    echo $0 connect
    echo $0 disconnect
    echo $0 status
    exit 1
esac

Thursday, 29 December 2011

Crashplan Active Bandwidth Control


I love what random things I get up to over the holidays. Crashplan is a Cloud backup service that I use for all my backups. I have devised a way so that Crashplan starts backing up at FULL speed, when everyone is not at home, or are not doing anything on the internet. And then drops back down to a trickle backup when things become busy.

Essentially I have one computer, my server, and it has the Crashplan service running on it. The server is an Ubuntu based Linux distrubution. Nothing fancy there. What is interesting is how I have managed to control the Crashplan bandwidth it utilises. In the previous house, I had a good 18-20Mbps internet connection, so my backups were really nice. Now, I only have a 3Mbps connection so the "usage" is very important. If crashplan hogs the connection you reall notice it.

Crashplan has two ways of controlling it's backup usage. First is on a backup set basis, you set the time that it runs. Helpful, for the past 2 months, my backups have been scheduled for 12am to 7am. Works well, but at that rate, I will be completely backed up in about 12 months time... hrmm.

The other way Crashplan operates is by bandwidth limiting. This is how I roll it now.

Attempt 1 - See when they Connect

I needed to determine the best method to "ascertain" if someone was using the internet. I pondered looking at when the phones (we have 4 adults, 3 iPhones and 1 Android) are "on" or can be seen as that is a good indicator that someone is home. But of course it goes a bit more than that.

I did however, to test the theory, write a quick Perl script which was the start of monitoring when an iPhone connects to the WiFi. The Android apparently uses Zeroconf also, but I didn't test that.
Basically, each time the phone connects for the initial session, it sends a multicast out. If you are listening, you will see it. Simply, this perl script listens on the right port.
I quickly discounted this method when I realised that some devices just wont tell me they connected. And because I want to keep my network largely zero configuation, I want to just use DHCP and not have to bother with static entries, or Static leases for my clients. Which is when it hit me:

Attempt 2 - Scan the Known DHCP Range


The premise behind my final solution is simple. I have two types of devices in use in our household.
  • Infrastructure - servers, printer, wirless and network switches / routers
  • Clients - Laptops, phones (soon tablets)

All my infrastructure devices use static IP addresses, such as 1 to 39. All the clients, use a DHCP IP address. We have no desktops in the house, only laptops and when they are closed, they are not in use.

If they are not in the house, they are not in use. Same goes with the phones, they are either sleeping or not in the house.

The Solution

So, if all the laptops are closed and all the phones are out, I know that none of the "clients" will ping, and therefore I can ramp up the Crashplan bandwidth.

Solution to Attempt 2 - Monitor for Active Clients

I had a few things to solve. But for each I knew that Perl would be all that I would need.

Part 1 - Automatically Raise and Lower Crashplan Bandwidth

I needed to determine how Crashplan "stored" it's bandwidth rate. Turns out it is in a config file, but the web site can also change the config. So, the client (my Crashplan service running on my server) and the Crashplan Cloud keep in contact all the time· If I change the bandwidth on the client, it updates on the website, and vice versa.

I fired off a few support queries to Crashplan and they basically said that the config file I found (/usr/local/crashplan/conf/my.service.xml) is not editable by hand. And that the only supported way is via the Client (desktop Java App) or the Website.

Call WWW::Mechanize - I used this module to login to the Crashplan Website and change the bandwidth (kbps) based on my argument. Simple and it looks like this.

Not rabbit proof, but it works for my needs

Part 2 - Monitor for Activity

This was the hardest part, but as always, was solvable. The router (Sky Broadband Provider) I currently use "knows" what clients are using it. VERY handy. So like the Crashplan website solution above, I again use WWW::Mechanize to determine what IP addresses are currently using the router.

I do a filter out of all the ip addresses that do NOT fall inside my DHCP range.

I won't go into the details of using XPath on the HTML from the Router, but, you can see that it is quite succinct. Essentially the IP Addresses appear in a 2nd column in a table. I use an XPath expression to select the right values.

This approach is brittle in as much as, when / if I change my router then I need to code or come up with another way to determine which hosts, within the DHCP range, are currently "in use". I did first to this by just pinging all 60 possible IP addresses; works, brute force, but of course worked :-)

So .. now putting it all together. The script, a perl script, runs from Cron every minute. and performs the following tasks.

  • Get the Current Rate from the Crashplan Config file
  • Get all the current "hosts" that the Router knows
  • Ping each host to MAKE sure they are active
  • If we have an active host (one or more) - we need to go slow
    • If the current rate that Crashplan is running is more than our slow rate, tell Crashplan to slow down
    • If the current rate is slow, do nothing
  • If we have no active hosts - we can go fast
    • If the current rate that Crashplan is running is less than our fast rate, tell Crashplan to go fast
    • If the current rate is fast, do nothing

Simple! And the full Script looks like below. Enjoy!

Of course, I did all this and know and realise that QoS could be used, but my Sky Broadband Router is just not that smart today and I haven't got the devices spare or the time to reconfigure to installl a dd-wrt based router or some such other. So perl scripts it is for now.

Thursday, 27 October 2011

Neo4J - 2nd Look - Setting a Primary Key on Nodes

Primary Key

In my last post I considered the lack of Primary Key like Id's as something I need to solve. My use case is

The application I will be building out will have, after all is said and done a really simple Web Interface with REST type URLs. So .. for example, I will be able to do.
http://myservice.co.uk/superwebapp/mySpecialThing/detailedView/55
The 55 there will result in a query to Neo4J to locate the "MySpecialThing" object with ID of type 55 and display it.

I also considered using a UUID across objects which is also good, but not really what I was after. I want a class of objects to all share an identifier. It has a lot of use. To solve the problem I arrived at the following solution.

Solution Outline

  • All Domain Objects extend fro super type of AbstractLongDomain which has getId()/setId() (Long)
  • An Aspect wrapped around the getId() looks for a null value and if no Id is found. It creates one
  • In the aspect creation of an ID involves talking to a singleton IdManager for a "nextId()"
  • nextId() on the manager looks to it's cache HashMap to see if it has an IdObject that knows what the next Id is
  • IdObject self persists to the repository after each call (** this could be slow.. see how we go)

To the Code

All my Objects extend the AbstractLongDomain The ID Object holds a "per" class Long Id, so each time an ID is needed, one of these objects gives one out. Next we have the IdManager that is managed as a Spring Singleton Bean. Its job is to return an id based on the "class" that needs an Id via getNextId(Class klass). The idRepository you see there is a simple Spring Data Neo4J Repository which has aspect-magic dust sprinkled on it to make the actual implementation.

Because I am not sure if neo4j is the "best" place to store the Id's (though it is the logical) I created a simple idGenerator interface which is simply what the aspect will call and talk to. One implementation (the only) is the Neo4JBackedIdGenerator which uses the id objects and idmanager above.

So first the interface for the IdGenerator

And then the actual Neo4JBackedIdGenerator which is created and managed as a spring bean.

I will have to play with the transactional semantics on this one. I recall a horrid situation which a similar design but via stored procs many moons ago where we had the sproc that generate Id's wrapped in transactions. They needed to be in their own transaction to ensure that mass object thread creation would not get stuck on a lock. (just an area I know can be sticky and bite.. so I put the @Transactional in there and commented out to remind me.

So last, we have the AspectJ which wraps our getId(). All the domain objects extend org.soqqo.luap.model.AbstractLongDomain which means we will get the Id creation and generation for free each time getId is called. (technically a catch here is that setId doesn't get checked if called manually on setting an Id. It could I guess look into the repo to see if the Id is already used.

And finally the Unit Test code to show that it all works

Note the use of @DirtiesContext, because the Neo4J is transactional, after each test the contents are dumped, which means that the idManager which has the HashMap cache becomes stale and it is singleton and has a lifecycle of the test class, not just the method. So the fix is either..manually flush() the cache or use @DirtiesContext which tells spring to re-build the context file. Both work but manually flushing my HashMap (new() ) is 2 seconds faster (0.037s for the test) than spring is at rebuilding.

The 2nd last piece to show is my test context file - model-test-context.xml

The very last piece is what my Maven POM looks like because a lot of people like to see that... Hopefully these are the correct relevant bits. I am happy to provide all this as a ZIP or push it up to github if people want to see more of it.

Current 5 booksmarks @ del.icio.us/pefdus