Two Scala Serialization Examples

In the last two days I’ve been looking into ways to serialize and deserialize some Scala objects. I tested a few suggestions that were mentioned on this post on Stackoverflow. As a reference for myself (and because sometimes it is hard to find good examples) I am adding two examples for Scala Pickling and Twitter Chill. Let’s have a basic SBT project first.

import sbt._
import sbt.Keys._
organization := "me"
name := "scala-ser"
version := "0.1-SNAPSHOT"
scalaVersion := "2.10.4"
resolvers += Resolver.sonatypeRepo("snapshots")
libraryDependencies ++= Seq(
"com.twitter" %% "chill" % "0.3.6",
"org.scalamacros" % "quasiquotes_2.10.4" % "2.0.0-M6",
"org.scala-lang" %% "scala-pickling" % "0.8.0-SNAPSHOT"
)
view raw build.sbt hosted with ❤ by GitHub


Since I work with the Battlefield franchise let’s create some domain classes that we are going to serialize and deserialize.

package me
import java.util.UUID
import scala.util.Random
class WeaponAccessory(
var guid: String,
var slug: Option[String],
var nameSID: Option[String],
var descriptionSID: Option[String],
var categorySID: Option[String],
var requirements: Option[List[UnlockRequirement]],
var weaponData: Option[WeaponData]) {
def this() = this("", None, None, None, None, None, None)
}
class UnlockRequirement(
var requirementType: RequirementType,
var valueNeeded: Float,
var codeNeeded: String) {
def this() = this(Bucket, 0.0F, "")
}
class WeaponData(
var statDamage: Option[Float],
var statAccuracy: Option[Float],
var statMobility: Option[Float],
var statRange: Option[Float],
var statHandling: Option[Float]) {
def this() = this(None, None, None, None, None)
}
sealed trait RequirementType {
def name() = getClass.getSimpleName
}
object Bucket extends RequirementType
object Create {
def randomWeaponAccessory() = {
val accessory = new WeaponAccessory()
accessory.guid = "%s".format(UUID.randomUUID())
accessory.slug = randomOption(randString(10))
accessory.nameSID = randomOption(randString(25))
accessory.descriptionSID = randomOption(randString(25))
accessory.categorySID = randomOption(randString(25))
accessory.requirements = Some(
List.fill(Random.nextInt(5))(randomRequirement())
)
accessory.weaponData = randomOption(randomWeaponData())
accessory
}
private def randomRequirement() = {
val requirement = new UnlockRequirement()
requirement.requirementType = Bucket
requirement.codeNeeded = randString(5)
requirement.valueNeeded = Random.nextFloat()
requirement
}
private def randomWeaponData() = {
val weaponData = new WeaponData()
weaponData.statAccuracy = randomOption(Random.nextFloat())
weaponData.statDamage = randomOption(Random.nextFloat())
weaponData.statHandling = randomOption(Random.nextFloat())
weaponData.statMobility = randomOption(Random.nextFloat())
weaponData.statRange = randomOption(Random.nextFloat())
weaponData
}
private def randomOption[T](value: T) = {
if (Random.nextBoolean()) {
Some(value)
} else {
None
}
}
private def randString(x: Int) = Random.alphanumeric.take(x).mkString
}
view raw Items.scala hosted with ❤ by GitHub


The first candidate will be Scala Pickling. The following code pickles a List of 3000 random WeaponAccessory instances.

package me
import scala.pickling._
import json._
object Pickling {
def main(args: Array[String]) {
val items = List.fill(3000)(Create.randomWeaponAccessory())
val pckl = items.pickle
val json = pckl.value
val jsonPckl = new JSONPickle(json)
val deser = jsonPckl.unpickle[List[WeaponAccessory]]
assert(deser.size == 3000)
}
}
view raw Pickling.scala hosted with ❤ by GitHub


Unfortunately the code doesn't even compile properly. Scala Pickling uses Macros and advanced Scala compile features. Trying to compile Pickling.scala fails during compilation. Also people are encouraged to depend on a SNAPSHOT version which means you are always depending on the latest patches. When I wrote this blog post I hit this issue. Verdict: scala-pickling is very easy to use and works great for very simple stuff. As soon as your object graph gets a bit more complicated you will hit weird errors. Another problem is the lack of a non-SNAPSHOT version.

The seconds test candidate was Twitter Chill which is based on Kryo. chill-scala adds some Scala specific extensions. Your SBT project should depend on chill directly, which contains the code in chill-scala (which isn’t published separately). Even though they don’t have Scala examples in their Github documentation and I got some cryptic errors first when doing stuff wrong - I have to say this is an awesome library that works great! Also the authors reply fast on Twitter. Verdict: highly recommended!

package me
import com.twitter.chill.ScalaKryoInstantiator
import java.io.ByteArrayOutputStream
import com.esotericsoftware.kryo.io.{Input, Output}
object Chill {
def main(args: Array[String]) {
val items = List.fill(3000)(Create.randomWeaponAccessory())
val instantiator = new ScalaKryoInstantiator
instantiator.setRegistrationRequired(false)
val kryo = instantiator.newKryo()
val baos = new ByteArrayOutputStream
val output = new Output(baos, 4096)
kryo.writeObject(output, items)
val input = new Input(baos.toByteArray)
val deser = kryo.readObject(input, classOf[List[WeaponAccessory]])
assert(deser.size == 3000)
}
}
view raw Chill.scala hosted with ❤ by GitHub

SBT and faster RPM packaging

We do a lot of Scala coding nowadays and I am trying to introduce SBT as build tool to all our new Scala projects. When we deploy these applications to Amazon EC2 nodes, we use Chef Solo and the Instance User Data feature to install an RPM file. We don’t use custom AMI’s. The RPM file is hosted in S3 and made available as package via this yum plugin. Each time we build our project via our continuous integration server (Bamboo), a new RPM package is created and uploaded to S3.

It became more and more of a problem that building that particular application in Bamboo took a long time. The build plan ran for more than 10 minutes. So yesterday I spent some time to make it build a bit faster.

First of all I have to say it is pretty lame that the SBT plugin is broken in Bamboo since version 4.4.3 and no one from Atlassian is interested in fixing it since August 2013! I tried to fix the Bamboo plugin myself but Atlassian has some non-public Maven repositories so I couldn’t even build it. Given that the top four Java/Scala build tools are Ant, Maven, Gradle and SBT you could also say that Bamboo is somewhat 25% broken currently. Anyway a workaround is to use the Script Task in a Job and run SBT, which is what we do currently.

When I looked at our build there were basically two steps which took a long time. First we were creating a big one-jar (also called uber-jar sometimes). This is a single jar file that contains all compiled classes from all dependencies as well as our own classes. To create the uber-jar we used the sbt-assembly plugin which can run for a bit if you have a lot of dependencies. But actually you don’t need to have a single big jar file as you can add an entire directory to the Java classpath when starting an application. So I switched to a plugin called sbt-pack which dumps the jar files of all managed dependencies into a folder under target along with your project jar. This folder is then used later when building the RPM. Not using the sbt-assembly plugin to create a single uber-jar already saved us about 2 minutes of buildtime.

The second change was addressing creation of the actual RPM package. Previously we were using SBT native packager to assemble the RPM file. Unfortunately it was also not running very fast. Another big issue in Bamboo was that the sbt-native-packager logs some stuff on Std Error. This failed the build because Bamboo is scanning the build log for errors. (Our hack around this issue was to write a SBT task that logs 250 lines of “Build Successful” into the Bamboo log - what a mess). Today the RPM is build using fpm. On your Bamboo server you need to install fpm which is a Ruby Gem (gem install fpm). Then install Python and the fabric library.

And here is how we use fabric and fpm. In the root of your Scala project create a folder called build. Inside this folder store the following file:

#!/usr/bin/env python
import os
import os.path
import shutil
from fabric.api import *
versionNumber = ""
with open('build/version.txt', 'r') as f:
versionNumber = f.readline()
RPM_INCLUDE="projectname"
INSTALL_DIR = "/opt"
WORK_DIR = os.getcwd()
BUILD_NUMBER = os.getenv('BUILD_NUMBER', '1')
@task
def build():
""" Creates a build with an optional RPM package """
print("Starting build %s... in %s" % (BUILD_NUMBER, WORK_DIR))
# folder created by the sbt-pack plugin
pack_dir = os.path.join(WORK_DIR, 'target/pack')
# folder containing all jars
lib_dir = os.path.join(pack_dir, 'lib')
# project folder which be installed to /opt/projectname later
opt_app_folder = os.path.join(pack_dir, 'projectname')
if not os.path.exists(opt_app_folder):
print("Creating %s" % opt_app_folder)
os.makedirs(opt_app_folder)
# move all jars into the project folder
for file in os.listdir(lib_dir):
print("Moving %s to %s" % (file, opt_app_folder))
shutil.move(os.path.join(lib_dir, file), opt_app_folder)
print("Creating RPM...")
# delete old RPM files if any
for file in os.listdir(WORK_DIR):
if ".rpm" in file:
os.remove(file)
# creates an RPM using fpm, aborts if problems
out = local('fpm -a all -s dir -t rpm -C %s --vendor "VENDOR NAME HERE" --prefix %s \
--license "(C) 2011-2014, License Statement Bla Bla. All Rights Reserved." \
--url "http://www.yourcompany.se/" --maintainer "<mail@address.com>" \
--description "Project Name" \
-n "packagename" -v %s --iteration %s %s' % (pack_dir, INSTALL_DIR, versionNumber, BUILD_NUMBER, RPM_INCLUDE))
if out.failed:
abort("RPM creation failed, check logs")
view raw fabfile.py hosted with ❤ by GitHub


You probably want to adapt projectname, packagename and the fpm settings to match your own project. To invoke the script during a build create a Script task in Bamboo that executes: fab -f build/fabfile.py build. When the Script is executed from Bamboo it is looking for a file called version.txt in the build folder. The file version.txt need to be created upfront via SBT to propagate the project version to the Python script. This is what the custom rpmPrepare task does.

lazy val branchName = settingKey[String]("The name of the Github branch which will prefix the RPM")
branchName := sys.props.getOrElse("branchName", sys.env.getOrElse("branchName", "master"))
lazy val rpmPrepare = taskKey[Unit]("Executes steps which are needed before the RPM can be build")
rpmPrepare := {
val dir = Paths.get("build")
val versionFile = dir.resolve("version.txt")
Files.deleteIfExists(versionFile)
Files.createFile(versionFile)
Some(new PrintWriter(versionFile.toFile)).foreach{p => p.write("%s_%s".format(branchName.value, version.value)); p.close()}
}
view raw build.sbt hosted with ❤ by GitHub


The rpmPrepare task reuses a SettingKey called branchName which contains the name of the branch in Github. The name of the RPM package will contain the branch name, so that you can build multiple branches of the same project in Bamboo in parallel without having to worry about version clashes. The branchName Setting in SBT is retrieved via either a system property or an environment variable called “branchName”. This variable is set from Bamboo. Each build plan in Bamboo is made of individual tasks and for a task you can set individual environment variables. So just add -DbranchName=${bamboo.repository.branch.name} and Bamboo will feed in the Github branch name into the task.

So after running the Python script you will have the RPM file in the WORK_DIR folder. For running Java command-line applications we use Supervisor. Here is an example how to invoke a Main class given that the RPM installs your project in /opt/projectname.

[program:projectname]
stdout_logfile=/var/log/projectname/projectname.log
command=/usr/java/latest/bin/java -cp "/opt/projectname/*" me.MainClass
directory=/opt/projectname
autostart=true
autorestart=true
redirect_stderr=true
view raw project.ini hosted with ❤ by GitHub

Publishing from SBT to Nexus

I am pretty new to SBT. Yesterday, for the first time, we wanted to publish the jar artifact of an in-house utility library into our private Nexus repository. This is an internal Nexus repository which we use mostly in Java projects build with Maven. While the task of publishing an artifact from SBT is well documented, it was not working right away. We hit some problems. Some answers to these problems we found on Stackoverflow, but some things we needed to figure out ourselves.

To prepare your build in SBT basically do these things. Add values for the publishTo Setting and the credentials Task. I recommend using a credentials file not under version control for obvious reasons. The first thing you want to verify is that you are using the correct “realm” value, which can be either a property in the credentials file or the first argument to the constructor of the Credentials class. Use curl to figure out the correct value as explained here. Send a POST to the Nexus repository which you want to publish to without any authentication arguments. For us this was the call.

curl -X POST http://10.20.108.220:8081/nexus/content/repositories/releases -v
view raw nexus_curl.sh hosted with ❤ by GitHub


Look for the WWW-Authenticate header and use the realm value. I think the default is “Sonatype Nexus Repository Manager”.

This was a step in the right direction but we still got the following error in SBT:

[trace] Stack trace suppressed: run last *:publish for the full output.
[error] (*:publish) java.io.IOException: Access to URL http://10.20.108.220:8081/nexus/content/repositories/releases/se/foo/operations/nexustest_2.10/0.1/nexustest_2.10-0.1.pom was refused by the server: Unauthorized


Not super useful but more info is actually available in the Nexus logfiles. Make sure you set the loglevel to DEBUG via the Nexus admin GUI first, then tail nexus.log while you try to publish from SBT. Here is some output in nexus.log, basically saying that SBT did not sent a value for username and password as part of the Basic Authentication.

2014-02-12 13:03:53 DEBUG DefaultSessionManager - Unable to resolve session ID from SessionKey. Returning null to indicate a session could not be found.
2014-02-12 13:03:53 DEBUG NexusContentAuthenticationFilter - No authorization found (header or request parameter)
2014-02-12 13:03:53 DEBUG NexusContentAuthenticationFilter - No authorization found (header or request parameter)
2014-02-12 13:03:53 DEBUG NexusContentAuthenticationFilter - Attempting to authenticate Subject as Anonymous request...
And I was using the following build.sbt file:

// next line contains the error
credentials += Credentials("Sonatype Nexus Repository Manager", "10.20.108.220:8081", "username", "password")
publishTo := {
val nexus = "http://10.20.108.220:8081/nexus/"
if (version.value.trim.endsWith("SNAPSHOT"))
Some("snapshots" at nexus + "content/repositories/snapshots")
else
Some("releases" at nexus + "content/repositories/releases")
}


After running a few tests, I figured out that the second argument to the sbt.Credentials class should only be the host and must not include the port – doh! After fixing this, everything works just fine. Another thing you want to check via the Nexus admin GUI is the Access Settings of your repository. For “Deployment Policy” we have set it to “Allow Redeploy”.

Dynamic Type System Trouble

This week I really learned to appreciate my Java compiler. I learned it the hard way – by not using it. In the last game that we released (Battlefield 4) I have implemented a feature for our players which suggests 3 game items to progress on, i.e. a weapon to unlock, an assignment that should be finished etc. Our internal name for this feature is “Suggestions”. A player would not only see these 3 items but also see his own progress towards reaching the suggestion goal of each item. The code that calculates the 3 items has become quite complex since there are a lot of different item types that we can pick from and we need to match each player individually. The code is written in Python, my favorite language at this point, which uses a dynamic type system.

The “Suggestions” feature was tested thoroughly and worked quite well in production. I implemented some additional functionality on top. Players now also had the opportunity to manually pick individual items so they could see their progress in the game and on our companion website Battlelog. Unfortunately after a few weeks players complained about strange problems. These players would see completely random items being suggested to them – even with the progression totally being off. In some cases, players got items suggested that they had completed or unlocked. These errors happened completely random. Not able to reproduce in any of our test systems. But it was happening mostly to players that played the game a lot. So I started to investigate.

No unit test was broken and also a long code review did not surface any problems. Fortunately we have very short release cycles. So I added some additional logging to this functionality, which was released to production earlier this week. This finally got me something! I could see that in some rare cases the function, which calculates the suggested items of a player, returns not just 3 but more: 4, 5, 6 sometimes 9 items! I am posting you a ridiculous simplified version of the code below. Try to spot the problem.

class ProgressSuggestions(TransportModel):
def __init__(self):
self.suggestions = []
class SuggestionService(object):
def suggest(self, playerId):
current = DB.load(playerId)
currentIds = [current.sug1, current.sug2, current.sug3]
progress = ProgressSuggestions
progress.suggestions = []
for index, suggestedId in enumerate(currentIds):
suggestedItem = DB.loadItem(suggestedId)
if not suggestedItem.stillExists():
suggestedItem = self.calculateNew(playerId)
progress.suggestions.append(suggestedItem)
return progress


I should also tell you, that an instance of the SuggestionService is shared. The Service is used in an application which uses gevent. There are many Greenlets (lightweight Threads) which call the suggest method simultaneously. Ring ring – multithreading issue! The problem is in Line 10, where two parentheses are missing. Instead of creating an instance of the ProgressSuggestions class every time the suggest method is called, the code gets a reference to the ProgressSuggestions class and assigns it to a variable called progress. Then, on the first invocation, it dynamically adds a suggestions class field to that class. Something that would neither be possible nor compile in a statically typed language like Java. All Greenlets modify the same class instance, so player’s suggestions can overwrite each other. The simple fix is to create an instance of the ProgressSuggestions class as it was intended. I am surprised that this bug could live so long. In a real multithreaded application this would have affected much more players. Greenlets are only semi parallel. They must yield at a bad time to trigger this problem. Here is the correct version.

class ProgressSuggestions(TransportModel):
def __init__(self):
self.suggestions = []
class SuggestionService(object):
def suggest(self, playerId):
current = DB.load(playerId)
currentIds = [current.sug1, current.sug2, current.sug3]
progress = ProgressSuggestions()
progress.suggestions = []
for index, suggestedId in enumerate(currentIds):
suggestedItem = DB.loadItem(suggestedId)
if not suggestedItem.stillExists():
suggestedItem = self.calculateNew(playerId)
progress.suggestions.append(suggestedItem)
return progress